feat(issues): add issues.scope surface visibility foundation

Introduce `issues.scope` (`board` | `channel` | `agent` | `chat`) to unify
surface visibility across human board tasks, 1:1 Agent Chats, agent-managed
operational tasks, and upcoming headless channels without introducing separate
issue types.

- Add `scope` column, check constraints, and composite indexes to `issues` with
  an online-compatible migration (`0511_pale_kronos.sql`) that backfills
  existing 1:1 conversations (`chat`) and automated/agent-created tasks (`agent`)
- Automatically derive default `scope` in `issueService.create` when omitted so
  existing Agent Chats, routines, Slack tasks, and chat-to-board handoffs remain
  100% backwards-compatible
- Consolidate list, count, and Mine visibility predicates onto `issues.scope`
  while isolating `channel` and `chat` scopes from default board views

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-11-30 18:11:55 -06:00
1 parent fb6632530d
commit a6b22197b4
18 files changed
+953 -20

No files matched your search

@@ -0,0 +1,403 @@
import { randomUUID } from "node:crypto";
import { eq, sql } from "drizzle-orm";
import request from "supertest";
import { describe, expect, it } from "vitest";
import {
activityLog,
agents,
authUsers,
heartbeatRuns,
issueComments,
issues,
issueThreadInteractions,
projects,
} from "@paperclipai/db";
import {
createIssueSchema,
deriveDefaultIssueScope,
updateIssueSchema,
} from "@paperclipai/shared";
import { issueRoutes } from "../routes/issues.js";
import { issueService } from "../services/issues.js";
import { issueThreadInteractionService } from "../services/issue-thread-interactions.js";
import { PaperclipRunnerToolAuthority } from "../services/native-runtime/paperclip-runner-tool-authority.js";
import {
describeEmbeddedPostgres,
resetCompanyIssueFixtures,
routeApp,
seedCompanyWithBoardAccess,
useEmbeddedPostgres,
} from "./helpers/route-test-harness.js";
describe("deriveDefaultIssueScope & validators", () => {
it("derives default scope from conversation, explicit scope, channel, board handoff, and creator", () => {
expect(
deriveDefaultIssueScope({
createdByUserId: "user-1",
originKind: "manual",
}),
).toBe("board");
expect(
deriveDefaultIssueScope({
conversationAgentId: "agent-1",
scope: "board",
createdByUserId: "user-1",
}),
).toBe("chat");
expect(
deriveDefaultIssueScope({
scope: "channel",
createdByAgentId: "agent-1",
}),
).toBe("channel");
expect(
deriveDefaultIssueScope({
channelId: "channel-1",
createdByUserId: "user-1",
}),
).toBe("channel");
expect(
deriveDefaultIssueScope({
isExplicitBoardHandoff: true,
createdByAgentId: "agent-1",
}),
).toBe("board");
expect(
deriveDefaultIssueScope({
createdByAgentId: "agent-1",
originKind: "manual",
}),
).toBe("agent");
expect(
deriveDefaultIssueScope({
createdByUserId: "user-1",
originKind: "routine_execution",
}),
).toBe("agent");
});
it("validates optional scope on createIssueSchema and updateIssueSchema", () => {
expect(
createIssueSchema.parse({ title: "Board task", scope: "board" }).scope,
).toBe("board");
expect(
createIssueSchema.parse({ title: "Channel post", scope: "channel" }).scope,
).toBe("channel");
expect(
createIssueSchema.safeParse({ title: "Bad scope", scope: "unknown" }).success,
).toBe(false);
expect(updateIssueSchema.parse({ scope: "board" }).scope).toBe("board");
expect(updateIssueSchema.safeParse({ scope: "invalid" }).success).toBe(false);
});
});
describeEmbeddedPostgres("issues.scope visibility and lifecycle", () => {
const ctx = useEmbeddedPostgres("paperclip-issue-scope-", {
resetEach: async (db) => {
await db.delete(activityLog);
await db.delete(issueThreadInteractions);
await db.delete(issueComments);
await db.delete(heartbeatRuns);
await db.delete(issues);
await db.delete(projects);
await db.delete(agents);
await resetCompanyIssueFixtures(db);
await db.delete(authUsers);
},
});
it("assigns scopes automatically, protects 1:1 chats, and defaults chat-to-project handoffs to board", async () => {
const { companyId, userId, actor } = await seedCompanyWithBoardAccess(ctx.db, "Issue Scope Chat");
await ctx.db
.insert(authUsers)
.values({ id: userId, name: "Board User", email: `${userId}@example.test`, createdAt: new Date(), updatedAt: new Date() })
.onConflictDoNothing();
const [agent] = await ctx.db
.insert(agents)
.values({ companyId, name: "Coordinator", role: "engineer", adapterType: "process" })
.returning();
const [project] = await ctx.db
.insert(projects)
.values({ companyId, name: "Web App" })
.returning();
const svc = issueService(ctx.db);
const chat = await svc.create(companyId, {
title: "Chat with Coordinator",
conversationAgentId: agent!.id,
conversationUserId: userId,
assigneeAgentId: agent!.id,
conversationState: "waiting",
status: "in_review",
createdByUserId: userId,
});
expect(chat.scope).toBe("chat");
await expect(
svc.create(companyId, {
title: "Invalid conversation scope",
conversationAgentId: agent!.id,
conversationUserId: `other-${randomUUID()}`,
assigneeAgentId: agent!.id,
conversationState: "waiting",
status: "in_review",
scope: "board",
}),
).rejects.toMatchObject({ status: 422 });
await expect(
svc.update(chat.id, { scope: "board" }),
).rejects.toMatchObject({ status: 422 });
expect((await svc.getById(chat.id))?.scope).toBe("chat");
// Conversation stays excluded from default list, Mine, and unreadInboxIssueIds,
// while still discoverable via explicit `q` search, `scope=chat`, or `issueIds`.
expect((await svc.list(companyId)).map((row) => row.id)).not.toContain(chat.id);
expect(await svc.count(companyId)).toBe(0);
expect(
(await svc.list(companyId, { touchedByUserId: userId })).map((row) => row.id),
).not.toContain(chat.id);
expect(
await svc.unreadInboxIssueIds(companyId, userId, sql<boolean>`true`),
).not.toContain(chat.id);
expect(
(await svc.list(companyId, { q: "Chat with Coordinator" })).map((row) => row.id),
).toContain(chat.id);
expect(
(await svc.list(companyId, { scope: "chat" })).map((row) => row.id),
).toContain(chat.id);
expect(
(await svc.list(companyId, { issueIds: [chat.id] })).map((row) => row.id),
).toContain(chat.id);
// Chat-to-project handoff via suggest_tasks gets scope = 'board'.
const interaction = await issueThreadInteractionService(ctx.db).create(
chat,
{
kind: "suggest_tasks",
payload: {
version: 1,
tasks: [
{
clientKey: "handoff-1",
title: "Ship scope foundation",
projectId: project!.id,
assigneeAgentId: agent!.id,
},
],
},
},
{ agentId: agent!.id },
);
const accepted = await issueThreadInteractionService(ctx.db).acceptSuggestedTasks(
chat,
interaction.id,
{},
{ userId, suggestedTaskEffectsAuthorized: true },
);
const suggestedTaskId = accepted.createdIssues[0]!.id;
const suggestedTask = await svc.getById(suggestedTaskId);
expect(suggestedTask?.scope).toBe("board");
// Chat-to-project handoff via native create_task from a conversation run gets scope = 'board'.
const [chatRun] = await ctx.db
.insert(heartbeatRuns)
.values({
companyId,
agentId: agent!.id,
status: "running",
runtimeMode: "native",
nativeIssueId: chat.id,
responsibleUserId: userId,
contextSnapshot: {
issueId: chat.id,
conversationMode: true,
conversationSessionGeneration: chat.conversationSessionGeneration,
},
})
.returning();
await ctx.db
.update(issues)
.set({ executionRunId: chatRun!.id })
.where(eq(issues.id, chat.id));
const authority = new PaperclipRunnerToolAuthority(ctx.db, {
companyId,
agentId: agent!.id,
issueId: chat.id,
runId: chatRun!.id,
});
const nativeHandoff = (await authority.execute({
tool: "create_task",
callId: randomUUID(),
arguments: {
idempotencyKey: "native-chat-handoff",
title: "Native chat handoff task",
projectId: project!.id,
},
})) as { task: { id: string } };
const nativeTask = await svc.getById(nativeHandoff.task.id);
expect(nativeTask?.scope).toBe("board");
// Both handoffs appear in default list even with includeAgentCreatedTasks: false.
const app = routeApp(ctx.db, actor, issueRoutes);
const boardRes = await request(app)
.get(`/api/companies/${companyId}/issues?includeAgentCreatedTasks=false`)
.expect(200);
expect(boardRes.body.map((row: { id: string }) => row.id).sort()).toEqual(
[suggestedTaskId, nativeHandoff.task.id].sort(),
);
expect(boardRes.body.every((row: { scope: string }) => row.scope === "board")).toBe(true);
});
it("isolates channel issues from default lists and Mine, filters by scope, and promotes via update", async () => {
const { companyId, userId, actor } = await seedCompanyWithBoardAccess(ctx.db, "Issue Scope Channel");
const svc = issueService(ctx.db);
const boardTask = await svc.create(companyId, {
title: "Board task",
status: "todo",
createdByUserId: userId,
});
const channelPost = await svc.create(companyId, {
title: "Deploy v1.2.3",
status: "backlog",
scope: "channel",
createdByUserId: userId,
});
const agentTask = await svc.create(companyId, {
title: "Routine audit",
status: "todo",
originKind: "routine_execution",
responsibleUserId: userId,
});
expect(boardTask.scope).toBe("board");
expect(channelPost.scope).toBe("channel");
expect(agentTask.scope).toBe("agent");
// Default list includes board + agent, excludes channel.
const defaultList = await svc.list(companyId);
expect(defaultList.map((row) => row.id).sort()).toEqual(
[boardTask.id, agentTask.id].sort(),
);
expect(await svc.count(companyId)).toBe(2);
// Mine / unreadInboxIssueIds exclude channel even when created by userId.
expect(
(await svc.list(companyId, { touchedByUserId: userId })).map((row) => row.id),
).toEqual([boardTask.id]);
expect(
await svc.unreadInboxIssueIds(companyId, userId, sql<boolean>`true`),
).not.toContain(channelPost.id);
// Explicit scope='channel' or issueIds returns the channel issue.
expect(
(await svc.list(companyId, { scope: "channel" })).map((row) => row.id),
).toEqual([channelPost.id]);
expect(
(await svc.list(companyId, { issueIds: [channelPost.id] })).map((row) => row.id),
).toEqual([channelPost.id]);
expect(
(await svc.list(companyId, { scope: "board,channel" })).map((row) => row.id).sort(),
).toEqual([boardTask.id, channelPost.id].sort());
const app = routeApp(ctx.db, actor, issueRoutes);
const channelRes = await request(app)
.get(`/api/companies/${companyId}/issues?scope=channel`)
.expect(200);
expect(channelRes.body.map((row: { id: string }) => row.id)).toEqual([channelPost.id]);
expect(channelRes.body[0].scope).toBe("channel");
const multiRes = await request(app)
.get(`/api/companies/${companyId}/issues?scope=board,agent&view=compact`)
.expect(200);
expect(multiRes.body.map((row: { id: string }) => row.id).sort()).toEqual(
[boardTask.id, agentTask.id].sort(),
);
expect(multiRes.body.map((row: { scope: string }) => row.scope).sort()).toEqual([
"agent",
"board",
]);
await request(app)
.get(`/api/companies/${companyId}/issues?scope=bogus`)
.expect(400);
// Promote channel item to board via PATCH /issues/:id.
const promoted = await request(app)
.patch(`/api/issues/${channelPost.id}`)
.send({ scope: "board", status: "todo" })
.expect(200);
expect(promoted.body.scope).toBe("board");
expect(promoted.body.status).toBe("todo");
expect(
(await svc.list(companyId, { includeAgentCreatedTasks: false })).map((row) => row.id).sort(),
).toEqual([boardTask.id, channelPost.id].sort());
});
it("handles includeAgentCreatedTasks=false with creationVisibilityUserId and includeAgentCreatedTasks=true", async () => {
const { companyId, userId } = await seedCompanyWithBoardAccess(ctx.db, "Issue Scope Agent");
const [agent] = await ctx.db
.insert(agents)
.values({ companyId, name: "Worker", role: "engineer", adapterType: "process" })
.returning();
const svc = issueService(ctx.db);
const boardTask = await svc.create(companyId, {
title: "Human task",
status: "todo",
createdByUserId: userId,
});
const agentTask = await svc.create(companyId, {
title: "Agent subtask",
status: "todo",
createdByAgentId: agent!.id,
});
const touchedAgentTask = await svc.create(companyId, {
title: "Touched agent task",
status: "todo",
createdByAgentId: agent!.id,
});
await svc.addComment(touchedAgentTask.id, "Human follow-up", { userId });
const channelTask = await svc.create(companyId, {
title: "Touched channel post",
status: "backlog",
scope: "channel",
createdByUserId: userId,
});
await svc.addComment(channelTask.id, "Channel reply", { userId });
expect(
(await svc.list(companyId, { includeAgentCreatedTasks: false })).map((row) => row.id),
).toEqual([boardTask.id]);
// With creationVisibilityUserId, user-touched agent tasks are included,
// while untouched agent tasks and channel tasks stay excluded.
expect(
(
await svc.list(companyId, {
includeAgentCreatedTasks: false,
creationVisibilityUserId: userId,
})
)
.map((row) => row.id)
.sort(),
).toEqual([boardTask.id, touchedAgentTask.id].sort());
// includeAgentCreatedTasks: true includes both board and agent, still excludes channel.
expect(
(await svc.list(companyId, { includeAgentCreatedTasks: true }))
.map((row) => row.id)
.sort(),
).toEqual([boardTask.id, agentTask.id, touchedAgentTask.id].sort());
});
});
@@ -3,7 +3,7 @@ import { eq, sql } from "drizzle-orm";
import request from "supertest";
import { expect, it } from "vitest";
import { activityLog, agents, authUsers, chatConversations, chatEndpoints, chatMessageLinks, issueComments, issueReadStates, issues, issueThreadInteractions, toolApplications, toolConnections } from "@paperclipai/db";
import { isAgentCreatedIssue } from "@paperclipai/shared";
import { deriveDefaultIssueScope, isAgentCreatedIssue } from "@paperclipai/shared";
import { issueRoutes } from "../routes/issues.js";
import { issueService } from "../services/issues.js";
import { issueThreadInteractionService } from "../services/issue-thread-interactions.js";
@@ -39,7 +39,7 @@ describeEmbeddedPostgres("issue creation visibility", () => {
{ id: randomUUID(), companyId, title: "Visibility manually run routine", createdByUserId: userId, originKind: "routine_execution" },
];
await ctx.db.insert(issues).values([
...rows.map((row, index) => ({ ...row, status: "todo", updatedAt: new Date(2026, 9, 13, 0, index) })),
...rows.map((row, index) => ({ ...row, scope: deriveDefaultIssueScope(row), status: "todo", updatedAt: new Date(2026, 9, 13, 0, index) })),
{ companyId: other.companyId, title: "Visibility other company", createdByUserId: other.userId },
{ companyId, title: "Visibility private task", createdByUserId: other.userId, visibility: "private" },
]);
@@ -101,7 +101,7 @@ describeEmbeddedPostgres("issue creation visibility", () => {
const { companyId, userId, actor } = await seedCompanyWithBoardAccess(ctx.db, "Inbox participation");
const ids = Object.fromEntries(["scheduled", "commented", "assigned", "manual", "read", "touched", "channelScheduled", "channelCommented", "channelManual"].map((name) => [name, randomUUID()]));
await ctx.db.insert(issues).values(Object.entries(ids).map(([name, id]) => ({
id, companyId, title: `Participation ${name}`, status: "todo", originKind: name.startsWith("channel") ? "chat_channel" : "routine_execution",
id, companyId, title: `Participation ${name}`, status: "todo", scope: "agent" as const, originKind: name.startsWith("channel") ? "chat_channel" : "routine_execution",
responsibleUserId: userId,
assigneeUserId: name === "assigned" ? userId : null,
createdByUserId: name === "manual" || name === "channelManual" ? userId : null,
@@ -184,7 +184,7 @@ describeEmbeddedPostgres("issue creation visibility", () => {
it("admits open addressed requests and removes that reason when they resolve", async () => {
const { companyId, userId, actor } = await seedCompanyWithBoardAccess(ctx.db, "Human requests");
const ids = Object.fromEntries(["question", "confirmation", "otherUser", "creatorExcluded", "private"].map((name) => [name, randomUUID()]));
await ctx.db.insert(issues).values(Object.entries(ids).map(([name, id]) => ({ id, companyId, title: name, status: "todo", originKind: "chat_channel", visibility: name === "private" ? "private" : "open", createdAt: new Date("2026-01-01") })));
await ctx.db.insert(issues).values(Object.entries(ids).map(([name, id]) => ({ id, companyId, title: name, status: "todo", scope: "agent" as const, originKind: "chat_channel", visibility: name === "private" ? "private" : "open", createdAt: new Date("2026-01-01") })));
const requests = await ctx.db.insert(issueThreadInteractions).values(Object.entries(ids).map(([name, issueId]) => ({
companyId, issueId, kind: name === "confirmation" ? "request_confirmation" : "ask_user_questions",
addresseeUserId: name === "otherUser" ? "someone-else" : userId,
@@ -292,7 +292,7 @@ describeEmbeddedPostgres("issue creation visibility", () => {
const names = ["historical", "done", "cancelled", "current", "authorization"];
const ids = Object.fromEntries(names.map((name) => [name, randomUUID()]));
await ctx.db.insert(issues).values(names.map((name) => ({
id: ids[name]!, companyId, title: name, originKind: "chat_channel",
id: ids[name]!, companyId, title: name, scope: "agent" as const, originKind: "chat_channel",
status: name === "done" || name === "cancelled" ? name : "todo",
createdAt: new Date("2026-01-01"), updatedAt: new Date("2026-01-01"),
})));
+38
View File
@@ -148,6 +148,7 @@ import {
linkIssueApprovalSchema,
issueDocumentKeySchema,
ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY,
ISSUE_SCOPES,
ISSUE_WATCHDOG_DISCOVERY_KINDS,
TASK_WATCHDOG_PRODUCT_BUG_ORIGIN_KIND,
ONBOARDING_FIRST_TASK_ORIGIN_KIND,
@@ -3071,6 +3072,7 @@ function toCompactIssue(issue: any): CompactIssue {
title: issue.title,
description: issue.description,
status: issue.status,
...(issue.scope !== undefined ? { scope: issue.scope } : {}),
workMode: issue.workMode,
priority: issue.priority,
reviewPolicy: issue.reviewPolicy,
@@ -3445,6 +3447,30 @@ function parseIssueListUuidQueryParams(
return { ok: true, values };
}
function parseIssueListScopeQueryParam(
raw: unknown,
): { ok: true; value: string | undefined } | { ok: false; error: string } {
if (raw === undefined) return { ok: true, value: undefined };
const entries = Array.isArray(raw) ? raw : typeof raw === "string" ? [raw] : null;
if (!entries || entries.some((entry) => typeof entry !== "string")) {
return { ok: false, error: `scope must be one of ${ISSUE_SCOPES.join(", ")}` };
}
const scopes = [
...new Set(
entries
.flatMap((entry) => entry.split(","))
.map((scope) => scope.trim())
.filter(Boolean),
),
];
for (const scope of scopes) {
if (!ISSUE_SCOPES.includes(scope as (typeof ISSUE_SCOPES)[number])) {
return { ok: false, error: `Invalid issue scope '${scope}'; expected one of ${ISSUE_SCOPES.join(", ")}` };
}
}
return { ok: true, value: scopes.length > 0 ? scopes.join(",") : undefined };
}
async function coordinateIssueListGet(input: {
req: Request;
companyId: string;
@@ -8862,6 +8888,11 @@ export function issueRoutes(
let assigneeAgentId: string | null | undefined;
const rawUpdatedSince = req.query.updatedSince as string | undefined;
const rawUpdatedBefore = req.query.updatedBefore as string | undefined;
const scopeQuery = parseIssueListScopeQueryParam(req.query.scope);
if (!scopeQuery.ok) {
res.status(400).json({ error: scopeQuery.error });
return;
}
if (
assigneeUserFilterRaw === "me" &&
@@ -9010,6 +9041,7 @@ export function issueRoutes(
attention: attention === "blocked" ? "blocked" : undefined,
status: req.query.status as string | string[] | undefined,
displayStatus: req.query.displayStatus as string | string[] | undefined,
scope: scopeQuery.value,
assigneeAgentId,
participantAgentId: uuidFilters.participantAgentId,
assigneeUserId,
@@ -9188,12 +9220,18 @@ export function issueRoutes(
return;
}
const countUuidFilters = countUuidQuery.values;
const countScopeQuery = parseIssueListScopeQueryParam(req.query.scope);
if (!countScopeQuery.ok) {
res.status(400).json({ error: countScopeQuery.error });
return;
}
const blockedCountFilters = {
readCondition: await issueReadSqlCondition(db, req.actor),
attention: "blocked",
status: req.query.status as string | string[] | undefined,
displayStatus: req.query.displayStatus as string | string[] | undefined,
scope: countScopeQuery.value,
assigneeAgentId: req.query.assigneeAgentId as string | undefined,
participantAgentId: countUuidFilters.participantAgentId,
assigneeUserId: req.query.assigneeUserId as string | undefined,
@@ -5740,6 +5740,7 @@ export function issueThreadInteractionService(
conversationId: sourceConversation.id,
sessionGeneration: sourceConversation.conversationSessionGeneration,
} } : {}),
...(sourceConversation && !parentIssueId ? { scope: "board" as const, isExplicitBoardHandoff: true } : {}),
} satisfies Parameters<ReturnType<typeof issueService>["createChild"]>[1];
const service = issueService(tx as unknown as Db);
// A nested suggestion may be placed beside its suggested parent, under
+7 -2
View File
@@ -1,5 +1,5 @@
import { nonIdleSlackIssueCondition } from "./slack-conversation-state.js";
import { and, isNull, isNotNull, or, type SQL } from "drizzle-orm";
import { and, isNull, isNotNull, ne, or, type SQL } from "drizzle-orm";
import { issues } from "@paperclipai/db";
export function visibleIssueCondition(): SQL {
@@ -10,9 +10,14 @@ export function visibleIssueSql(alias = "issues") {
return `"${alias}"."hidden_at" IS NULL AND "${alias}"."harness_kind" IS NULL`;
}
/** Default task lists and Mine exclude standing 1:1 chats and channel streams. */
export function nonChatAndChannelIssueCondition(): SQL {
return and(ne(issues.scope, "chat"), ne(issues.scope, "channel"), isNull(issues.conversationAgentId))!;
}
/** Work queues and execution totals omit persistent conversation containers. */
export function executionIssueCondition(): SQL {
return and(visibleIssueCondition(), isNull(issues.conversationAgentId), nonIdleSlackIssueCondition())!;
return and(visibleIssueCondition(), ne(issues.scope, "chat"), isNull(issues.conversationAgentId), nonIdleSlackIssueCondition())!;
}
export function attentionIssueCondition(includeConversations = false): SQL {
+65 -9
View File
@@ -161,14 +161,17 @@ import type {
IssueBlockedInboxAttention,
IssueBlockedInboxIssueRef,
IssueRelationIssueSummary,
IssueScope,
IssueWatchdogSummary,
LowTrustBoundary,
SuccessfulRunHandoffState,
} from "@paperclipai/shared";
import {
clampIssueRequestDepth,
deriveDefaultIssueScope,
extractAgentMentionIds,
extractProjectMentionIds,
ISSUE_SCOPES,
issueCommentAuthorTypeSchema,
issueCommentMetadataSchema,
issueCommentPresentationSchema,
@@ -266,7 +269,7 @@ import {
type IssueGraphLivenessInput,
type IssueLivenessFinding,
} from "./recovery/issue-graph-liveness.js";
import { visibleIssueCondition } from "./issue-visibility.js";
import { nonChatAndChannelIssueCondition, visibleIssueCondition } from "./issue-visibility.js";
import { finalizeStatusCardsForStalledGeneration } from "./status-card-finalization.js";
import { finalizeSummarySlotsForTerminalIssue } from "./summary-slot-finalization.js";
import {
@@ -1877,6 +1880,18 @@ export type IssueListPhase =
| "candidates" | "query" | "labels" | "active_runs" | "user_stats" | "read_stats" | "last_activity"
| "archives" | "active_archives" | "blocked_by" | "live_descendants" | "attention";
export function parseScopeFilter(
input: IssueScope | string | readonly string[] | undefined,
): IssueScope[] {
const scopes = [...new Set(parseStatusFilter(input))];
for (const scope of scopes) {
if (!ISSUE_SCOPES.includes(scope as IssueScope)) {
throw unprocessable(`Invalid issue scope: ${scope}`);
}
}
return scopes as IssueScope[];
}
export interface IssueListOptions {
/** Wraps each internal read so callers can report per-phase timing. */
timePhase?: <T>(phase: IssueListPhase, read: () => Promise<T>) => Promise<T>;
@@ -1890,6 +1905,7 @@ export interface IssueFilters {
attention?: "blocked";
status?: string | readonly string[];
displayStatus?: string | readonly string[];
scope?: IssueScope | string | readonly IssueScope[];
/**
* Filter by assignee agent ID.
* - `string` (UUID): match issues assigned to that agent.
@@ -2078,6 +2094,8 @@ type IssueCreateInput = Omit<typeof issues.$inferInsert, "companyId" | "title" |
initialPlan?: string | null;
/** Internal, server-derived provenance for an accepted in-app chat suggestion. */
conversationHandoff?: { conversationId: string; sessionGeneration: number };
/** True for explicit chat-to-board handoffs that should default to scope 'board'. */
isExplicitBoardHandoff?: boolean;
labelIds?: string[];
blockedByIssueIds?: string[];
inheritExecutionWorkspaceFromIssueId?: string | null;
@@ -5335,6 +5353,7 @@ const issueListSelect = {
END
`,
status: issues.status,
scope: issues.scope,
displayStatus: issueDisplayStatusSql(),
statusVersion: issues.statusVersion,
lastStatusDecisionId: issues.lastStatusDecisionId,
@@ -6705,9 +6724,10 @@ function assertValidAssigneeAgentFilter(
function creationVisibilityCondition(companyId: string, filters?: IssueFilters) {
if (filters?.includeAgentCreatedTasks !== false) return undefined;
const boardScopeCondition = eq(issues.scope, "board");
return filters.creationVisibilityUserId
? or(humanCreatedIssueCondition(), touchedByUserCondition(companyId, filters.creationVisibilityUserId))!
: humanCreatedIssueCondition();
? or(boardScopeCondition, touchedByUserCondition(companyId, filters.creationVisibilityUserId))!
: boardScopeCondition;
}
async function blockedInboxIssueConditions(
@@ -6720,6 +6740,12 @@ async function blockedInboxIssueConditions(
visibleIssueCondition(),
notInArray(issues.status, [...BLOCKED_INBOX_TERMINAL_STATUSES]),
];
const scopes = parseScopeFilter(filters?.scope);
if (scopes.length > 0) {
conditions.push(scopes.length === 1 ? eq(issues.scope, scopes[0]!) : inArray(issues.scope, scopes));
} else if (!filters?.q?.trim() && !filters?.issueIds) {
conditions.push(nonChatAndChannelIssueCondition());
}
if (filters?.readCondition) conditions.push(filters.readCondition);
const creationCondition = creationVisibilityCondition(companyId, filters);
if (creationCondition) conditions.push(creationCondition);
@@ -8559,7 +8585,7 @@ export function issueService(db: Db) {
.from(participated).innerJoin(issues, eq(issues.id, sql`"mine_participants"."id"`)).where(and(
eq(issues.companyId, companyId),
visibleIssueCondition(),
isNull(issues.conversationAgentId),
nonChatAndChannelIssueCondition(),
nonPluginOperationIssueCondition(),
ne(issues.status, "cancelled"),
inboxVisibleForUserCondition(companyId, userId),
@@ -8617,8 +8643,11 @@ export function issueService(db: Db) {
? sql<boolean>`NOT (${inboxVisibleForUserCondition(companyId, inboxArchive.userId)})`
: undefined;
if (inboxArchive?.mode === "archived" && archivedCondition) conditions.push(archivedCondition);
if (!filters?.q?.trim() && !filters?.issueIds) {
conditions.push(isNull(issues.conversationAgentId));
const scopes = parseScopeFilter(filters?.scope);
if (scopes.length > 0) {
conditions.push(scopes.length === 1 ? eq(issues.scope, scopes[0]!) : inArray(issues.scope, scopes));
} else if (!filters?.q?.trim() && !filters?.issueIds) {
conditions.push(nonChatAndChannelIssueCondition());
// Explicit child navigation includes waiting chat tasks, just like
// readable-child counts. Ambient lists still omit idle conversations.
if (!filters?.parentId && !filters?.parentIds && !filters?.descendantOf && !filters?.touchedByUserId && !filters?.unreadForUserId && !filters?.inboxArchivedByUserId && inboxArchive?.mode !== "archived") {
@@ -9026,8 +9055,11 @@ export function issueService(db: Db) {
if (filters?.readCondition) conditions.push(filters.readCondition);
const creationCondition = creationVisibilityCondition(companyId, filters);
if (creationCondition) conditions.push(creationCondition);
if (!filters?.q?.trim()) {
conditions.push(isNull(issues.conversationAgentId));
const scopes = parseScopeFilter(filters?.scope);
if (scopes.length > 0) {
conditions.push(scopes.length === 1 ? eq(issues.scope, scopes[0]!) : inArray(issues.scope, scopes));
} else if (!filters?.q?.trim() && !filters?.issueIds) {
conditions.push(nonChatAndChannelIssueCondition());
if (!filters?.parentId && !filters?.parentIds && !filters?.touchedByUserId && !filters?.unreadForUserId && !filters?.inboxArchivedByUserId) {
conditions.push(nonIdleSlackIssueCondition());
}
@@ -10635,6 +10667,7 @@ export function issueService(db: Db) {
workspaceSelection, workspaceSelectionSource = "explicit", workspaceSelectionActor,
initialPlan,
conversationHandoff,
isExplicitBoardHandoff,
generateConversationTitle,
labelIds: inputLabelIds,
blockedByIssueIds,
@@ -10678,6 +10711,9 @@ export function issueService(db: Db) {
if (data.assigneeAgentId && data.assigneeUserId) {
throw unprocessable("Issue can only have one assignee");
}
if (issueData.conversationAgentId != null && issueData.scope !== undefined && issueData.scope !== null && issueData.scope !== "chat") {
throw unprocessable("Conversation issues must have scope 'chat'");
}
if (data.assigneeAgentId) {
await assertAssignableAgent(db, companyId, data.assigneeAgentId, {
kind: "work",
@@ -11119,13 +11155,18 @@ export function issueService(db: Db) {
}) : null;
// The task the creating run was bound to, when a run created this task.
let runSourceIssueId: string | null = null;
let runSourceIssueIsConversation = false;
const sourceRunId = issueData.originRunId ?? actorRunId;
if (sourceRunId && isUuidLike(sourceRunId)) {
const [sourceRun] = await tx.select().from(heartbeatRuns)
.where(and(eq(heartbeatRuns.id, sourceRunId), eq(heartbeatRuns.companyId, companyId)));
// Same binding rules as creation-source reads: native identity, issue
// scope, then legacy task context (including identifiers), company-scoped.
if (sourceRun) runSourceIssueId = (await loadRunBoundIssue(tx as unknown as Db, sourceRun))?.id ?? null;
if (sourceRun) {
const runBoundIssue = await loadRunBoundIssue(tx as unknown as Db, sourceRun);
runSourceIssueId = runBoundIssue?.id ?? null;
runSourceIssueIsConversation = Boolean(runBoundIssue?.conversationAgentId);
}
}
// Privacy follows structure: the requested parent (even when placed
// beside it), the chat that handed this off, or the run's task.
@@ -11188,8 +11229,20 @@ export function issueService(db: Db) {
.then((rows) => rows.length > 0));
if (!originPublic) originIssueId = null;
}
const derivedScope = deriveDefaultIssueScope({
scope: issueData.scope ?? null,
conversationAgentId: issueData.conversationAgentId ?? null,
channelId: null,
createdByAgentId: issueData.createdByAgentId ?? null,
createdByUserId: issueData.createdByUserId ?? null,
originKind: issueData.originKind ?? "manual",
isExplicitBoardHandoff:
isExplicitBoardHandoff ??
Boolean(handoffSource || (runSourceIssueIsConversation && !issueData.parentId)),
});
const values = {
...issueData,
scope: derivedScope,
workspaceSelection: workspaceIntent,
visibility,
privacyRootIssueId,
@@ -11762,6 +11815,9 @@ export function issueService(db: Db) {
await assertExecutionTaskParent(dbOrTx, existing.companyId, data.parentId);
}
if (existing.conversationAgentId) {
if (data.scope !== undefined && data.scope !== "chat") {
throw unprocessable("Conversation issues must keep scope 'chat'");
}
if ((data.assigneeAgentId !== undefined && data.assigneeAgentId !== existing.conversationAgentId)
|| data.assigneeUserId || data.conversationAgentId !== undefined || data.conversationUserId !== undefined
|| data.conversationState !== undefined || data.conversationSessionGeneration !== undefined
@@ -2287,6 +2287,7 @@ export class PaperclipRunnerToolAuthority {
parentDepthPolicy,
...(parentIssueId ? { expectedParentId: placedParentId } : {}),
...(workspaceSourceIssueId ? { inheritExecutionWorkspaceFromIssueId: workspaceSourceIssueId } : {}),
...(context.issue.conversationAgentId && !parentIssueId ? { scope: "board" as const, isExplicitBoardHandoff: true } : {}),
createdByAgentId: this.binding.agentId,
originKind: "manual" as const,
originId: durableIdempotencyKey,