diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index 71d713489dd..3ba930058dc 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -923,6 +923,7 @@ const MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS = new Set([ "0505_nice_rawhide_kid.sql", "0508_normal_riptide.sql", "0507_special_kang.sql", + "0511_pale_kronos.sql", ]); async function applyPendingMigrationsManually( diff --git a/packages/db/src/migrations/0511_pale_kronos.sql b/packages/db/src/migrations/0511_pale_kronos.sql new file mode 100644 index 00000000000..6ad5368e012 --- /dev/null +++ b/packages/db/src/migrations/0511_pale_kronos.sql @@ -0,0 +1,10 @@ +-- paperclip:migration-compat online_compatible: adds issues.scope with constant default 'board', backfills existing conversation and agent-created rows, adds check constraints as NOT VALID then validates under SHARE UPDATE EXCLUSIVE, and builds both scope indexes CONCURRENTLY. Every statement is idempotent because this file runs outside a transaction. +ALTER TABLE "issues" ADD COLUMN IF NOT EXISTS "scope" text DEFAULT 'board' NOT NULL;--> statement-breakpoint +UPDATE "issues" SET "scope" = 'chat' WHERE "conversation_agent_id" IS NOT NULL AND "scope" <> 'chat';--> statement-breakpoint +UPDATE "issues" SET "scope" = 'agent' WHERE "conversation_agent_id" IS NULL AND "scope" = 'board' AND ("created_by_agent_id" IS NOT NULL OR "origin_kind" NOT IN ('manual', 'onboarding_first_task'));--> statement-breakpoint +ALTER TABLE "issues" DROP CONSTRAINT IF EXISTS "issues_scope_check", ADD CONSTRAINT "issues_scope_check" CHECK ("issues"."scope" in ('board', 'channel', 'agent', 'chat')) NOT VALID;--> statement-breakpoint +ALTER TABLE "issues" VALIDATE CONSTRAINT "issues_scope_check";--> statement-breakpoint +ALTER TABLE "issues" DROP CONSTRAINT IF EXISTS "issues_conversation_scope_check", ADD CONSTRAINT "issues_conversation_scope_check" CHECK (("issues"."conversation_agent_id" is null) or ("issues"."scope" = 'chat')) NOT VALID;--> statement-breakpoint +ALTER TABLE "issues" VALIDATE CONSTRAINT "issues_conversation_scope_check";--> statement-breakpoint +CREATE INDEX CONCURRENTLY IF NOT EXISTS "issues_company_scope_status_idx" ON "issues" USING btree ("company_id","scope","status");--> statement-breakpoint +CREATE INDEX CONCURRENTLY IF NOT EXISTS "issues_company_scope_updated_idx" ON "issues" USING btree ("company_id","scope","updated_at"); diff --git a/packages/db/src/migrations/meta/0506_snapshot.json b/packages/db/src/migrations/meta/0511_snapshot.json similarity index 99% rename from packages/db/src/migrations/meta/0506_snapshot.json rename to packages/db/src/migrations/meta/0511_snapshot.json index f5584aa440b..c661ae46a90 100644 --- a/packages/db/src/migrations/meta/0506_snapshot.json +++ b/packages/db/src/migrations/meta/0511_snapshot.json @@ -1,6 +1,6 @@ { - "id": "7adc8220-8196-44a5-94ee-26f8f5c33dee", - "prevId": "001ed6d5-4cc4-4f05-91ec-f3031c94bc98", + "id": "2cc13a19-e7a2-4561-be70-733611070aa0", + "prevId": "bd7706ab-f548-43f0-9dbb-4f1d52d9c135", "version": "7", "dialect": "postgresql", "tables": { @@ -26298,6 +26298,160 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.document_annotation_comment_reactions": { + "name": "document_annotation_comment_reactions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "comment_id": { + "name": "comment_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "reaction": { + "name": "reaction", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_type": { + "name": "actor_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "removed_at": { + "name": "removed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "document_annotation_comment_reactions_company_comment_idx": { + "name": "document_annotation_comment_reactions_company_comment_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "comment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "document_annotation_comment_reactions_comment_reaction_actor_idx": { + "name": "document_annotation_comment_reactions_comment_reaction_actor_idx", + "columns": [ + { + "expression": "comment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "reaction", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "actor_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "actor_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "document_annotation_comment_reactions_company_id_companies_id_fk": { + "name": "document_annotation_comment_reactions_company_id_companies_id_fk", + "tableFrom": "document_annotation_comment_reactions", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "document_annotation_comment_reactions_comment_id_document_annotation_comments_id_fk": { + "name": "document_annotation_comment_reactions_comment_id_document_annotation_comments_id_fk", + "tableFrom": "document_annotation_comment_reactions", + "tableTo": "document_annotation_comments", + "columnsFrom": [ + "comment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "document_annotation_comment_reactions_reaction_chk": { + "name": "document_annotation_comment_reactions_reaction_chk", + "value": "\"document_annotation_comment_reactions\".\"reaction\" in ('done', 'check', 'thumbs_up', 'question')" + }, + "document_annotation_comment_reactions_actor_type_chk": { + "name": "document_annotation_comment_reactions_actor_type_chk", + "value": "\"document_annotation_comment_reactions\".\"actor_type\" in ('agent', 'user')" + } + }, + "isRLSEnabled": false + }, "public.document_annotation_comments": { "name": "document_annotation_comments", "schema": "", @@ -36739,6 +36893,62 @@ "method": "btree", "with": {} }, + "heartbeat_runs_attention_resumed_idx": { + "name": "heartbeat_runs_attention_resumed_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"issue_id\"::text, \"native_issue_id\"::text,\n \"context_snapshot\"->>'issueId', \"context_snapshot\"->>'taskId')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"heartbeat_runs\".\"status\" in ('running', 'succeeded')", + "concurrently": true, + "method": "btree", + "with": {} + }, + "heartbeat_runs_attention_history_idx": { + "name": "heartbeat_runs_attention_history_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": false, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"heartbeat_runs\".\"status\" in ('failed', 'timed_out') or \"heartbeat_runs\".\"error_code\" = 'provider_limit_wait'", + "concurrently": true, + "method": "btree", + "with": {} + }, "heartbeat_runs_company_ctx_issue_created_idx": { "name": "heartbeat_runs_company_ctx_issue_created_idx", "columns": [ @@ -44083,6 +44293,13 @@ "notNull": true, "default": "'backlog'" }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'board'" + }, "status_version": { "name": "status_version", "type": "bigint", @@ -44449,6 +44666,60 @@ "method": "btree", "with": {} }, + "issues_company_scope_status_idx": { + "name": "issues_company_scope_status_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scope", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "issues_company_scope_updated_idx": { + "name": "issues_company_scope_updated_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scope", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, "issues_company_harness_kind_idx": { "name": "issues_company_harness_kind_idx", "columns": [ @@ -45342,6 +45613,14 @@ "name": "issues_visibility_check", "value": "\"issues\".\"visibility\" in ('open', 'private')" }, + "issues_scope_check": { + "name": "issues_scope_check", + "value": "\"issues\".\"scope\" in ('board', 'channel', 'agent', 'chat')" + }, + "issues_conversation_scope_check": { + "name": "issues_conversation_scope_check", + "value": "(\"issues\".\"conversation_agent_id\" is null) or (\"issues\".\"scope\" = 'chat')" + }, "issues_conversation_identity_check": { "name": "issues_conversation_identity_check", "value": "(\n \"issues\".\"conversation_agent_id\" is null and \"issues\".\"conversation_user_id\" is null and \"issues\".\"conversation_state\" is null\n ) or (\n \"issues\".\"conversation_agent_id\" is not null and \"issues\".\"conversation_user_id\" is not null\n and \"issues\".\"assignee_agent_id\" = \"issues\".\"conversation_agent_id\" and \"issues\".\"assignee_agent_id\" is not null\n and \"issues\".\"assignee_user_id\" is null and \"issues\".\"conversation_state\" is not null\n and \"issues\".\"conversation_state\" in ('active', 'waiting')\n and \"issues\".\"status\" not in ('done', 'cancelled')\n )" @@ -60159,6 +60438,28 @@ "concurrently": false, "method": "btree", "with": {} + }, + "tool_call_events_connection_error_idx": { + "name": "tool_call_events_connection_error_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"tool_call_events\".\"error_message\" is not null", + "concurrently": false, + "method": "btree", + "with": {} } }, "foreignKeys": { @@ -62611,6 +62912,28 @@ "method": "btree", "with": {} }, + "tool_invocations_connection_error_idx": { + "name": "tool_invocations_connection_error_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"tool_invocations\".\"error_message\" is not null", + "concurrently": false, + "method": "btree", + "with": {} + }, "tool_invocations_company_idempotency_uq": { "name": "tool_invocations_company_idempotency_uq", "columns": [ diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index 2e760e9fa7e..848a97e48e8 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -3564,6 +3564,13 @@ "when": 1795635927842, "tag": "0510_clear_speedball", "breakpoints": true + }, + { + "idx": 511, + "version": "7", + "when": 1796071038991, + "tag": "0511_pale_kronos", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema/issues.ts b/packages/db/src/schema/issues.ts index 60e7b2408d7..2eb8dff3544 100644 --- a/packages/db/src/schema/issues.ts +++ b/packages/db/src/schema/issues.ts @@ -21,7 +21,7 @@ import { companies } from "./companies.js"; import { heartbeatRuns } from "./heartbeat_runs.js"; import { projectWorkspaces } from "./project_workspaces.js"; import { executionWorkspaces } from "./execution_workspaces.js"; -import type { IssueReviewPolicy, IssueUnblockDescriptor, SourceTrustMetadata, TaskWorkspaceIntent, TaskWorkspacePendingSelection } from "@paperclipai/shared"; +import type { IssueReviewPolicy, IssueScope, IssueUnblockDescriptor, SourceTrustMetadata, TaskWorkspaceIntent, TaskWorkspacePendingSelection } from "@paperclipai/shared"; export const issues = pgTable( "issues", @@ -45,6 +45,7 @@ export const issues = pgTable( titleNeedsGeneration: boolean("title_needs_generation").notNull().default(false), description: text("description"), status: text("status").notNull().default("backlog"), + scope: text("scope").$type().notNull().default("board"), statusVersion: bigint("status_version", { mode: "number" }).notNull().default(0), lastStatusDecisionId: uuid("last_status_decision_id"), workMode: text("work_mode").notNull().default("standard"), @@ -102,6 +103,8 @@ export const issues = pgTable( }, (table) => ({ visibilityCheck: check("issues_visibility_check", sql`${table.visibility} in ('open', 'private')`), + scopeCheck: check("issues_scope_check", sql`${table.scope} in ('board', 'channel', 'agent', 'chat')`), + conversationScopeCheck: check("issues_conversation_scope_check", sql`(${table.conversationAgentId} is null) or (${table.scope} = 'chat')`), conversationIdentityIdx: uniqueIndex("issues_conversation_identity_idx").on(table.companyId, table.conversationAgentId, table.conversationUserId), conversationIdentityCheck: check("issues_conversation_identity_check", sql`( ${table.conversationAgentId} is null and ${table.conversationUserId} is null and ${table.conversationState} is null @@ -114,6 +117,8 @@ export const issues = pgTable( )`), companyIdUq: unique("issues_company_id_uq").on(table.companyId, table.id), companyStatusIdx: index("issues_company_status_idx").on(table.companyId, table.status), + companyScopeStatusIdx: index("issues_company_scope_status_idx").on(table.companyId, table.scope, table.status), + companyScopeUpdatedIdx: index("issues_company_scope_updated_idx").on(table.companyId, table.scope, table.updatedAt), companyHarnessKindIdx: index("issues_company_harness_kind_idx").on(table.companyId, table.harnessKind), assigneeStatusIdx: index("issues_company_assignee_status_idx").on( table.companyId, diff --git a/packages/shared/src/constants.ts b/packages/shared/src/constants.ts index 4709afa0716..de3d7da2b99 100644 --- a/packages/shared/src/constants.ts +++ b/packages/shared/src/constants.ts @@ -228,6 +228,8 @@ export const ISSUE_REVIEW_POLICIES = ["anyone", "not_creator", "human_only"] as export type IssueReviewPolicy = (typeof ISSUE_REVIEW_POLICIES)[number]; export const ISSUE_WORK_MODES = ["standard", "ask", "planning", "skill_test"] as const; export type IssueWorkMode = (typeof ISSUE_WORK_MODES)[number]; +export const ISSUE_SCOPES = ["board", "channel", "agent", "chat"] as const; +export type IssueScope = (typeof ISSUE_SCOPES)[number]; export const ISSUE_HARNESS_KINDS = ["skill_test"] as const; export type IssueHarnessKind = (typeof ISSUE_HARNESS_KINDS)[number]; export const MAX_ISSUE_REQUEST_DEPTH = 1024; diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index cdfadcb65f5..41188e4af6d 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -444,6 +444,7 @@ export { INBOX_MINE_ISSUE_STATUS_FILTER, ISSUE_PRIORITIES, ISSUE_REVIEW_POLICIES, + ISSUE_SCOPES, ISSUE_WORK_MODES, ISSUE_HARNESS_KINDS, MAX_ISSUE_REQUEST_DEPTH, @@ -671,6 +672,7 @@ export { type IssueDisplayStatus, type IssuePriority, type IssueReviewPolicy, + type IssueScope, type IssueWorkMode, type IssueHarnessKind, type SummarySlotScopeKind, @@ -1193,6 +1195,7 @@ export type { ExternalObjectSummary, ExternalObjectSummaryItem, CompactIssue, + IssueFilters, IssueInboxArchiveFilter, IssueSummary, Issue, @@ -3136,7 +3139,13 @@ export * from "./muse-protocol.js"; export * from "./muse-invitations.js"; export * from "./fast-response.js"; -export { HUMAN_TASK_ORIGIN_KINDS, isAgentCreatedIssue, type IssueCreationSourceFields } from "./issue-creation-source.js"; +export { + HUMAN_TASK_ORIGIN_KINDS, + isAgentCreatedIssue, + deriveDefaultIssueScope, + type IssueCreationSourceFields, + type DeriveIssueScopeInput, +} from "./issue-creation-source.js"; export * from "./grok-bot.js"; export * from "./agent-observability.js"; diff --git a/packages/shared/src/issue-creation-source.ts b/packages/shared/src/issue-creation-source.ts index 48bd43f183b..d8f750a0e70 100644 --- a/packages/shared/src/issue-creation-source.ts +++ b/packages/shared/src/issue-creation-source.ts @@ -1,3 +1,5 @@ +import type { IssueScope } from "./constants.js"; + /** Origins that represent a person's ordinary task or onboarding request. */ export const HUMAN_TASK_ORIGIN_KINDS = ["manual", "onboarding_first_task"] as const; @@ -15,3 +17,20 @@ export function isAgentCreatedIssue(issue: IssueCreationSourceFields): boolean { (issue.originKind ?? "manual") as typeof HUMAN_TASK_ORIGIN_KINDS[number], ); } + +export interface DeriveIssueScopeInput extends IssueCreationSourceFields { + scope?: IssueScope | null; + conversationAgentId?: string | null; + channelId?: string | null; + isExplicitBoardHandoff?: boolean; +} + +/** Derives the default surface scope for a newly created issue. */ +export function deriveDefaultIssueScope(input: DeriveIssueScopeInput): IssueScope { + if (input.conversationAgentId != null) return "chat"; + if (input.scope != null) return input.scope; + if (input.channelId != null) return "channel"; + if (input.isExplicitBoardHandoff) return "board"; + if (isAgentCreatedIssue(input)) return "agent"; + return "board"; +} diff --git a/packages/shared/src/types/index.ts b/packages/shared/src/types/index.ts index f8eedd126cf..07ec789357c 100644 --- a/packages/shared/src/types/index.ts +++ b/packages/shared/src/types/index.ts @@ -736,6 +736,7 @@ export type { } from "./external-object.js"; export type { CompactIssue, + IssueFilters, IssueInboxArchiveFilter, IssueSummary, Issue, diff --git a/packages/shared/src/types/issue.ts b/packages/shared/src/types/issue.ts index 5229e472a1e..b32eb37c13e 100644 --- a/packages/shared/src/types/issue.ts +++ b/packages/shared/src/types/issue.ts @@ -31,6 +31,7 @@ import type { IssueRecoveryActionOwnerType, IssueBlockerStallRelation, IssueRecoveryActionStatus, + IssueScope, IssueWorkMode, IssueThreadInteractionContinuationPolicy, IssueThreadInteractionCanonicalResolverPolicy, @@ -957,6 +958,7 @@ export interface Issue { description: string | null; descriptionTruncated?: boolean; status: IssueStatus; + scope?: IssueScope; workMode: IssueWorkMode; priority: IssuePriority; reviewPolicy: IssueReviewPolicy | null; @@ -1049,6 +1051,53 @@ export interface Issue { export type IssueInboxArchiveFilter = "include" | "archived"; +export interface IssueFilters { + attention?: "blocked"; + status?: string | readonly string[]; + displayStatus?: string | readonly string[]; + scope?: IssueScope | string; + assigneeAgentId?: string | null; + participantAgentId?: string; + issueIds?: string[]; + listProjection?: "index" | "rows"; + parentIds?: string[]; + oneChildPerParent?: boolean; + assigneeUserId?: string; + touchedByUserId?: string; + touchedCandidates?: "participation"; + inboxArchivedByUserId?: string; + inboxArchive?: { userId: string; mode: IssueInboxArchiveFilter }; + unreadForUserId?: string; + readStateForUserId?: string; + projectId?: string; + workspaceId?: string; + executionWorkspaceId?: string; + parentId?: string; + descendantOf?: string; + createdFromIssueId?: string; + labelId?: string; + originKind?: string; + originKindPrefix?: string; + originId?: string; + includeAgentCreatedTasks?: boolean; + creationVisibilityUserId?: string; + includeRoutineExecutions?: boolean; + excludeRoutineExecutions?: boolean; + includePluginOperations?: boolean; + includeBlockedBy?: boolean; + includeBlockedInboxAttention?: boolean; + includeLiveDescendantSummary?: boolean; + hasPlanDocument?: boolean; + q?: string; + limit?: number; + offset?: number; + sortField?: "updated" | "created" | "id"; + afterId?: string; + sortDir?: "asc" | "desc"; + updatedSince?: string; + updatedBefore?: string; +} + export type CompactIssue = Pick< Issue, | "listProjection" @@ -1065,6 +1114,7 @@ export type CompactIssue = Pick< | "description" | "displayStatus" | "status" + | "scope" | "workMode" | "priority" | "reviewPolicy" diff --git a/packages/shared/src/validators/issue.ts b/packages/shared/src/validators/issue.ts index af96c56dc0a..6f581b6392c 100644 --- a/packages/shared/src/validators/issue.ts +++ b/packages/shared/src/validators/issue.ts @@ -27,6 +27,7 @@ import { ISSUE_RECOVERY_ACTION_OWNER_TYPES, ISSUE_RECOVERY_ACTION_STATUSES, ISSUE_REVIEW_POLICIES, + ISSUE_SCOPES, ISSUE_WORK_MODES, clampIssueRequestDepth, ISSUE_STATUSES, @@ -839,6 +840,7 @@ const createIssueBaseSchema = z.object({ title: z.string().min(1), description: multilineTextSchema.optional().nullable(), status: z.enum(ISSUE_STATUSES), + scope: z.enum(ISSUE_SCOPES).optional(), workMode: z.enum(ISSUE_WORK_MODES).optional().default("standard"), harnessKind: z.enum(ISSUE_HARNESS_KINDS).optional().nullable(), priority: z.enum(ISSUE_PRIORITIES).optional().default("medium"), diff --git a/server/src/__tests__/issue-scope-visibility.test.ts b/server/src/__tests__/issue-scope-visibility.test.ts new file mode 100644 index 00000000000..325925b3bae --- /dev/null +++ b/server/src/__tests__/issue-scope-visibility.test.ts @@ -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`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`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()); + }); +}); diff --git a/server/src/__tests__/issues-creation-visibility.test.ts b/server/src/__tests__/issues-creation-visibility.test.ts index 64cc0855279..3880d916ede 100644 --- a/server/src/__tests__/issues-creation-visibility.test.ts +++ b/server/src/__tests__/issues-creation-visibility.test.ts @@ -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"), }))); diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index 16879efbc7b..7fc406afd01 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -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, diff --git a/server/src/services/issue-thread-interactions.ts b/server/src/services/issue-thread-interactions.ts index 243dcba2c0e..218ebe544b5 100644 --- a/server/src/services/issue-thread-interactions.ts +++ b/server/src/services/issue-thread-interactions.ts @@ -5740,6 +5740,7 @@ export function issueThreadInteractionService( conversationId: sourceConversation.id, sessionGeneration: sourceConversation.conversationSessionGeneration, } } : {}), + ...(sourceConversation && !parentIssueId ? { scope: "board" as const, isExplicitBoardHandoff: true } : {}), } satisfies Parameters["createChild"]>[1]; const service = issueService(tx as unknown as Db); // A nested suggestion may be placed beside its suggested parent, under diff --git a/server/src/services/issue-visibility.ts b/server/src/services/issue-visibility.ts index b54832f29ee..5861e0091f6 100644 --- a/server/src/services/issue-visibility.ts +++ b/server/src/services/issue-visibility.ts @@ -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 { diff --git a/server/src/services/issues.ts b/server/src/services/issues.ts index 31b2992e32a..d498884dc58 100644 --- a/server/src/services/issues.ts +++ b/server/src/services/issues.ts @@ -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?: (phase: IssueListPhase, read: () => Promise) => Promise; @@ -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 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`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 diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts index 8330cac59a4..2887876fafb 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts @@ -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,