Files
PaperClipAI/server/src/services/headless-labels-batch.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

664 lines
19 KiB
TypeScript

import { createHash, randomUUID } from "node:crypto";
import { and, eq, inArray, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
channels,
companies,
issueBatchIdempotencyKeys,
issueRelations,
issues,
projects,
} from "@paperclipai/db";
import {
applyKvLabelMutation,
KvLabelMutationSchema,
validateAndSortBatchPlan,
type BatchCreatedTaskItem,
type BatchCreateIssuesResult,
type BoardEventView,
type IssueScope,
} from "@paperclipai/shared";
import { badRequest, conflict, unprocessable } from "../errors.js";
import {
logActivity,
publishActivity,
type ActivityPublication,
} from "./activity-log.js";
import {
attachTagLabels,
ensureChannel,
resolveAssigneeAgent,
} from "./headless-channels.js";
import {
appendBoardEvent,
assertIssueChannelScopeAccess,
assertProjectReadAccess,
enforceHeadlessScopes,
loadHeadlessIssueView,
loadHeadlessIssueViews,
publishCommittedBoardEvent,
resolveIssueByIdOrIdentifier,
resolveProjectReference,
type HeadlessActorContext,
} from "./headless-common.js";
import {
assertSchemaExists,
formatBlocksAsFencedJson,
validateSchemaBlocks,
} from "./headless-schemas.js";
function canonicalizeValue(value: unknown): unknown {
if (Array.isArray(value)) {
return value.map(canonicalizeValue);
}
if (typeof value === "object" && value !== null) {
const obj = value as Record<string, unknown>;
const sorted: Record<string, unknown> = {};
for (const key of Object.keys(obj).sort()) {
const v = obj[key];
if (v !== undefined) {
sorted[key] = canonicalizeValue(v);
}
}
return sorted;
}
return value;
}
function hashCanonicalRequest(rawInput: unknown): string {
const canonical = JSON.stringify(canonicalizeValue(rawInput));
return createHash("sha256").update(canonical).digest("hex");
}
function assertNoReservedLabelKeys(rawMutation: unknown): void {
if (!rawMutation || typeof rawMutation !== "object") return;
const mut = rawMutation as Record<string, unknown>;
if (mut.set && typeof mut.set === "object" && !Array.isArray(mut.set)) {
for (const key of Object.keys(mut.set)) {
if (key.startsWith("paperclip.")) {
throw badRequest("Label keys starting with 'paperclip.' are reserved", {
error: "reserved_label",
code: "reserved_label",
key,
});
}
}
}
if (Array.isArray(mut.unset)) {
for (const key of mut.unset) {
if (typeof key === "string" && key.startsWith("paperclip.")) {
throw badRequest("Label keys starting with 'paperclip.' are reserved", {
error: "reserved_label",
code: "reserved_label",
key,
});
}
}
}
}
export async function mutateIssueKvLabels(
db: Db,
issueRef: string,
actor: HeadlessActorContext,
rawMutation: unknown,
): Promise<{ id: string; kvLabels: Record<string, string>; cursor: string }> {
enforceHeadlessScopes(actor, { action: "label" });
assertNoReservedLabelKeys(rawMutation);
const parsed = KvLabelMutationSchema.safeParse(rawMutation);
if (!parsed.success) {
throw badRequest(
parsed.error.issues
.map((i) => `${i.path.join(".") || "$"}: ${i.message}`)
.join("; "),
{
error: "validation_error",
code: "validation_error",
issues: parsed.error.issues,
},
);
}
const target = await resolveIssueByIdOrIdentifier(db, issueRef, actor.companyId);
const publications: ActivityPublication[] = [];
let committedEvent!: BoardEventView;
const result = await db.transaction(async (tx) => {
const [locked] = await tx
.select()
.from(issues)
.where(and(eq(issues.id, target.id), eq(issues.companyId, actor.companyId)))
.for("update");
if (!locked) {
throw conflict("Issue disappeared during transaction");
}
const { channelPath } = await assertIssueChannelScopeAccess(tx, locked, actor);
if (!locked.channelId) {
enforceHeadlessScopes(actor, { action: "label" });
}
const currentKvLabels = (locked.kvLabels ?? {}) as Record<string, string>;
const applied = applyKvLabelMutation(currentKvLabels, parsed.data);
if (!applied.ok) {
throw conflict("Label Compare-And-Swap precondition failed", {
error: "label_conflict",
code: "label_conflict",
conflictingKeys: applied.conflictingKeys,
currentLabels: currentKvLabels,
});
}
const now = new Date();
await tx
.update(issues)
.set({
kvLabels: applied.labels,
updatedAt: now,
})
.where(eq(issues.id, locked.id));
if (locked.channelId) {
await tx
.update(channels)
.set({ lastActivityAt: now, updatedAt: now })
.where(eq(channels.id, locked.channelId));
}
await logActivity(
tx as unknown as Db,
{
companyId: actor.companyId,
actorType: actor.principalType === "agent" ? "agent" : "user",
actorId:
actor.principalType === "agent"
? actor.agentId!
: (actor.userId ?? "local-board"),
agentId: actor.agentId,
issueId: locked.id,
responsibleUserIdOverride: actor.responsibleUserId,
action: "issue.kv_labels_updated",
entityType: "issue",
entityId: locked.id,
details: {
previous: currentKvLabels,
current: applied.labels,
},
},
publications,
);
committedEvent = await appendBoardEvent(tx, {
companyId: actor.companyId,
type: "labels.changed",
channelId: locked.channelId,
channelPath,
issueId: locked.id,
identifier: locked.identifier ?? locked.id,
actor,
payload: {
previous: currentKvLabels,
current: applied.labels,
},
});
return {
id: locked.id,
kvLabels: applied.labels,
cursor: committedEvent.cursor,
};
});
for (const pub of publications) {
publishActivity(pub);
}
publishCommittedBoardEvent(committedEvent);
return result;
}
export async function createBatchIssuesPlan(
db: Db,
companyId: string,
actor: HeadlessActorContext,
rawInput: unknown,
): Promise<BatchCreateIssuesResult> {
const plan = validateAndSortBatchPlan(rawInput);
if (!plan.ok) {
const { ok: _ok, message: _msg, ...planDetails } = plan;
throw unprocessable(plan.message, {
error: plan.code,
...planDetails,
});
}
enforceHeadlessScopes(actor, {
action: "tasks.create",
channelPath: plan.channel,
});
const requestHash = hashCanonicalRequest(rawInput);
const publications: ActivityPublication[] = [];
const committedEvents: BoardEventView[] = [];
const result = await db.transaction(async (tx) => {
if (plan.idempotencyKey) {
// Serialize concurrent requests sharing the same (companyId, idempotencyKey)
// before reading or writing any tasks so losers never commit duplicates.
await tx.execute(
sql`SELECT pg_advisory_xact_lock(hashtext(${companyId}), hashtext(${plan.idempotencyKey}))`,
);
const [existingIdemp] = await tx
.select()
.from(issueBatchIdempotencyKeys)
.where(
and(
eq(issueBatchIdempotencyKeys.companyId, companyId),
eq(issueBatchIdempotencyKeys.idempotencyKey, plan.idempotencyKey),
),
)
.limit(1);
if (existingIdemp) {
if (existingIdemp.requestHash === requestHash) {
return {
...(existingIdemp.responsePayload as unknown as BatchCreateIssuesResult),
idempotentReplay: true,
};
}
throw conflict("Idempotency key already used with a different plan payload", {
error: "idempotency_conflict",
code: "idempotency_conflict",
idempotencyKey: plan.idempotencyKey,
});
}
}
const channel = plan.channel
? await ensureChannel(tx, companyId, actor, { path: plan.channel })
: null;
let planDefaultProjectId: string | null = channel?.defaultProjectId ?? null;
if (plan.projectId !== undefined) {
planDefaultProjectId =
plan.projectId === null
? null
: await resolveProjectReference(tx, companyId, plan.projectId, actor);
} else if (planDefaultProjectId) {
await assertProjectReadAccess(tx, companyId, planDefaultProjectId, actor);
}
// Pre-resolve external dependencies
const externalIssueByRef = new Map<string, typeof issues.$inferSelect>();
for (const task of plan.tasks) {
for (const extRef of task.externalNeeds) {
if (!externalIssueByRef.has(extRef)) {
const extIssue = await resolveIssueByIdOrIdentifier(
tx,
extRef,
companyId,
);
await assertIssueChannelScopeAccess(tx, extIssue, actor);
externalIssueByRef.set(extRef, extIssue);
}
}
}
// Validate blocks, resultSchema, projectId, and assignees for all tasks before writing
const resolvedTaskConfigs: Array<{
projectId: string | null;
assigneeAgentId: string | null;
resultSchemaRef: string | null;
}> = [];
for (const task of plan.tasks) {
await validateSchemaBlocks(tx, companyId, task.blocks);
const resultSchemaRef = task.resultSchema
? await assertSchemaExists(tx, companyId, task.resultSchema)
: null;
let taskProjectId = planDefaultProjectId;
if (task.projectId === null) {
taskProjectId = null;
} else if (task.projectId !== undefined) {
taskProjectId = await resolveProjectReference(
tx,
companyId,
task.projectId,
actor,
);
}
const assigneeAgentId = await resolveAssigneeAgent(tx, companyId, {
assigneeAgentId: task.assigneeAgentId,
for: task.for,
});
resolvedTaskConfigs.push({
projectId: taskProjectId,
assigneeAgentId,
resultSchemaRef,
});
}
// Atomically allocate issue numbers for the batch
const now = new Date();
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}) + ${plan.tasks.length}`,
updatedAt: now,
})
.where(eq(companies.id, companyId))
.returning({
issueCounter: companies.issueCounter,
issuePrefix: companies.issuePrefix,
});
const firstIssueNumber = companyRow!.issueCounter - plan.tasks.length + 1;
const createdByKey = new Map<string, typeof issues.$inferSelect>();
const createdRows: Array<typeof issues.$inferSelect> = [];
const pendingEvents: Array<{
issueId: string;
identifier: string;
key: string | null;
type: "task.created" | "task.ready";
payload: Record<string, unknown>;
isTaskCreated?: boolean;
}> = [];
const cursorByIssueId = new Map<string, string>();
const keyByIssueId = new Map<string, string | null>();
// Pre-fetch private project visibility for all referenced projects
const referencedProjectIds = Array.from(
new Set(
resolvedTaskConfigs
.map((c) => c.projectId)
.filter((id): id is string => Boolean(id)),
),
);
const privateProjectIds = new Set<string>();
if (referencedProjectIds.length > 0) {
const projRows = await tx
.select({ id: projects.id, visibility: projects.visibility })
.from(projects)
.where(
and(
eq(projects.companyId, companyId),
inArray(projects.id, referencedProjectIds),
),
);
for (const p of projRows) {
if (p.visibility === "private") privateProjectIds.add(p.id);
}
}
for (let i = 0; i < plan.tasks.length; i += 1) {
const task = plan.tasks[i]!;
const cfg = resolvedTaskConfigs[i]!;
const issueNumber = firstIssueNumber + i;
const identifier = `${companyRow!.issuePrefix}-${issueNumber}`;
const scope: IssueScope =
(task.board ?? plan.board) ? "board" : channel ? "channel" : "board";
const description =
task.description !== null
? task.description
: task.blocks.length > 0
? formatBlocksAsFencedJson(task.blocks)
: null;
const taskVisibility: "open" | "private" =
channel?.visibility === "private" ||
(cfg.projectId !== null && privateProjectIds.has(cfg.projectId))
? "private"
: "open";
const taskIssueId = randomUUID();
const privacyRootIssueId = taskVisibility === "private" ? taskIssueId : null;
const [inserted] = await tx
.insert(issues)
.values({
id: taskIssueId,
companyId,
projectId: cfg.projectId,
channelId: channel?.id ?? null,
visibility: taskVisibility,
privacyRootIssueId,
title: task.title,
description,
status: "todo",
scope,
priority: task.priority,
assigneeAgentId: cfg.assigneeAgentId,
createdByAgentId: actor.agentId,
createdByUserId: actor.agentId ? null : actor.userId,
createdByProfile: actor.actorProfile,
responsibleUserId: actor.responsibleUserId,
kvLabels: task.labels,
schemaBlocks: task.blocks,
resultSchemaRef: cfg.resultSchemaRef,
issueNumber,
identifier,
originKind: "manual",
createdAt: now,
updatedAt: now,
})
.returning();
createdRows.push(inserted!);
keyByIssueId.set(inserted!.id, task.key);
if (task.key) {
createdByKey.set(task.key, inserted!);
}
if (task.tagLabels.length > 0) {
await attachTagLabels(tx, companyId, inserted!.id, task.tagLabels);
}
const blockerIds: string[] = [];
let hasOpenBlocker = false;
for (const localKey of task.localNeeds) {
const blocker = createdByKey.get(localKey)!;
blockerIds.push(blocker.id);
hasOpenBlocker = true;
}
for (const extRef of task.externalNeeds) {
const ext = externalIssueByRef.get(extRef)!;
if (!blockerIds.includes(ext.id)) {
blockerIds.push(ext.id);
}
if (ext.status !== "done" && ext.status !== "cancelled") {
hasOpenBlocker = true;
}
}
if (blockerIds.length > 0) {
await tx
.insert(issueRelations)
.values(
blockerIds.map((blockerId) => ({
companyId,
issueId: blockerId,
relatedIssueId: inserted!.id,
type: "blocks" as const,
createdByAgentId: actor.agentId,
createdByUserId: actor.agentId ? null : actor.userId,
})),
)
.onConflictDoNothing({
target: [
issueRelations.companyId,
issueRelations.issueId,
issueRelations.relatedIssueId,
issueRelations.type,
],
});
}
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: "issue.created",
entityType: "issue",
entityId: inserted!.id,
details: {
identifier,
channel: channel?.path ?? null,
batchKey: task.key,
blockedByIssueIds: blockerIds,
},
},
publications,
);
pendingEvents.push({
issueId: inserted!.id,
identifier,
key: task.key ?? null,
type: "task.created",
isTaskCreated: true,
payload: {
key: task.key,
title: task.title,
...(description ? { description: description.slice(0, 4000) } : {}),
blockedByIssueIds: blockerIds,
},
});
if (!hasOpenBlocker && cfg.assigneeAgentId === null) {
pendingEvents.push({
issueId: inserted!.id,
identifier,
key: task.key ?? null,
type: "task.ready",
payload: { key: task.key },
});
}
}
if (channel) {
await tx
.update(channels)
.set({ lastActivityAt: now, updatedAt: now })
.where(eq(channels.id, channel.id));
}
for (const evInput of pendingEvents) {
const evt = await appendBoardEvent(tx, {
companyId,
type: evInput.type,
channelId: channel?.id ?? null,
channelPath: channel?.path ?? null,
issueId: evInput.issueId,
identifier: evInput.identifier,
actor,
payload: evInput.payload,
});
committedEvents.push(evt);
cursorByIssueId.set(evInput.issueId, evt.cursor);
}
const issueViews = await loadHeadlessIssueViews(tx, createdRows);
const items: BatchCreatedTaskItem[] = issueViews.map((issueView) => {
const cursor = cursorByIssueId.get(issueView.id) ?? issueView.cursor;
return {
key: keyByIssueId.get(issueView.id) ?? null,
id: issueView.id,
identifier: issueView.identifier,
cursor,
issue: {
...issueView,
cursor,
},
};
});
const latestCursor =
committedEvents[committedEvents.length - 1]?.cursor ?? "evt_0";
const batchResult: BatchCreateIssuesResult = {
tasks: items,
cursor: latestCursor,
idempotentReplay: false,
};
if (plan.idempotencyKey) {
const [insertedKey] = await tx
.insert(issueBatchIdempotencyKeys)
.values({
companyId,
idempotencyKey: plan.idempotencyKey,
requestHash,
responsePayload: batchResult as unknown as Record<string, unknown>,
})
.onConflictDoNothing({
target: [
issueBatchIdempotencyKeys.companyId,
issueBatchIdempotencyKeys.idempotencyKey,
],
})
.returning();
if (!insertedKey) {
const [raced] = await tx
.select()
.from(issueBatchIdempotencyKeys)
.where(
and(
eq(issueBatchIdempotencyKeys.companyId, companyId),
eq(issueBatchIdempotencyKeys.idempotencyKey, plan.idempotencyKey),
),
)
.limit(1);
if (raced && raced.requestHash === requestHash) {
return {
...(raced.responsePayload as unknown as BatchCreateIssuesResult),
idempotentReplay: true,
};
}
throw conflict(
"Idempotency key already used with a different plan payload",
{
error: "idempotency_conflict",
code: "idempotency_conflict",
idempotencyKey: plan.idempotencyKey,
},
);
}
}
return batchResult;
});
if (!result.idempotentReplay) {
for (const pub of publications) {
publishActivity(pub);
}
for (const evt of committedEvents) {
publishCommittedBoardEvent(evt);
}
}
return result;
}