mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 09:39:53 +01:00
feat(issues): add issues.scope surface visibility foundation (#23329)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - Issues currently store human board tasks, agent-created operational
tasks, and persistent 1:1 Agent Chats in the same `issues` table.
> - Default board lists, counts, and Mine views previously relied on
ad-hoc creator and origin predicates to hide chats and separate agent
tasks.
> - Upcoming headless channels also need a clean way to isolate channel
issues from default board lists without inventing a separate task
entity.
> - This pull request adds an explicit `issues.scope` column (`board`,
`channel`, `agent`, `chat`) across the schema, shared types, service
filters, client filters, and issue routes.
> - The benefit is unified surface visibility filtering and explicit
scope derivation while keeping rolling deploys safe and preserving
existing Agent Chat and board behavior.
## Linked Issues or Issue Description
**Subsystem affected**
Cross-cutting (`packages/db`, `packages/shared`, `server/` REST API &
orchestration services, `ui/` client filters, and `docs/api/issues.md`).
**Problem or motivation**
Paperclip uses the `issues` table for human board work, automated or
agent-created operational work, and persistent 1:1 Agent Chats. Without
a dedicated surface-scope column, list, count, and Mine queries depend
on `conversationAgentId`, `createdByAgentId`, and `originKind` checks,
and there is no first-class way to isolate channel streams from default
board views.
**Proposed solution**
Add an `issues.scope` column (`board` | `channel` | `agent` | `chat`)
with `issues_scope_check` and composite indexes, expose `scope` in
shared types and Zod validators, derive default scope on issue creation
and batch imports, protect `chat` scope on 1:1 conversations and block
unauthorized agent `scope: "board"` writes across routes and
`issueService`, update server visibility queries and `applyIssueFilters`
on the client to honor `scope`, add `scope` filtering on `GET
/api/companies/:companyId/issues` and `/count`, and document the new
parameter in `docs/api/issues.md`.
**Alternatives considered**
1. Create separate tables for chats and channels. We ruled this out
because Paperclip builds assignment, comments, approvals, and execution
around a single `issues` model.
2. Add a DB `CHECK ((conversation_agent_id IS NULL) OR (scope =
'chat'))` constraint in this expand migration. We ruled this out for the
initial rollout because `ADD CONSTRAINT ... NOT VALID` still enforces
checks on new writes from older server instances that omit `scope`
during a rolling deploy.
3. Continue filtering only by `originKind` and `conversationAgentId` at
query time. We ruled this out because it cannot distinguish an explicit
chat-to-board handoff from a background agent task.
**Roadmap alignment**
Supports the **Agent Chat (including CEO Chat)** and **Work Queues** /
channel-intake directions in `ROADMAP.md` by separating surface
visibility on the shared `issues` table.
**Additional context**
This PR introduces the expand-phase schema, shared contract,
service-layer derivation, client filter handling, API filter foundation,
and API documentation. Follow-up work will build channel UI surfaces on
`issues.scope` and add the contract-phase DB check constraint after
older writers drain and re-backfill any rolling-deploy conversation
rows.
## What Changed
- Added `scope` (`board` | `channel` | `agent` | `chat`, default
`board`) to `packages/db/src/schema/issues.ts` with
`issues_scope_check`, `issues_company_scope_status_idx`, and
`issues_company_scope_updated_idx`.
- Added online-compatible migration
`packages/db/src/migrations/0511_simple_the_hunter.sql` (plus updated
Drizzle snapshot/journal and `MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS`
entry in `packages/db/src/client.ts`) to backfill existing `chat` and
`agent` rows in bounded 1,000-row primary-key cursor batches matching
`isAgentCreatedIssue`, validate `issues_scope_check` with `NOT VALID` +
`VALIDATE CONSTRAINT`, and build indexes `CONCURRENTLY`.
- Exported `ISSUE_SCOPES`, `IssueScope`, and `deriveDefaultIssueScope`
in `packages/shared`, added `scope?: IssueScope` to `Issue` and
`CompactIssue`, and added optional `scope` validation to
`createIssueSchema` and `updateIssueSchema`.
- Extracted `parseScopeFilter` and `surfaceScopeCondition` in
`server/src/services/issue-visibility.ts`, and updated `issueService`
(`create`, `importIssues`, `update`, `list`, `count`, blocked inbox
counts, and Mine views) to derive default scope (including `scope:
"agent"` for creatorless imports), enforce `chat` scope on 1:1
conversations, reject `scope: "chat"` on non-conversation issues, reject
unauthorized agent `scope: "board"` creation without handoff provenance,
default chat-to-board handoffs to `board`, preserve
`nonIdleSlackIssueCondition` on non-chat/channel scope filters, let
explicit `scope` filters override `includeAgentCreatedTasks=false`, and
exclude `chat` and `channel` rows from default board queries unless
filtered by `scope`, `q`, or `issueIds`.
- Updated `applyIssueFilters` (`isBoardVisibleByDefault`) in
`ui/src/lib/issue-filters.ts` so agent-created tasks with `scope:
"board"` (such as chat-to-board handoffs) stay visible by default.
- Added `scope` query parsing (`parseIssueListScopeQueryParam`
delegating to `parseScopeFilter`) and `assertActorMayWriteIssueScope`
across `POST /companies/:companyId/issues`, `POST /issues/:id/children`,
`POST /issues/:id/accepted-plan-decompositions`, and `PATCH /issues/:id`
in `server/src/routes/issues.ts`, included `scope` in `toCompactIssue`,
and documented `scope` in `docs/api/issues.md`.
- Added tests in `server/src/__tests__/issue-scope-visibility.test.ts`
and `ui/src/lib/issue-filters.test.ts`, updated
`server/src/__tests__/fixtures/issue-detail-response.json` and
`server/src/__tests__/issues-creation-visibility.test.ts`, and refreshed
`tests/runner-e2e/source-sdk-public-inputs.json`.
## Verification
- `pnpm --filter @paperclipai/db typecheck` (`check:migrations` + `tsc
--noEmit`), `pnpm --filter @paperclipai/shared typecheck`, and `pnpm
--filter @paperclipai/server typecheck` — passed on
`3db819854ff28ebc5e875b8d9d0daa74055bef35`.
- `npx vitest run packages/db/src/migration-snapshot-drift.test.ts
server/src/__tests__/issue-scope-visibility.test.ts
server/src/__tests__/issues-creation-visibility.test.ts
server/src/__tests__/company-portability-import-batching.test.ts
ui/src/lib/issue-filters.test.ts` — 5 files, 51 tests passed (1
pre-existing skip in `company-portability-import-batching.test.ts`).
- `node tests/runner-e2e/source-sdk-public-inputs.mjs
3db819854f --check` — exited 0
(`"changed":false`).
- Full CI + security/review checks passed on
`3db819854ff28ebc5e875b8d9d0daa74055bef35` (88/88 check runs completed
with 0 failures; `mergeable: MERGEABLE`, `mergeStateStatus: CLEAN`;
Greptile `5/5` with 0 unresolved threads).
## Risks
- Migration `0511_simple_the_hunter.sql` runs outside a transaction
(`MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS`) because it commits bounded
1,000-row primary-key cursor backfill batches and builds indexes with
`CREATE INDEX CONCURRENTLY`. All statements are idempotent, and
`issues_scope_check` uses `NOT VALID` followed by `VALIDATE CONSTRAINT`.
- The DB-level `conversation_agent_id -> scope = 'chat'` check
constraint is deferred to a follow-up contract migration (which must
re-run the bounded `scope = 'chat'` backfill before adding/validating
the constraint) so rolling deploys with previous writers do not fail 1:1
chat inserts; `issueService.create` and `issueService.update` enforce
this invariant in application code, and
`nonChatAndChannelIssueCondition()` continues checking
`isNull(issues.conversationAgentId)`.
- Behavioral shift: `GET /api/companies/:companyId/issues` and
blocked/Mine aggregations now isolate `scope = 'channel'` and `scope =
'chat'` from default board views unless `scope`, `q`, or `issueIds` is
explicitly passed.
> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.
## 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
158613ef81
commit
66a8aa7f7e
22 files changed
+1168
-35
No files matched your search
+7
-1
@@ -35,6 +35,7 @@ Query parameters:
|
|||||||
| Param | Description |
|
| Param | Description |
|
||||||
|-------|-------------|
|
|-------|-------------|
|
||||||
| `status` | Filter by status (comma-separated: `todo,in_progress`) |
|
| `status` | Filter by status (comma-separated: `todo,in_progress`) |
|
||||||
|
| `scope` | Filter by surface scope (`board`, `channel`, `agent`, `chat`); accepts comma-separated values (`scope=board,agent`) or repeated query parameters (`scope=board&scope=agent`). Invalid values return `400` |
|
||||||
| `assigneeAgentId` | Filter by assigned agent |
|
| `assigneeAgentId` | Filter by assigned agent |
|
||||||
| `projectId` | Filter by project |
|
| `projectId` | Filter by project |
|
||||||
| `view` | `index`: collection rows without bodies or diagnostics; `rows`: rows with diagnostic summaries but no bodies; `compact`: existing board row contract |
|
| `view` | `index`: collection rows without bodies or diagnostics; `rows`: rows with diagnostic summaries but no bodies; `compact`: existing board row contract |
|
||||||
@@ -48,6 +49,8 @@ Query parameters:
|
|||||||
|
|
||||||
Results sorted by priority.
|
Results sorted by priority.
|
||||||
|
|
||||||
|
Default exclusions: when `scope`, `q`, and `ids` are omitted, `GET /api/companies/{companyId}/issues` and `GET /api/companies/{companyId}/issues/count` exclude `chat` and `channel` scoped issues. `GET /api/companies/{companyId}/issues/count` accepts the same `scope` query syntax and returns `400` on invalid values.
|
||||||
|
|
||||||
`inboxArchive` requires a signed-in board user. The filter cannot be combined
|
`inboxArchive` requires a signed-in board user. The filter cannot be combined
|
||||||
with `attention`. When `inboxArchive` is present, each result includes the
|
with `attention`. When `inboxArchive` is present, each result includes the
|
||||||
boolean `isArchivedForMe`. Paperclip uses the same activity rules as Mine to
|
boolean `isArchivedForMe`. Paperclip uses the same activity rules as Mine to
|
||||||
@@ -94,6 +97,7 @@ POST /api/companies/{companyId}/issues
|
|||||||
"title": "Implement caching layer",
|
"title": "Implement caching layer",
|
||||||
"description": "Add Redis caching for hot queries",
|
"description": "Add Redis caching for hot queries",
|
||||||
"status": "todo",
|
"status": "todo",
|
||||||
|
"scope": "board",
|
||||||
"priority": "high",
|
"priority": "high",
|
||||||
"assigneeAgentId": "{agentId}",
|
"assigneeAgentId": "{agentId}",
|
||||||
"parentId": "{parentIssueId}",
|
"parentId": "{parentIssueId}",
|
||||||
@@ -102,6 +106,8 @@ POST /api/companies/{companyId}/issues
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`scope` is optional (`board` | `channel` | `agent` | `chat`). When omitted, the server derives `chat` for 1:1 conversations, `board` for manual human issues and explicit chat-to-board handoffs, and `agent` for agent-created or automated issues. Passing a non-`chat` scope on a 1:1 conversation or `scope: "chat"` on a non-conversation issue returns `422`. Agent actors cannot pass `scope: "board"` directly (`403`).
|
||||||
|
|
||||||
## Update Issue
|
## Update Issue
|
||||||
|
|
||||||
```
|
```
|
||||||
@@ -115,7 +121,7 @@ Headers: X-Paperclip-Run-Id: {runId}
|
|||||||
|
|
||||||
The optional `comment` field adds a comment in the same call. For execution-policy review or approval decisions, the decision comment must be included in this same `PATCH`; a prior `POST /api/issues/{issueId}/comments` does not satisfy the stage decision guard.
|
The optional `comment` field adds a comment in the same call. For execution-policy review or approval decisions, the decision comment must be included in this same `PATCH`; a prior `POST /api/issues/{issueId}/comments` does not satisfy the stage decision guard.
|
||||||
|
|
||||||
Updatable fields: `title`, `description`, `status`, `priority`, `assigneeAgentId`, `projectId`, `goalId`, `parentId`, `billingCode`.
|
Updatable fields: `title`, `description`, `status`, `scope`, `priority`, `assigneeAgentId`, `projectId`, `goalId`, `parentId`, `billingCode`. Existing 1:1 conversation issues must keep `scope: "chat"` and non-conversation issues cannot be set to `scope: "chat"` (`422`). Agent actors cannot promote issues to `scope: "board"` (`403`).
|
||||||
|
|
||||||
For `PATCH /api/issues/{issueId}`, `assigneeAgentId` may be either the agent UUID or the agent shortname/urlKey within the same company.
|
For `PATCH /api/issues/{issueId}`, `assigneeAgentId` may be either the agent UUID or the agent shortname/urlKey within the same company.
|
||||||
|
|
||||||
|
|||||||
@@ -923,6 +923,7 @@ const MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS = new Set([
|
|||||||
"0505_nice_rawhide_kid.sql",
|
"0505_nice_rawhide_kid.sql",
|
||||||
"0508_normal_riptide.sql",
|
"0508_normal_riptide.sql",
|
||||||
"0507_special_kang.sql",
|
"0507_special_kang.sql",
|
||||||
|
"0511_simple_the_hunter.sql",
|
||||||
]);
|
]);
|
||||||
|
|
||||||
async function applyPendingMigrationsManually(
|
async function applyPendingMigrationsManually(
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
-- paperclip:migration-compat online_compatible: adds issues.scope with constant default 'board', backfills existing conversation and agent-created rows in bounded primary-key batches, adds issues_scope_check 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; issues_conversation_scope_check is deferred to a follow-up contract migration (which must re-run the conversation scope='chat' backfill in bounded batches before ADD/VALIDATE CONSTRAINT to catch any conversation rows inserted by old writers during rolling deploy).
|
||||||
|
ALTER TABLE "issues" ADD COLUMN IF NOT EXISTS "scope" text DEFAULT 'board' NOT NULL;--> statement-breakpoint
|
||||||
|
DO $$
|
||||||
|
DECLARE
|
||||||
|
cursor_id uuid := '00000000-0000-0000-0000-000000000000';
|
||||||
|
batch_ids uuid[];
|
||||||
|
BEGIN
|
||||||
|
LOOP
|
||||||
|
SELECT ARRAY(
|
||||||
|
SELECT "id"
|
||||||
|
FROM "issues"
|
||||||
|
WHERE "id" > cursor_id
|
||||||
|
ORDER BY "id"
|
||||||
|
LIMIT 1000
|
||||||
|
) INTO batch_ids;
|
||||||
|
EXIT WHEN coalesce(cardinality(batch_ids), 0) = 0;
|
||||||
|
|
||||||
|
UPDATE "issues" AS i
|
||||||
|
SET "scope" = CASE
|
||||||
|
WHEN i."conversation_agent_id" IS NOT NULL THEN 'chat'
|
||||||
|
WHEN i."scope" = 'board'
|
||||||
|
AND (
|
||||||
|
i."created_by_agent_id" IS NOT NULL
|
||||||
|
OR i."created_by_user_id" IS NULL
|
||||||
|
OR i."origin_kind" NOT IN ('manual', 'onboarding_first_task')
|
||||||
|
)
|
||||||
|
THEN 'agent'
|
||||||
|
ELSE i."scope"
|
||||||
|
END
|
||||||
|
WHERE i."id" = ANY(batch_ids)
|
||||||
|
AND (
|
||||||
|
(i."conversation_agent_id" IS NOT NULL AND i."scope" <> 'chat')
|
||||||
|
OR (
|
||||||
|
i."conversation_agent_id" IS NULL
|
||||||
|
AND i."scope" = 'board'
|
||||||
|
AND (
|
||||||
|
i."created_by_agent_id" IS NOT NULL
|
||||||
|
OR i."created_by_user_id" IS NULL
|
||||||
|
OR i."origin_kind" NOT IN ('manual', 'onboarding_first_task')
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
cursor_id := batch_ids[cardinality(batch_ids)];
|
||||||
|
COMMIT;
|
||||||
|
END LOOP;
|
||||||
|
END $$;--> 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
|
||||||
|
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");
|
||||||
+321
-2
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"id": "7adc8220-8196-44a5-94ee-26f8f5c33dee",
|
"id": "081cc14c-5504-4a93-8b4c-e5945f3936c3",
|
||||||
"prevId": "001ed6d5-4cc4-4f05-91ec-f3031c94bc98",
|
"prevId": "bd7706ab-f548-43f0-9dbb-4f1d52d9c135",
|
||||||
"version": "7",
|
"version": "7",
|
||||||
"dialect": "postgresql",
|
"dialect": "postgresql",
|
||||||
"tables": {
|
"tables": {
|
||||||
@@ -26298,6 +26298,160 @@
|
|||||||
"checkConstraints": {},
|
"checkConstraints": {},
|
||||||
"isRLSEnabled": false
|
"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": {
|
"public.document_annotation_comments": {
|
||||||
"name": "document_annotation_comments",
|
"name": "document_annotation_comments",
|
||||||
"schema": "",
|
"schema": "",
|
||||||
@@ -36739,6 +36893,62 @@
|
|||||||
"method": "btree",
|
"method": "btree",
|
||||||
"with": {}
|
"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": {
|
"heartbeat_runs_company_ctx_issue_created_idx": {
|
||||||
"name": "heartbeat_runs_company_ctx_issue_created_idx",
|
"name": "heartbeat_runs_company_ctx_issue_created_idx",
|
||||||
"columns": [
|
"columns": [
|
||||||
@@ -44083,6 +44293,13 @@
|
|||||||
"notNull": true,
|
"notNull": true,
|
||||||
"default": "'backlog'"
|
"default": "'backlog'"
|
||||||
},
|
},
|
||||||
|
"scope": {
|
||||||
|
"name": "scope",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "'board'"
|
||||||
|
},
|
||||||
"status_version": {
|
"status_version": {
|
||||||
"name": "status_version",
|
"name": "status_version",
|
||||||
"type": "bigint",
|
"type": "bigint",
|
||||||
@@ -44449,6 +44666,60 @@
|
|||||||
"method": "btree",
|
"method": "btree",
|
||||||
"with": {}
|
"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": {
|
"issues_company_harness_kind_idx": {
|
||||||
"name": "issues_company_harness_kind_idx",
|
"name": "issues_company_harness_kind_idx",
|
||||||
"columns": [
|
"columns": [
|
||||||
@@ -45342,6 +45613,10 @@
|
|||||||
"name": "issues_visibility_check",
|
"name": "issues_visibility_check",
|
||||||
"value": "\"issues\".\"visibility\" in ('open', 'private')"
|
"value": "\"issues\".\"visibility\" in ('open', 'private')"
|
||||||
},
|
},
|
||||||
|
"issues_scope_check": {
|
||||||
|
"name": "issues_scope_check",
|
||||||
|
"value": "\"issues\".\"scope\" in ('board', 'channel', 'agent', 'chat')"
|
||||||
|
},
|
||||||
"issues_conversation_identity_check": {
|
"issues_conversation_identity_check": {
|
||||||
"name": "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 )"
|
"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 +60434,28 @@
|
|||||||
"concurrently": false,
|
"concurrently": false,
|
||||||
"method": "btree",
|
"method": "btree",
|
||||||
"with": {}
|
"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": {
|
"foreignKeys": {
|
||||||
@@ -62611,6 +62908,28 @@
|
|||||||
"method": "btree",
|
"method": "btree",
|
||||||
"with": {}
|
"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": {
|
"tool_invocations_company_idempotency_uq": {
|
||||||
"name": "tool_invocations_company_idempotency_uq",
|
"name": "tool_invocations_company_idempotency_uq",
|
||||||
"columns": [
|
"columns": [
|
||||||
+7
@@ -3564,6 +3564,13 @@
|
|||||||
"when": 1795635927842,
|
"when": 1795635927842,
|
||||||
"tag": "0510_clear_speedball",
|
"tag": "0510_clear_speedball",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 511,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1796075417353,
|
||||||
|
"tag": "0511_simple_the_hunter",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -21,7 +21,7 @@ import { companies } from "./companies.js";
|
|||||||
import { heartbeatRuns } from "./heartbeat_runs.js";
|
import { heartbeatRuns } from "./heartbeat_runs.js";
|
||||||
import { projectWorkspaces } from "./project_workspaces.js";
|
import { projectWorkspaces } from "./project_workspaces.js";
|
||||||
import { executionWorkspaces } from "./execution_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(
|
export const issues = pgTable(
|
||||||
"issues",
|
"issues",
|
||||||
@@ -45,6 +45,7 @@ export const issues = pgTable(
|
|||||||
titleNeedsGeneration: boolean("title_needs_generation").notNull().default(false),
|
titleNeedsGeneration: boolean("title_needs_generation").notNull().default(false),
|
||||||
description: text("description"),
|
description: text("description"),
|
||||||
status: text("status").notNull().default("backlog"),
|
status: text("status").notNull().default("backlog"),
|
||||||
|
scope: text("scope").$type<IssueScope>().notNull().default("board"),
|
||||||
statusVersion: bigint("status_version", { mode: "number" }).notNull().default(0),
|
statusVersion: bigint("status_version", { mode: "number" }).notNull().default(0),
|
||||||
lastStatusDecisionId: uuid("last_status_decision_id"),
|
lastStatusDecisionId: uuid("last_status_decision_id"),
|
||||||
workMode: text("work_mode").notNull().default("standard"),
|
workMode: text("work_mode").notNull().default("standard"),
|
||||||
@@ -102,6 +103,7 @@ export const issues = pgTable(
|
|||||||
},
|
},
|
||||||
(table) => ({
|
(table) => ({
|
||||||
visibilityCheck: check("issues_visibility_check", sql`${table.visibility} in ('open', 'private')`),
|
visibilityCheck: check("issues_visibility_check", sql`${table.visibility} in ('open', 'private')`),
|
||||||
|
scopeCheck: check("issues_scope_check", sql`${table.scope} in ('board', 'channel', 'agent', 'chat')`),
|
||||||
conversationIdentityIdx: uniqueIndex("issues_conversation_identity_idx").on(table.companyId, table.conversationAgentId, table.conversationUserId),
|
conversationIdentityIdx: uniqueIndex("issues_conversation_identity_idx").on(table.companyId, table.conversationAgentId, table.conversationUserId),
|
||||||
conversationIdentityCheck: check("issues_conversation_identity_check", sql`(
|
conversationIdentityCheck: check("issues_conversation_identity_check", sql`(
|
||||||
${table.conversationAgentId} is null and ${table.conversationUserId} is null and ${table.conversationState} is null
|
${table.conversationAgentId} is null and ${table.conversationUserId} is null and ${table.conversationState} is null
|
||||||
@@ -114,6 +116,8 @@ export const issues = pgTable(
|
|||||||
)`),
|
)`),
|
||||||
companyIdUq: unique("issues_company_id_uq").on(table.companyId, table.id),
|
companyIdUq: unique("issues_company_id_uq").on(table.companyId, table.id),
|
||||||
companyStatusIdx: index("issues_company_status_idx").on(table.companyId, table.status),
|
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),
|
companyHarnessKindIdx: index("issues_company_harness_kind_idx").on(table.companyId, table.harnessKind),
|
||||||
assigneeStatusIdx: index("issues_company_assignee_status_idx").on(
|
assigneeStatusIdx: index("issues_company_assignee_status_idx").on(
|
||||||
table.companyId,
|
table.companyId,
|
||||||
|
|||||||
@@ -228,6 +228,8 @@ export const ISSUE_REVIEW_POLICIES = ["anyone", "not_creator", "human_only"] as
|
|||||||
export type IssueReviewPolicy = (typeof ISSUE_REVIEW_POLICIES)[number];
|
export type IssueReviewPolicy = (typeof ISSUE_REVIEW_POLICIES)[number];
|
||||||
export const ISSUE_WORK_MODES = ["standard", "ask", "planning", "skill_test"] as const;
|
export const ISSUE_WORK_MODES = ["standard", "ask", "planning", "skill_test"] as const;
|
||||||
export type IssueWorkMode = (typeof ISSUE_WORK_MODES)[number];
|
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 const ISSUE_HARNESS_KINDS = ["skill_test"] as const;
|
||||||
export type IssueHarnessKind = (typeof ISSUE_HARNESS_KINDS)[number];
|
export type IssueHarnessKind = (typeof ISSUE_HARNESS_KINDS)[number];
|
||||||
export const MAX_ISSUE_REQUEST_DEPTH = 1024;
|
export const MAX_ISSUE_REQUEST_DEPTH = 1024;
|
||||||
|
|||||||
@@ -444,6 +444,7 @@ export {
|
|||||||
INBOX_MINE_ISSUE_STATUS_FILTER,
|
INBOX_MINE_ISSUE_STATUS_FILTER,
|
||||||
ISSUE_PRIORITIES,
|
ISSUE_PRIORITIES,
|
||||||
ISSUE_REVIEW_POLICIES,
|
ISSUE_REVIEW_POLICIES,
|
||||||
|
ISSUE_SCOPES,
|
||||||
ISSUE_WORK_MODES,
|
ISSUE_WORK_MODES,
|
||||||
ISSUE_HARNESS_KINDS,
|
ISSUE_HARNESS_KINDS,
|
||||||
MAX_ISSUE_REQUEST_DEPTH,
|
MAX_ISSUE_REQUEST_DEPTH,
|
||||||
@@ -671,6 +672,7 @@ export {
|
|||||||
type IssueDisplayStatus,
|
type IssueDisplayStatus,
|
||||||
type IssuePriority,
|
type IssuePriority,
|
||||||
type IssueReviewPolicy,
|
type IssueReviewPolicy,
|
||||||
|
type IssueScope,
|
||||||
type IssueWorkMode,
|
type IssueWorkMode,
|
||||||
type IssueHarnessKind,
|
type IssueHarnessKind,
|
||||||
type SummarySlotScopeKind,
|
type SummarySlotScopeKind,
|
||||||
@@ -3136,7 +3138,13 @@ export * from "./muse-protocol.js";
|
|||||||
export * from "./muse-invitations.js";
|
export * from "./muse-invitations.js";
|
||||||
export * from "./fast-response.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 "./grok-bot.js";
|
||||||
export * from "./agent-observability.js";
|
export * from "./agent-observability.js";
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import type { IssueScope } from "./constants.js";
|
||||||
|
|
||||||
/** Origins that represent a person's ordinary task or onboarding request. */
|
/** Origins that represent a person's ordinary task or onboarding request. */
|
||||||
export const HUMAN_TASK_ORIGIN_KINDS = ["manual", "onboarding_first_task"] as const;
|
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],
|
(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";
|
||||||
|
}
|
||||||
@@ -31,6 +31,7 @@ import type {
|
|||||||
IssueRecoveryActionOwnerType,
|
IssueRecoveryActionOwnerType,
|
||||||
IssueBlockerStallRelation,
|
IssueBlockerStallRelation,
|
||||||
IssueRecoveryActionStatus,
|
IssueRecoveryActionStatus,
|
||||||
|
IssueScope,
|
||||||
IssueWorkMode,
|
IssueWorkMode,
|
||||||
IssueThreadInteractionContinuationPolicy,
|
IssueThreadInteractionContinuationPolicy,
|
||||||
IssueThreadInteractionCanonicalResolverPolicy,
|
IssueThreadInteractionCanonicalResolverPolicy,
|
||||||
@@ -957,6 +958,7 @@ export interface Issue {
|
|||||||
description: string | null;
|
description: string | null;
|
||||||
descriptionTruncated?: boolean;
|
descriptionTruncated?: boolean;
|
||||||
status: IssueStatus;
|
status: IssueStatus;
|
||||||
|
scope?: IssueScope;
|
||||||
workMode: IssueWorkMode;
|
workMode: IssueWorkMode;
|
||||||
priority: IssuePriority;
|
priority: IssuePriority;
|
||||||
reviewPolicy: IssueReviewPolicy | null;
|
reviewPolicy: IssueReviewPolicy | null;
|
||||||
@@ -1065,6 +1067,7 @@ export type CompactIssue = Pick<
|
|||||||
| "description"
|
| "description"
|
||||||
| "displayStatus"
|
| "displayStatus"
|
||||||
| "status"
|
| "status"
|
||||||
|
| "scope"
|
||||||
| "workMode"
|
| "workMode"
|
||||||
| "priority"
|
| "priority"
|
||||||
| "reviewPolicy"
|
| "reviewPolicy"
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ import {
|
|||||||
ISSUE_RECOVERY_ACTION_OWNER_TYPES,
|
ISSUE_RECOVERY_ACTION_OWNER_TYPES,
|
||||||
ISSUE_RECOVERY_ACTION_STATUSES,
|
ISSUE_RECOVERY_ACTION_STATUSES,
|
||||||
ISSUE_REVIEW_POLICIES,
|
ISSUE_REVIEW_POLICIES,
|
||||||
|
ISSUE_SCOPES,
|
||||||
ISSUE_WORK_MODES,
|
ISSUE_WORK_MODES,
|
||||||
clampIssueRequestDepth,
|
clampIssueRequestDepth,
|
||||||
ISSUE_STATUSES,
|
ISSUE_STATUSES,
|
||||||
@@ -839,6 +840,7 @@ const createIssueBaseSchema = z.object({
|
|||||||
title: z.string().min(1),
|
title: z.string().min(1),
|
||||||
description: multilineTextSchema.optional().nullable(),
|
description: multilineTextSchema.optional().nullable(),
|
||||||
status: z.enum(ISSUE_STATUSES),
|
status: z.enum(ISSUE_STATUSES),
|
||||||
|
scope: z.enum(ISSUE_SCOPES).optional(),
|
||||||
workMode: z.enum(ISSUE_WORK_MODES).optional().default("standard"),
|
workMode: z.enum(ISSUE_WORK_MODES).optional().default("standard"),
|
||||||
harnessKind: z.enum(ISSUE_HARNESS_KINDS).optional().nullable(),
|
harnessKind: z.enum(ISSUE_HARNESS_KINDS).optional().nullable(),
|
||||||
priority: z.enum(ISSUE_PRIORITIES).optional().default("medium"),
|
priority: z.enum(ISSUE_PRIORITIES).optional().default("medium"),
|
||||||
|
|||||||
@@ -17,6 +17,7 @@
|
|||||||
"titleNeedsGeneration": false,
|
"titleNeedsGeneration": false,
|
||||||
"description": "Uses [@Detail project](project://<id:2>)",
|
"description": "Uses [@Detail project](project://<id:2>)",
|
||||||
"status": "in_progress",
|
"status": "in_progress",
|
||||||
|
"scope": "board",
|
||||||
"statusVersion": 0,
|
"statusVersion": 0,
|
||||||
"lastStatusDecisionId": null,
|
"lastStatusDecisionId": null,
|
||||||
"workMode": "standard",
|
"workMode": "standard",
|
||||||
|
|||||||
@@ -0,0 +1,529 @@
|
|||||||
|
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());
|
||||||
|
|
||||||
|
// Explicit scope wins even when includeAgentCreatedTasks=false.
|
||||||
|
const explicitAgentRes = await request(app)
|
||||||
|
.get(`/api/companies/${companyId}/issues?scope=agent&includeAgentCreatedTasks=false`)
|
||||||
|
.expect(200);
|
||||||
|
expect(explicitAgentRes.body.map((row: { id: string }) => row.id)).toEqual([agentTask.id]);
|
||||||
|
|
||||||
|
// Non-conversation issues cannot take scope 'chat' on create or update.
|
||||||
|
await expect(
|
||||||
|
svc.create(companyId, {
|
||||||
|
title: "Bogus non-chat",
|
||||||
|
status: "todo",
|
||||||
|
scope: "chat",
|
||||||
|
createdByUserId: userId,
|
||||||
|
}),
|
||||||
|
).rejects.toMatchObject({ status: 422 });
|
||||||
|
await expect(
|
||||||
|
svc.update(boardTask.id, { scope: "chat" }),
|
||||||
|
).rejects.toMatchObject({ status: 422 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("forbids agent actors from forging scope='board' on POST, child POST, decomposition POST, or PATCH", async () => {
|
||||||
|
const { companyId, userId, actor: boardActor } = await seedCompanyWithBoardAccess(ctx.db, "Issue Scope Agent Authz");
|
||||||
|
const [agent] = await ctx.db
|
||||||
|
.insert(agents)
|
||||||
|
.values({ companyId, name: "Caller", role: "engineer", adapterType: "process" })
|
||||||
|
.returning();
|
||||||
|
const svc = issueService(ctx.db);
|
||||||
|
const agentTask = await svc.create(companyId, {
|
||||||
|
title: "Agent task",
|
||||||
|
status: "todo",
|
||||||
|
createdByAgentId: agent!.id,
|
||||||
|
assigneeAgentId: agent!.id,
|
||||||
|
});
|
||||||
|
const agentActor = {
|
||||||
|
type: "agent",
|
||||||
|
companyId,
|
||||||
|
agentId: agent!.id,
|
||||||
|
runId: undefined,
|
||||||
|
source: "agent_jwt",
|
||||||
|
onBehalfOfUserId: null,
|
||||||
|
onBehalfOfMemberships: [],
|
||||||
|
} as unknown as Parameters<typeof routeApp>[1];
|
||||||
|
const agentApp = routeApp(ctx.db, agentActor, issueRoutes);
|
||||||
|
const boardApp = routeApp(ctx.db, boardActor, issueRoutes);
|
||||||
|
|
||||||
|
await request(agentApp)
|
||||||
|
.post(`/api/companies/${companyId}/issues`)
|
||||||
|
.send({ title: "Spoofed board task", status: "todo", scope: "board" })
|
||||||
|
.expect(403);
|
||||||
|
|
||||||
|
await request(agentApp)
|
||||||
|
.post(`/api/issues/${agentTask.id}/children`)
|
||||||
|
.send({ title: "Spoofed board child", status: "todo", scope: "board" })
|
||||||
|
.expect(403);
|
||||||
|
|
||||||
|
await request(agentApp)
|
||||||
|
.post(`/api/issues/${agentTask.id}/accepted-plan-decompositions`)
|
||||||
|
.send({
|
||||||
|
acceptedPlanRevisionId: randomUUID(),
|
||||||
|
children: [{ title: "Spoofed plan child", status: "todo", scope: "board" }],
|
||||||
|
})
|
||||||
|
.expect(403);
|
||||||
|
|
||||||
|
await request(agentApp)
|
||||||
|
.patch(`/api/issues/${agentTask.id}`)
|
||||||
|
.send({ scope: "board" })
|
||||||
|
.expect(403);
|
||||||
|
expect((await svc.getById(agentTask.id))?.scope).toBe("agent");
|
||||||
|
|
||||||
|
// Direct service creation by an agent without handoff provenance also rejects scope='board'.
|
||||||
|
await expect(
|
||||||
|
svc.create(companyId, {
|
||||||
|
title: "Direct service spoof",
|
||||||
|
status: "todo",
|
||||||
|
scope: "board",
|
||||||
|
createdByAgentId: agent!.id,
|
||||||
|
}),
|
||||||
|
).rejects.toMatchObject({ status: 403 });
|
||||||
|
|
||||||
|
// A normal agent-created issue or child defaults to 'agent' cleanly.
|
||||||
|
const createdByAgent = await request(agentApp)
|
||||||
|
.post(`/api/companies/${companyId}/issues`)
|
||||||
|
.send({ title: "Ordinary agent task", status: "todo" })
|
||||||
|
.expect(201);
|
||||||
|
expect(createdByAgent.body.scope).toBe("agent");
|
||||||
|
|
||||||
|
const boardChild = await request(boardApp)
|
||||||
|
.post(`/api/issues/${agentTask.id}/children`)
|
||||||
|
.send({ title: "Board child", status: "todo", scope: "board" })
|
||||||
|
.expect(201);
|
||||||
|
expect(boardChild.body.scope).toBe("board");
|
||||||
|
expect(userId).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
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());
|
||||||
|
});
|
||||||
|
|
||||||
|
it("derives scope='agent' for creatorless imported tasks so includeAgentCreatedTasks=false excludes them", async () => {
|
||||||
|
const { companyId } = await seedCompanyWithBoardAccess(ctx.db, "Imported scope");
|
||||||
|
const svc = issueService(ctx.db);
|
||||||
|
const importedId = randomUUID();
|
||||||
|
|
||||||
|
await svc.importIssues(companyId, [
|
||||||
|
{
|
||||||
|
id: importedId,
|
||||||
|
ref: "imported-task",
|
||||||
|
projectId: null,
|
||||||
|
projectWorkspaceId: null,
|
||||||
|
title: "Imported historical task",
|
||||||
|
description: null,
|
||||||
|
assigneeAgentId: null,
|
||||||
|
status: "todo",
|
||||||
|
priority: "medium",
|
||||||
|
billingCode: null,
|
||||||
|
assigneeAdapterOverrides: null,
|
||||||
|
executionWorkspaceSettings: null,
|
||||||
|
labelIds: [],
|
||||||
|
monitorNotes: null,
|
||||||
|
monitorScheduledBy: null,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
const imported = await svc.getById(importedId);
|
||||||
|
expect(imported?.scope).toBe("agent");
|
||||||
|
expect(await svc.list(companyId, { includeAgentCreatedTasks: false })).toEqual([]);
|
||||||
|
expect((await svc.list(companyId, { scope: "agent" })).map((row) => row.id)).toEqual([
|
||||||
|
importedId,
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -3,7 +3,7 @@ import { eq, sql } from "drizzle-orm";
|
|||||||
import request from "supertest";
|
import request from "supertest";
|
||||||
import { expect, it } from "vitest";
|
import { expect, it } from "vitest";
|
||||||
import { activityLog, agents, authUsers, chatConversations, chatEndpoints, chatMessageLinks, issueComments, issueReadStates, issues, issueThreadInteractions, toolApplications, toolConnections } from "@paperclipai/db";
|
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 { issueRoutes } from "../routes/issues.js";
|
||||||
import { issueService } from "../services/issues.js";
|
import { issueService } from "../services/issues.js";
|
||||||
import { issueThreadInteractionService } from "../services/issue-thread-interactions.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" },
|
{ id: randomUUID(), companyId, title: "Visibility manually run routine", createdByUserId: userId, originKind: "routine_execution" },
|
||||||
];
|
];
|
||||||
await ctx.db.insert(issues).values([
|
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: other.companyId, title: "Visibility other company", createdByUserId: other.userId },
|
||||||
{ companyId, title: "Visibility private task", createdByUserId: other.userId, visibility: "private" },
|
{ 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 { 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()]));
|
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]) => ({
|
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,
|
responsibleUserId: userId,
|
||||||
assigneeUserId: name === "assigned" ? userId : null,
|
assigneeUserId: name === "assigned" ? userId : null,
|
||||||
createdByUserId: name === "manual" || name === "channelManual" ? 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 () => {
|
it("admits open addressed requests and removes that reason when they resolve", async () => {
|
||||||
const { companyId, userId, actor } = await seedCompanyWithBoardAccess(ctx.db, "Human requests");
|
const { companyId, userId, actor } = await seedCompanyWithBoardAccess(ctx.db, "Human requests");
|
||||||
const ids = Object.fromEntries(["question", "confirmation", "otherUser", "creatorExcluded", "private"].map((name) => [name, randomUUID()]));
|
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]) => ({
|
const requests = await ctx.db.insert(issueThreadInteractions).values(Object.entries(ids).map(([name, issueId]) => ({
|
||||||
companyId, issueId, kind: name === "confirmation" ? "request_confirmation" : "ask_user_questions",
|
companyId, issueId, kind: name === "confirmation" ? "request_confirmation" : "ask_user_questions",
|
||||||
addresseeUserId: name === "otherUser" ? "someone-else" : userId,
|
addresseeUserId: name === "otherUser" ? "someone-else" : userId,
|
||||||
@@ -292,7 +292,7 @@ describeEmbeddedPostgres("issue creation visibility", () => {
|
|||||||
const names = ["historical", "done", "cancelled", "current", "authorization"];
|
const names = ["historical", "done", "cancelled", "current", "authorization"];
|
||||||
const ids = Object.fromEntries(names.map((name) => [name, randomUUID()]));
|
const ids = Object.fromEntries(names.map((name) => [name, randomUUID()]));
|
||||||
await ctx.db.insert(issues).values(names.map((name) => ({
|
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",
|
status: name === "done" || name === "cancelled" ? name : "todo",
|
||||||
createdAt: new Date("2026-01-01"), updatedAt: new Date("2026-01-01"),
|
createdAt: new Date("2026-01-01"), updatedAt: new Date("2026-01-01"),
|
||||||
})));
|
})));
|
||||||
|
|||||||
@@ -148,6 +148,7 @@ import {
|
|||||||
linkIssueApprovalSchema,
|
linkIssueApprovalSchema,
|
||||||
issueDocumentKeySchema,
|
issueDocumentKeySchema,
|
||||||
ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY,
|
ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY,
|
||||||
|
ISSUE_SCOPES,
|
||||||
ISSUE_WATCHDOG_DISCOVERY_KINDS,
|
ISSUE_WATCHDOG_DISCOVERY_KINDS,
|
||||||
TASK_WATCHDOG_PRODUCT_BUG_ORIGIN_KIND,
|
TASK_WATCHDOG_PRODUCT_BUG_ORIGIN_KIND,
|
||||||
ONBOARDING_FIRST_TASK_ORIGIN_KIND,
|
ONBOARDING_FIRST_TASK_ORIGIN_KIND,
|
||||||
@@ -244,6 +245,7 @@ import {
|
|||||||
routineService,
|
routineService,
|
||||||
workProductService,
|
workProductService,
|
||||||
} from "../services/index.js";
|
} from "../services/index.js";
|
||||||
|
import { parseScopeFilter } from "../services/issue-visibility.js";
|
||||||
import {
|
import {
|
||||||
runnerGoalService,
|
runnerGoalService,
|
||||||
RunnerGoalActionError,
|
RunnerGoalActionError,
|
||||||
@@ -3071,6 +3073,7 @@ function toCompactIssue(issue: any): CompactIssue {
|
|||||||
title: issue.title,
|
title: issue.title,
|
||||||
description: issue.description,
|
description: issue.description,
|
||||||
status: issue.status,
|
status: issue.status,
|
||||||
|
...(issue.scope !== undefined ? { scope: issue.scope } : {}),
|
||||||
workMode: issue.workMode,
|
workMode: issue.workMode,
|
||||||
priority: issue.priority,
|
priority: issue.priority,
|
||||||
reviewPolicy: issue.reviewPolicy,
|
reviewPolicy: issue.reviewPolicy,
|
||||||
@@ -3445,6 +3448,43 @@ function parseIssueListUuidQueryParams(
|
|||||||
return { ok: true, values };
|
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(", ")}` };
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const scopes = parseScopeFilter(entries);
|
||||||
|
return { ok: true, value: scopes.length > 0 ? scopes.join(",") : undefined };
|
||||||
|
} catch (err) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
error: err instanceof Error ? err.message : `scope must be one of ${ISSUE_SCOPES.join(", ")}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertActorMayWriteIssueScope(
|
||||||
|
req: Request,
|
||||||
|
requestedScope: unknown,
|
||||||
|
existingScope?: string | null,
|
||||||
|
) {
|
||||||
|
if (
|
||||||
|
req.actor.type === "agent" &&
|
||||||
|
requestedScope === "board" &&
|
||||||
|
existingScope !== "board"
|
||||||
|
) {
|
||||||
|
throw forbidden(
|
||||||
|
existingScope === undefined
|
||||||
|
? "Only board users can create issues with scope 'board'"
|
||||||
|
: "Only board users can promote issues to scope 'board'",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function coordinateIssueListGet(input: {
|
async function coordinateIssueListGet(input: {
|
||||||
req: Request;
|
req: Request;
|
||||||
companyId: string;
|
companyId: string;
|
||||||
@@ -8862,6 +8902,11 @@ export function issueRoutes(
|
|||||||
let assigneeAgentId: string | null | undefined;
|
let assigneeAgentId: string | null | undefined;
|
||||||
const rawUpdatedSince = req.query.updatedSince as string | undefined;
|
const rawUpdatedSince = req.query.updatedSince as string | undefined;
|
||||||
const rawUpdatedBefore = req.query.updatedBefore 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 (
|
if (
|
||||||
assigneeUserFilterRaw === "me" &&
|
assigneeUserFilterRaw === "me" &&
|
||||||
@@ -9010,6 +9055,7 @@ export function issueRoutes(
|
|||||||
attention: attention === "blocked" ? "blocked" : undefined,
|
attention: attention === "blocked" ? "blocked" : undefined,
|
||||||
status: req.query.status as string | string[] | undefined,
|
status: req.query.status as string | string[] | undefined,
|
||||||
displayStatus: req.query.displayStatus as string | string[] | undefined,
|
displayStatus: req.query.displayStatus as string | string[] | undefined,
|
||||||
|
scope: scopeQuery.value,
|
||||||
assigneeAgentId,
|
assigneeAgentId,
|
||||||
participantAgentId: uuidFilters.participantAgentId,
|
participantAgentId: uuidFilters.participantAgentId,
|
||||||
assigneeUserId,
|
assigneeUserId,
|
||||||
@@ -9188,12 +9234,18 @@ export function issueRoutes(
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const countUuidFilters = countUuidQuery.values;
|
const countUuidFilters = countUuidQuery.values;
|
||||||
|
const countScopeQuery = parseIssueListScopeQueryParam(req.query.scope);
|
||||||
|
if (!countScopeQuery.ok) {
|
||||||
|
res.status(400).json({ error: countScopeQuery.error });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const blockedCountFilters = {
|
const blockedCountFilters = {
|
||||||
readCondition: await issueReadSqlCondition(db, req.actor),
|
readCondition: await issueReadSqlCondition(db, req.actor),
|
||||||
attention: "blocked",
|
attention: "blocked",
|
||||||
status: req.query.status as string | string[] | undefined,
|
status: req.query.status as string | string[] | undefined,
|
||||||
displayStatus: req.query.displayStatus as string | string[] | undefined,
|
displayStatus: req.query.displayStatus as string | string[] | undefined,
|
||||||
|
scope: countScopeQuery.value,
|
||||||
assigneeAgentId: req.query.assigneeAgentId as string | undefined,
|
assigneeAgentId: req.query.assigneeAgentId as string | undefined,
|
||||||
participantAgentId: countUuidFilters.participantAgentId,
|
participantAgentId: countUuidFilters.participantAgentId,
|
||||||
assigneeUserId: req.query.assigneeUserId as string | undefined,
|
assigneeUserId: req.query.assigneeUserId as string | undefined,
|
||||||
@@ -13461,6 +13513,7 @@ export function issueRoutes(
|
|||||||
);
|
);
|
||||||
let deduplicationReason: "idempotency_key" | "recent_open_title" | null =
|
let deduplicationReason: "idempotency_key" | "recent_open_title" | null =
|
||||||
null;
|
null;
|
||||||
|
assertActorMayWriteIssueScope(req, createBody.scope);
|
||||||
const createInput = {
|
const createInput = {
|
||||||
...createBody,
|
...createBody,
|
||||||
workspaceSelectionActor: req.actor,
|
workspaceSelectionActor: req.actor,
|
||||||
@@ -13780,6 +13833,7 @@ export function issueRoutes(
|
|||||||
? { assigneeAgentId: normalizedAssigneeAgentId }
|
? { assigneeAgentId: normalizedAssigneeAgentId }
|
||||||
: {}),
|
: {}),
|
||||||
};
|
};
|
||||||
|
assertActorMayWriteIssueScope(req, createBody.scope);
|
||||||
// Board users nest freely, and watchdog follow-ups are located by parent.
|
// Board users nest freely, and watchdog follow-ups are located by parent.
|
||||||
// Other agents build at most parent → child trees: a child of a child is
|
// Other agents build at most parent → child trees: a child of a child is
|
||||||
// placed beside it instead (never rejected).
|
// placed beside it instead (never rejected).
|
||||||
@@ -14054,6 +14108,7 @@ export function issueRoutes(
|
|||||||
? { assigneeAgentId: normalizedAssigneeAgentId }
|
? { assigneeAgentId: normalizedAssigneeAgentId }
|
||||||
: {}),
|
: {}),
|
||||||
};
|
};
|
||||||
|
assertActorMayWriteIssueScope(req, childBody.scope);
|
||||||
requestedChildren.push(childBody);
|
requestedChildren.push(childBody);
|
||||||
assertNoAgentHostWorkspaceCommandMutation(
|
assertNoAgentHostWorkspaceCommandMutation(
|
||||||
req,
|
req,
|
||||||
@@ -14875,6 +14930,7 @@ export function issueRoutes(
|
|||||||
// An authorized agent may restrict a task; widening access remains an owner/admin action.
|
// An authorized agent may restrict a task; widening access remains an owner/admin action.
|
||||||
if (req.body.visibility !== undefined && !(req.actor.type === "agent" && req.body.visibility === "private")
|
if (req.body.visibility !== undefined && !(req.actor.type === "agent" && req.body.visibility === "private")
|
||||||
&& !(await resolveManagedIssueForPrivacy(req, res, existing))) return;
|
&& !(await resolveManagedIssueForPrivacy(req, res, existing))) return;
|
||||||
|
assertActorMayWriteIssueScope(req, req.body.scope, existing.scope);
|
||||||
// MCP task changes cannot stop a run or implicitly decide a pending review.
|
// MCP task changes cannot stop a run or implicitly decide a pending review.
|
||||||
const mcpParticipationChange = req.actor.source === "mcp_oauth" &&
|
const mcpParticipationChange = req.actor.source === "mcp_oauth" &&
|
||||||
["status", "assigneeAgentId", "assigneeUserId", "blockedByIssueIds", "parentId", "projectId"].some(key => req.body[key] !== undefined);
|
["status", "assigneeAgentId", "assigneeUserId", "blockedByIssueIds", "parentId", "projectId"].some(key => req.body[key] !== undefined);
|
||||||
|
|||||||
@@ -5740,6 +5740,7 @@ export function issueThreadInteractionService(
|
|||||||
conversationId: sourceConversation.id,
|
conversationId: sourceConversation.id,
|
||||||
sessionGeneration: sourceConversation.conversationSessionGeneration,
|
sessionGeneration: sourceConversation.conversationSessionGeneration,
|
||||||
} } : {}),
|
} } : {}),
|
||||||
|
...(sourceConversation && !parentIssueId ? { scope: "board" as const, isExplicitBoardHandoff: true } : {}),
|
||||||
} satisfies Parameters<ReturnType<typeof issueService>["createChild"]>[1];
|
} satisfies Parameters<ReturnType<typeof issueService>["createChild"]>[1];
|
||||||
const service = issueService(tx as unknown as Db);
|
const service = issueService(tx as unknown as Db);
|
||||||
// A nested suggestion may be placed beside its suggested parent, under
|
// A nested suggestion may be placed beside its suggested parent, under
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import { nonIdleSlackIssueCondition } from "./slack-conversation-state.js";
|
import { nonIdleSlackIssueCondition } from "./slack-conversation-state.js";
|
||||||
import { and, isNull, isNotNull, or, type SQL } from "drizzle-orm";
|
import { and, eq, inArray, isNull, isNotNull, ne, or, type SQL } from "drizzle-orm";
|
||||||
import { issues } from "@paperclipai/db";
|
import { issues } from "@paperclipai/db";
|
||||||
|
import { ISSUE_SCOPES, type IssueScope } from "@paperclipai/shared";
|
||||||
|
import { unprocessable } from "../errors.js";
|
||||||
|
|
||||||
export function visibleIssueCondition(): SQL {
|
export function visibleIssueCondition(): SQL {
|
||||||
return and(isNull(issues.hiddenAt), isNull(issues.harnessKind))!;
|
return and(isNull(issues.hiddenAt), isNull(issues.harnessKind))!;
|
||||||
@@ -10,9 +12,59 @@ export function visibleIssueSql(alias = "issues") {
|
|||||||
return `"${alias}"."hidden_at" IS NULL AND "${alias}"."harness_kind" IS NULL`;
|
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))!;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parse and validate comma-separated or repeated issue scope filters. */
|
||||||
|
export function parseScopeFilter(
|
||||||
|
input: IssueScope | string | readonly string[] | undefined,
|
||||||
|
): IssueScope[] {
|
||||||
|
if (input === undefined || input === null) return [];
|
||||||
|
const entries = Array.isArray(input)
|
||||||
|
? input
|
||||||
|
: typeof input === "string"
|
||||||
|
? [input]
|
||||||
|
: [];
|
||||||
|
const scopes = [
|
||||||
|
...new Set(
|
||||||
|
entries
|
||||||
|
.flatMap((entry) => (typeof entry === "string" ? entry.split(",") : []))
|
||||||
|
.map((scope) => scope.trim())
|
||||||
|
.filter(Boolean),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
for (const scope of scopes) {
|
||||||
|
if (!ISSUE_SCOPES.includes(scope as IssueScope)) {
|
||||||
|
throw unprocessable(`Invalid issue scope: ${scope}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return scopes as IssueScope[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resolve the surface scope SQL condition for issue list, count, and inbox queries. */
|
||||||
|
export function surfaceScopeCondition(filters?: {
|
||||||
|
scope?: IssueScope | string | readonly IssueScope[];
|
||||||
|
q?: string;
|
||||||
|
issueIds?: string[];
|
||||||
|
}): { scopes: IssueScope[]; condition: SQL | undefined } {
|
||||||
|
const scopes = parseScopeFilter(filters?.scope);
|
||||||
|
if (scopes.length > 0) {
|
||||||
|
return {
|
||||||
|
scopes,
|
||||||
|
condition: scopes.length === 1 ? eq(issues.scope, scopes[0]!) : inArray(issues.scope, scopes),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (!filters?.q?.trim() && !filters?.issueIds) {
|
||||||
|
return { scopes, condition: nonChatAndChannelIssueCondition() };
|
||||||
|
}
|
||||||
|
return { scopes, condition: undefined };
|
||||||
|
}
|
||||||
|
|
||||||
/** Work queues and execution totals omit persistent conversation containers. */
|
/** Work queues and execution totals omit persistent conversation containers. */
|
||||||
export function executionIssueCondition(): SQL {
|
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 {
|
export function attentionIssueCondition(includeConversations = false): SQL {
|
||||||
|
|||||||
@@ -161,12 +161,14 @@ import type {
|
|||||||
IssueBlockedInboxAttention,
|
IssueBlockedInboxAttention,
|
||||||
IssueBlockedInboxIssueRef,
|
IssueBlockedInboxIssueRef,
|
||||||
IssueRelationIssueSummary,
|
IssueRelationIssueSummary,
|
||||||
|
IssueScope,
|
||||||
IssueWatchdogSummary,
|
IssueWatchdogSummary,
|
||||||
LowTrustBoundary,
|
LowTrustBoundary,
|
||||||
SuccessfulRunHandoffState,
|
SuccessfulRunHandoffState,
|
||||||
} from "@paperclipai/shared";
|
} from "@paperclipai/shared";
|
||||||
import {
|
import {
|
||||||
clampIssueRequestDepth,
|
clampIssueRequestDepth,
|
||||||
|
deriveDefaultIssueScope,
|
||||||
extractAgentMentionIds,
|
extractAgentMentionIds,
|
||||||
extractProjectMentionIds,
|
extractProjectMentionIds,
|
||||||
issueCommentAuthorTypeSchema,
|
issueCommentAuthorTypeSchema,
|
||||||
@@ -266,7 +268,13 @@ import {
|
|||||||
type IssueGraphLivenessInput,
|
type IssueGraphLivenessInput,
|
||||||
type IssueLivenessFinding,
|
type IssueLivenessFinding,
|
||||||
} from "./recovery/issue-graph-liveness.js";
|
} from "./recovery/issue-graph-liveness.js";
|
||||||
import { visibleIssueCondition } from "./issue-visibility.js";
|
import {
|
||||||
|
nonChatAndChannelIssueCondition,
|
||||||
|
parseScopeFilter,
|
||||||
|
surfaceScopeCondition,
|
||||||
|
visibleIssueCondition,
|
||||||
|
} from "./issue-visibility.js";
|
||||||
|
export { parseScopeFilter };
|
||||||
import { finalizeStatusCardsForStalledGeneration } from "./status-card-finalization.js";
|
import { finalizeStatusCardsForStalledGeneration } from "./status-card-finalization.js";
|
||||||
import { finalizeSummarySlotsForTerminalIssue } from "./summary-slot-finalization.js";
|
import { finalizeSummarySlotsForTerminalIssue } from "./summary-slot-finalization.js";
|
||||||
import {
|
import {
|
||||||
@@ -1890,6 +1898,7 @@ export interface IssueFilters {
|
|||||||
attention?: "blocked";
|
attention?: "blocked";
|
||||||
status?: string | readonly string[];
|
status?: string | readonly string[];
|
||||||
displayStatus?: string | readonly string[];
|
displayStatus?: string | readonly string[];
|
||||||
|
scope?: IssueScope | string | readonly IssueScope[];
|
||||||
/**
|
/**
|
||||||
* Filter by assignee agent ID.
|
* Filter by assignee agent ID.
|
||||||
* - `string` (UUID): match issues assigned to that agent.
|
* - `string` (UUID): match issues assigned to that agent.
|
||||||
@@ -2078,6 +2087,8 @@ type IssueCreateInput = Omit<typeof issues.$inferInsert, "companyId" | "title" |
|
|||||||
initialPlan?: string | null;
|
initialPlan?: string | null;
|
||||||
/** Internal, server-derived provenance for an accepted in-app chat suggestion. */
|
/** Internal, server-derived provenance for an accepted in-app chat suggestion. */
|
||||||
conversationHandoff?: { conversationId: string; sessionGeneration: number };
|
conversationHandoff?: { conversationId: string; sessionGeneration: number };
|
||||||
|
/** True for explicit chat-to-board handoffs that should default to scope 'board'. */
|
||||||
|
isExplicitBoardHandoff?: boolean;
|
||||||
labelIds?: string[];
|
labelIds?: string[];
|
||||||
blockedByIssueIds?: string[];
|
blockedByIssueIds?: string[];
|
||||||
inheritExecutionWorkspaceFromIssueId?: string | null;
|
inheritExecutionWorkspaceFromIssueId?: string | null;
|
||||||
@@ -5335,6 +5346,7 @@ const issueListSelect = {
|
|||||||
END
|
END
|
||||||
`,
|
`,
|
||||||
status: issues.status,
|
status: issues.status,
|
||||||
|
scope: issues.scope,
|
||||||
displayStatus: issueDisplayStatusSql(),
|
displayStatus: issueDisplayStatusSql(),
|
||||||
statusVersion: issues.statusVersion,
|
statusVersion: issues.statusVersion,
|
||||||
lastStatusDecisionId: issues.lastStatusDecisionId,
|
lastStatusDecisionId: issues.lastStatusDecisionId,
|
||||||
@@ -6705,9 +6717,11 @@ function assertValidAssigneeAgentFilter(
|
|||||||
|
|
||||||
function creationVisibilityCondition(companyId: string, filters?: IssueFilters) {
|
function creationVisibilityCondition(companyId: string, filters?: IssueFilters) {
|
||||||
if (filters?.includeAgentCreatedTasks !== false) return undefined;
|
if (filters?.includeAgentCreatedTasks !== false) return undefined;
|
||||||
|
if (parseScopeFilter(filters?.scope).length > 0) return undefined;
|
||||||
|
const boardScopeCondition = eq(issues.scope, "board");
|
||||||
return filters.creationVisibilityUserId
|
return filters.creationVisibilityUserId
|
||||||
? or(humanCreatedIssueCondition(), touchedByUserCondition(companyId, filters.creationVisibilityUserId))!
|
? or(boardScopeCondition, touchedByUserCondition(companyId, filters.creationVisibilityUserId))!
|
||||||
: humanCreatedIssueCondition();
|
: boardScopeCondition;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function blockedInboxIssueConditions(
|
async function blockedInboxIssueConditions(
|
||||||
@@ -6720,6 +6734,8 @@ async function blockedInboxIssueConditions(
|
|||||||
visibleIssueCondition(),
|
visibleIssueCondition(),
|
||||||
notInArray(issues.status, [...BLOCKED_INBOX_TERMINAL_STATUSES]),
|
notInArray(issues.status, [...BLOCKED_INBOX_TERMINAL_STATUSES]),
|
||||||
];
|
];
|
||||||
|
const { condition: scopeCondition } = surfaceScopeCondition(filters);
|
||||||
|
if (scopeCondition) conditions.push(scopeCondition);
|
||||||
if (filters?.readCondition) conditions.push(filters.readCondition);
|
if (filters?.readCondition) conditions.push(filters.readCondition);
|
||||||
const creationCondition = creationVisibilityCondition(companyId, filters);
|
const creationCondition = creationVisibilityCondition(companyId, filters);
|
||||||
if (creationCondition) conditions.push(creationCondition);
|
if (creationCondition) conditions.push(creationCondition);
|
||||||
@@ -8559,7 +8575,7 @@ export function issueService(db: Db) {
|
|||||||
.from(participated).innerJoin(issues, eq(issues.id, sql`"mine_participants"."id"`)).where(and(
|
.from(participated).innerJoin(issues, eq(issues.id, sql`"mine_participants"."id"`)).where(and(
|
||||||
eq(issues.companyId, companyId),
|
eq(issues.companyId, companyId),
|
||||||
visibleIssueCondition(),
|
visibleIssueCondition(),
|
||||||
isNull(issues.conversationAgentId),
|
nonChatAndChannelIssueCondition(),
|
||||||
nonPluginOperationIssueCondition(),
|
nonPluginOperationIssueCondition(),
|
||||||
ne(issues.status, "cancelled"),
|
ne(issues.status, "cancelled"),
|
||||||
inboxVisibleForUserCondition(companyId, userId),
|
inboxVisibleForUserCondition(companyId, userId),
|
||||||
@@ -8617,13 +8633,12 @@ export function issueService(db: Db) {
|
|||||||
? sql<boolean>`NOT (${inboxVisibleForUserCondition(companyId, inboxArchive.userId)})`
|
? sql<boolean>`NOT (${inboxVisibleForUserCondition(companyId, inboxArchive.userId)})`
|
||||||
: undefined;
|
: undefined;
|
||||||
if (inboxArchive?.mode === "archived" && archivedCondition) conditions.push(archivedCondition);
|
if (inboxArchive?.mode === "archived" && archivedCondition) conditions.push(archivedCondition);
|
||||||
if (!filters?.q?.trim() && !filters?.issueIds) {
|
const { scopes, condition: scopeCondition } = surfaceScopeCondition(filters);
|
||||||
conditions.push(isNull(issues.conversationAgentId));
|
if (scopeCondition) conditions.push(scopeCondition);
|
||||||
// Explicit child navigation includes waiting chat tasks, just like
|
// Explicit child navigation includes waiting chat tasks, just like
|
||||||
// readable-child counts. Ambient lists still omit idle conversations.
|
// 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") {
|
if (!filters?.q?.trim() && !filters?.issueIds && !scopes.includes("channel") && !scopes.includes("chat") && !filters?.parentId && !filters?.parentIds && !filters?.descendantOf && !filters?.touchedByUserId && !filters?.unreadForUserId && !filters?.inboxArchivedByUserId && inboxArchive?.mode !== "archived") {
|
||||||
conditions.push(nonIdleSlackIssueCondition());
|
conditions.push(nonIdleSlackIssueCondition());
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (filters?.afterId) conditions.push(gt(issues.id, filters.afterId));
|
if (filters?.afterId) conditions.push(gt(issues.id, filters.afterId));
|
||||||
if (filters?.readCondition) conditions.push(filters.readCondition);
|
if (filters?.readCondition) conditions.push(filters.readCondition);
|
||||||
@@ -9026,11 +9041,10 @@ export function issueService(db: Db) {
|
|||||||
if (filters?.readCondition) conditions.push(filters.readCondition);
|
if (filters?.readCondition) conditions.push(filters.readCondition);
|
||||||
const creationCondition = creationVisibilityCondition(companyId, filters);
|
const creationCondition = creationVisibilityCondition(companyId, filters);
|
||||||
if (creationCondition) conditions.push(creationCondition);
|
if (creationCondition) conditions.push(creationCondition);
|
||||||
if (!filters?.q?.trim()) {
|
const { scopes, condition: scopeCondition } = surfaceScopeCondition(filters);
|
||||||
conditions.push(isNull(issues.conversationAgentId));
|
if (scopeCondition) conditions.push(scopeCondition);
|
||||||
if (!filters?.parentId && !filters?.parentIds && !filters?.touchedByUserId && !filters?.unreadForUserId && !filters?.inboxArchivedByUserId) {
|
if (!filters?.q?.trim() && !filters?.issueIds && !scopes.includes("channel") && !scopes.includes("chat") && !filters?.parentId && !filters?.parentIds && !filters?.touchedByUserId && !filters?.unreadForUserId && !filters?.inboxArchivedByUserId) {
|
||||||
conditions.push(nonIdleSlackIssueCondition());
|
conditions.push(nonIdleSlackIssueCondition());
|
||||||
}
|
|
||||||
}
|
}
|
||||||
const displayStatuses = parseStatusFilter(filters?.displayStatus);
|
const displayStatuses = parseStatusFilter(filters?.displayStatus);
|
||||||
if (displayStatuses.length) conditions.push(inArray(issueDisplayStatusSql(), displayStatuses));
|
if (displayStatuses.length) conditions.push(inArray(issueDisplayStatusSql(), displayStatuses));
|
||||||
@@ -10635,6 +10649,7 @@ export function issueService(db: Db) {
|
|||||||
workspaceSelection, workspaceSelectionSource = "explicit", workspaceSelectionActor,
|
workspaceSelection, workspaceSelectionSource = "explicit", workspaceSelectionActor,
|
||||||
initialPlan,
|
initialPlan,
|
||||||
conversationHandoff,
|
conversationHandoff,
|
||||||
|
isExplicitBoardHandoff,
|
||||||
generateConversationTitle,
|
generateConversationTitle,
|
||||||
labelIds: inputLabelIds,
|
labelIds: inputLabelIds,
|
||||||
blockedByIssueIds,
|
blockedByIssueIds,
|
||||||
@@ -10678,6 +10693,12 @@ export function issueService(db: Db) {
|
|||||||
if (data.assigneeAgentId && data.assigneeUserId) {
|
if (data.assigneeAgentId && data.assigneeUserId) {
|
||||||
throw unprocessable("Issue can only have one assignee");
|
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 (issueData.conversationAgentId == null && issueData.scope === "chat") {
|
||||||
|
throw unprocessable("Non-conversation issues cannot have scope 'chat'");
|
||||||
|
}
|
||||||
if (data.assigneeAgentId) {
|
if (data.assigneeAgentId) {
|
||||||
await assertAssignableAgent(db, companyId, data.assigneeAgentId, {
|
await assertAssignableAgent(db, companyId, data.assigneeAgentId, {
|
||||||
kind: "work",
|
kind: "work",
|
||||||
@@ -11119,13 +11140,18 @@ export function issueService(db: Db) {
|
|||||||
}) : null;
|
}) : null;
|
||||||
// The task the creating run was bound to, when a run created this task.
|
// The task the creating run was bound to, when a run created this task.
|
||||||
let runSourceIssueId: string | null = null;
|
let runSourceIssueId: string | null = null;
|
||||||
|
let runSourceIssueIsConversation = false;
|
||||||
const sourceRunId = issueData.originRunId ?? actorRunId;
|
const sourceRunId = issueData.originRunId ?? actorRunId;
|
||||||
if (sourceRunId && isUuidLike(sourceRunId)) {
|
if (sourceRunId && isUuidLike(sourceRunId)) {
|
||||||
const [sourceRun] = await tx.select().from(heartbeatRuns)
|
const [sourceRun] = await tx.select().from(heartbeatRuns)
|
||||||
.where(and(eq(heartbeatRuns.id, sourceRunId), eq(heartbeatRuns.companyId, companyId)));
|
.where(and(eq(heartbeatRuns.id, sourceRunId), eq(heartbeatRuns.companyId, companyId)));
|
||||||
// Same binding rules as creation-source reads: native identity, issue
|
// Same binding rules as creation-source reads: native identity, issue
|
||||||
// scope, then legacy task context (including identifiers), company-scoped.
|
// 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
|
// Privacy follows structure: the requested parent (even when placed
|
||||||
// beside it), the chat that handed this off, or the run's task.
|
// beside it), the chat that handed this off, or the run's task.
|
||||||
@@ -11188,8 +11214,29 @@ export function issueService(db: Db) {
|
|||||||
.then((rows) => rows.length > 0));
|
.then((rows) => rows.length > 0));
|
||||||
if (!originPublic) originIssueId = null;
|
if (!originPublic) originIssueId = null;
|
||||||
}
|
}
|
||||||
|
const trustedBoardHandoff =
|
||||||
|
isExplicitBoardHandoff ??
|
||||||
|
Boolean(handoffSource || (runSourceIssueIsConversation && !issueData.parentId));
|
||||||
|
if (
|
||||||
|
issueData.scope === "board" &&
|
||||||
|
issueData.createdByAgentId != null &&
|
||||||
|
issueData.createdByUserId == null &&
|
||||||
|
!trustedBoardHandoff
|
||||||
|
) {
|
||||||
|
throw forbidden("Only board users or chat handoffs can create issues with scope 'board'");
|
||||||
|
}
|
||||||
|
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: trustedBoardHandoff,
|
||||||
|
});
|
||||||
const values = {
|
const values = {
|
||||||
...issueData,
|
...issueData,
|
||||||
|
scope: derivedScope,
|
||||||
workspaceSelection: workspaceIntent,
|
workspaceSelection: workspaceIntent,
|
||||||
visibility,
|
visibility,
|
||||||
privacyRootIssueId,
|
privacyRootIssueId,
|
||||||
@@ -11525,6 +11572,11 @@ export function issueService(db: Db) {
|
|||||||
responsibleUserId: null,
|
responsibleUserId: null,
|
||||||
requestDepth: clampIssueRequestDepth(undefined),
|
requestDepth: clampIssueRequestDepth(undefined),
|
||||||
originKind: "manual",
|
originKind: "manual",
|
||||||
|
scope: deriveDefaultIssueScope({
|
||||||
|
createdByAgentId: null,
|
||||||
|
createdByUserId: null,
|
||||||
|
originKind: "manual",
|
||||||
|
}),
|
||||||
// The caller resolves parentId against ids in this same batch, so a
|
// The caller resolves parentId against ids in this same batch, so a
|
||||||
// parent always lands in the same insert (rows arrive parents-first).
|
// parent always lands in the same insert (rows arrive parents-first).
|
||||||
parentId: row.parentId ?? null,
|
parentId: row.parentId ?? null,
|
||||||
@@ -11762,12 +11814,17 @@ export function issueService(db: Db) {
|
|||||||
await assertExecutionTaskParent(dbOrTx, existing.companyId, data.parentId);
|
await assertExecutionTaskParent(dbOrTx, existing.companyId, data.parentId);
|
||||||
}
|
}
|
||||||
if (existing.conversationAgentId) {
|
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)
|
if ((data.assigneeAgentId !== undefined && data.assigneeAgentId !== existing.conversationAgentId)
|
||||||
|| data.assigneeUserId || data.conversationAgentId !== undefined || data.conversationUserId !== undefined
|
|| data.assigneeUserId || data.conversationAgentId !== undefined || data.conversationUserId !== undefined
|
||||||
|| data.conversationState !== undefined || data.conversationSessionGeneration !== undefined
|
|| data.conversationState !== undefined || data.conversationSessionGeneration !== undefined
|
||||||
|| data.conversationBoundaryCommentId !== undefined || data.status === "done" || data.status === "cancelled") {
|
|| data.conversationBoundaryCommentId !== undefined || data.status === "done" || data.status === "cancelled") {
|
||||||
throw unprocessable("Conversation identity is fixed; finish the reply instead of completing or reassigning the conversation");
|
throw unprocessable("Conversation identity is fixed; finish the reply instead of completing or reassigning the conversation");
|
||||||
}
|
}
|
||||||
|
} else if (data.scope === "chat") {
|
||||||
|
throw unprocessable("Non-conversation issues cannot have scope 'chat'");
|
||||||
}
|
}
|
||||||
|
|
||||||
const {
|
const {
|
||||||
|
|||||||
@@ -2287,6 +2287,7 @@ export class PaperclipRunnerToolAuthority {
|
|||||||
parentDepthPolicy,
|
parentDepthPolicy,
|
||||||
...(parentIssueId ? { expectedParentId: placedParentId } : {}),
|
...(parentIssueId ? { expectedParentId: placedParentId } : {}),
|
||||||
...(workspaceSourceIssueId ? { inheritExecutionWorkspaceFromIssueId: workspaceSourceIssueId } : {}),
|
...(workspaceSourceIssueId ? { inheritExecutionWorkspaceFromIssueId: workspaceSourceIssueId } : {}),
|
||||||
|
...(context.issue.conversationAgentId && !parentIssueId ? { scope: "board" as const, isExplicitBoardHandoff: true } : {}),
|
||||||
createdByAgentId: this.binding.agentId,
|
createdByAgentId: this.binding.agentId,
|
||||||
originKind: "manual" as const,
|
originKind: "manual" as const,
|
||||||
originId: durableIdempotencyKey,
|
originId: durableIdempotencyKey,
|
||||||
|
|||||||
@@ -237,7 +237,7 @@
|
|||||||
"packages/shared/src/connector-availability.ts": "7797798bc989b774e8b6e62748ad689f66ab4193",
|
"packages/shared/src/connector-availability.ts": "7797798bc989b774e8b6e62748ad689f66ab4193",
|
||||||
"packages/shared/src/connector-identity.test.ts": "d58357707faefa7c98bb906cdaeb4db39d31081a",
|
"packages/shared/src/connector-identity.test.ts": "d58357707faefa7c98bb906cdaeb4db39d31081a",
|
||||||
"packages/shared/src/connector-identity.ts": "5ede83c9c5225dbe8af9cf3a49c74e477ef5b955",
|
"packages/shared/src/connector-identity.ts": "5ede83c9c5225dbe8af9cf3a49c74e477ef5b955",
|
||||||
"packages/shared/src/constants.ts": "4709afa0716747373733dd68755e10972fca0068",
|
"packages/shared/src/constants.ts": "de3d7da2b991efaf7f3eb5775af252e4f20d273f",
|
||||||
"packages/shared/src/crash-point-registry.ts": "3cbf2d290bc111061376b43020848623e493737c",
|
"packages/shared/src/crash-point-registry.ts": "3cbf2d290bc111061376b43020848623e493737c",
|
||||||
"packages/shared/src/crash-points.test.ts": "3564a1f62d22f54a3c2fb0a72b3a6cde17c957d2",
|
"packages/shared/src/crash-points.test.ts": "3564a1f62d22f54a3c2fb0a72b3a6cde17c957d2",
|
||||||
"packages/shared/src/crash-points.ts": "c15259f39610e352eac5423a491548ec1bae94fe",
|
"packages/shared/src/crash-points.ts": "c15259f39610e352eac5423a491548ec1bae94fe",
|
||||||
@@ -279,14 +279,14 @@
|
|||||||
"packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d",
|
"packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d",
|
||||||
"packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca",
|
"packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca",
|
||||||
"packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699",
|
"packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699",
|
||||||
"packages/shared/src/index.ts": "cdfadcb65f541b0d07a0af3c27ad2ec74d62bd08",
|
"packages/shared/src/index.ts": "159182d500385c0d13c20ff71627e20ba5c0d47f",
|
||||||
"packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca",
|
"packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca",
|
||||||
"packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075",
|
"packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075",
|
||||||
"packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9",
|
"packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9",
|
||||||
"packages/shared/src/issue-attribution.ts": "9c85194fb8739aeb5d70c8e128db6127a3057569",
|
"packages/shared/src/issue-attribution.ts": "9c85194fb8739aeb5d70c8e128db6127a3057569",
|
||||||
"packages/shared/src/issue-context-usage.ts": "2de0de824da2e4bce3c248335cdb5694d2a926ce",
|
"packages/shared/src/issue-context-usage.ts": "2de0de824da2e4bce3c248335cdb5694d2a926ce",
|
||||||
"packages/shared/src/issue-creation-source.test.ts": "afd00ce1ad8357daf860bc7e8e79340c765805f7",
|
"packages/shared/src/issue-creation-source.test.ts": "afd00ce1ad8357daf860bc7e8e79340c765805f7",
|
||||||
"packages/shared/src/issue-creation-source.ts": "48bd43f183b1a9f7bc233128ad0fe84c82e04c17",
|
"packages/shared/src/issue-creation-source.ts": "d8f750a0e70ad3af34f66dacc70ef968e148adad",
|
||||||
"packages/shared/src/issue-references.test.ts": "273873e8ecdb41aa9f88f76792880222822e39ee",
|
"packages/shared/src/issue-references.test.ts": "273873e8ecdb41aa9f88f76792880222822e39ee",
|
||||||
"packages/shared/src/issue-references.ts": "3516c974d3e1b8e9de3bc204408ea3f130705323",
|
"packages/shared/src/issue-references.ts": "3516c974d3e1b8e9de3bc204408ea3f130705323",
|
||||||
"packages/shared/src/issue-thread-interactions.test.ts": "6f516055744fcedd2e0c06ce82c6a1a019120762",
|
"packages/shared/src/issue-thread-interactions.test.ts": "6f516055744fcedd2e0c06ce82c6a1a019120762",
|
||||||
@@ -443,7 +443,7 @@
|
|||||||
"packages/shared/src/types/index.ts": "f8eedd126cf46462eed07976d2f9480ad9194428",
|
"packages/shared/src/types/index.ts": "f8eedd126cf46462eed07976d2f9480ad9194428",
|
||||||
"packages/shared/src/types/instance.ts": "406736718fa7e8f788d4e963291943d38c16a368",
|
"packages/shared/src/types/instance.ts": "406736718fa7e8f788d4e963291943d38c16a368",
|
||||||
"packages/shared/src/types/issue-tree-control.ts": "75489fffd491b8350b05caf57d7796419797d9df",
|
"packages/shared/src/types/issue-tree-control.ts": "75489fffd491b8350b05caf57d7796419797d9df",
|
||||||
"packages/shared/src/types/issue.ts": "5229e472a1e6da94bc8905d94ba08e6a0faa7ba8",
|
"packages/shared/src/types/issue.ts": "84699de7b12622743914b66ce6d6d2c91220a64a",
|
||||||
"packages/shared/src/types/live.ts": "b90e55e4de8600c6fc17d7fa8d89079d4ae655ec",
|
"packages/shared/src/types/live.ts": "b90e55e4de8600c6fc17d7fa8d89079d4ae655ec",
|
||||||
"packages/shared/src/types/native-finalization.ts": "c026a73003ae232fea4f7624d561493b383df358",
|
"packages/shared/src/types/native-finalization.ts": "c026a73003ae232fea4f7624d561493b383df358",
|
||||||
"packages/shared/src/types/plugin.ts": "af85e6aa845c2ef6956d0151ff11332947bf3949",
|
"packages/shared/src/types/plugin.ts": "af85e6aa845c2ef6956d0151ff11332947bf3949",
|
||||||
@@ -526,7 +526,7 @@
|
|||||||
"packages/shared/src/validators/issue-chat-bootstrap.test.ts": "e1ebb9aa94da22c825bc3ddd32ce2cfc98bfe645",
|
"packages/shared/src/validators/issue-chat-bootstrap.test.ts": "e1ebb9aa94da22c825bc3ddd32ce2cfc98bfe645",
|
||||||
"packages/shared/src/validators/issue-tree-control.ts": "7144ef86a83e008ac0626e1d62a1d6164c46f438",
|
"packages/shared/src/validators/issue-tree-control.ts": "7144ef86a83e008ac0626e1d62a1d6164c46f438",
|
||||||
"packages/shared/src/validators/issue.test.ts": "7584bcce33a933ebcb02695b439767163e5ef61a",
|
"packages/shared/src/validators/issue.test.ts": "7584bcce33a933ebcb02695b439767163e5ef61a",
|
||||||
"packages/shared/src/validators/issue.ts": "af96c56dc0a72b0f4c6d152c7ad1df75943231c2",
|
"packages/shared/src/validators/issue.ts": "6f581b6392cc1005b3dfdb2af2084773721410e8",
|
||||||
"packages/shared/src/validators/json-schema.ts": "b6cba6a3f76b49afce1c7dc1c2f086ab946c6133",
|
"packages/shared/src/validators/json-schema.ts": "b6cba6a3f76b49afce1c7dc1c2f086ab946c6133",
|
||||||
"packages/shared/src/validators/native-finalization.test.ts": "40c68bdd1d0e8a77cd70c4576fae53334fe5be0d",
|
"packages/shared/src/validators/native-finalization.test.ts": "40c68bdd1d0e8a77cd70c4576fae53334fe5be0d",
|
||||||
"packages/shared/src/validators/native-finalization.ts": "d4e674de6ac7d36385e6f6c2172fa16ffc9b1830",
|
"packages/shared/src/validators/native-finalization.ts": "d4e674de6ac7d36385e6f6c2172fa16ffc9b1830",
|
||||||
|
|||||||
@@ -94,6 +94,15 @@ describe("issue filters", () => {
|
|||||||
expect(countActiveIssueFilters({ ...defaultIssueFilterState, showAgentCreatedTasks: true }, true)).toBe(1);
|
expect(countActiveIssueFilters({ ...defaultIssueFilterState, showAgentCreatedTasks: true }, true)).toBe(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("keeps agent-created board handoffs visible by default when scope is set", () => {
|
||||||
|
const handoff = makeIssue({ id: "handoff", scope: "board", createdByAgentId: "agent" });
|
||||||
|
const agentTask = makeIssue({ id: "agent-scoped", scope: "agent", createdByAgentId: "agent" });
|
||||||
|
const channelPost = makeIssue({ id: "channel", scope: "channel", createdByUserId: "person" });
|
||||||
|
const issues = [handoff, agentTask, channelPost];
|
||||||
|
expect(applyIssueFilters(issues, defaultIssueFilterState, null, true).map((issue) => issue.id)).toEqual(["handoff"]);
|
||||||
|
expect(applyIssueFilters(issues, { ...defaultIssueFilterState, showAgentCreatedTasks: true }, null, true).map((issue) => issue.id)).toEqual(["handoff", "agent-scoped", "channel"]);
|
||||||
|
});
|
||||||
|
|
||||||
it("selects only routine executions even when automatic tasks are hidden", () => {
|
it("selects only routine executions even when automatic tasks are hidden", () => {
|
||||||
const routine = makeIssue({ id: "routine", originKind: "routine_execution", createdByUserId: "person" });
|
const routine = makeIssue({ id: "routine", originKind: "routine_execution", createdByUserId: "person" });
|
||||||
const issues = [makeIssue({ id: "manual", createdByUserId: "person" }), routine,
|
const issues = [makeIssue({ id: "manual", createdByUserId: "person" }), routine,
|
||||||
|
|||||||
@@ -377,6 +377,11 @@ export function issueCreationRequestFilters(
|
|||||||
: {};
|
: {};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function isBoardVisibleByDefault(issue: Issue): boolean {
|
||||||
|
if (issue.scope !== undefined) return issue.scope === "board";
|
||||||
|
return !isAgentCreatedIssue(issue);
|
||||||
|
}
|
||||||
|
|
||||||
export function applyIssueFilters(
|
export function applyIssueFilters(
|
||||||
issues: Issue[],
|
issues: Issue[],
|
||||||
state: IssueFilterState,
|
state: IssueFilterState,
|
||||||
@@ -403,7 +408,7 @@ export function applyIssueFilters(
|
|||||||
result = result.filter((issue) => issue.originKind === "routine_execution");
|
result = result.filter((issue) => issue.originKind === "routine_execution");
|
||||||
}
|
}
|
||||||
if (enableAgentCreatedVisibilityFilter && !state.showAgentCreatedTasks && !state.routineTasksOnly) {
|
if (enableAgentCreatedVisibilityFilter && !state.showAgentCreatedTasks && !state.routineTasksOnly) {
|
||||||
result = result.filter((issue) => !isAgentCreatedIssue(issue));
|
result = result.filter(isBoardVisibleByDefault);
|
||||||
}
|
}
|
||||||
if (state.statuses.length > 0) result = result.filter((issue) => state.statuses.includes(issue.displayStatus ?? issue.status));
|
if (state.statuses.length > 0) result = result.filter((issue) => state.statuses.includes(issue.displayStatus ?? issue.status));
|
||||||
if (state.priorities.length > 0) result = result.filter((issue) => state.priorities.includes(issue.priority));
|
if (state.priorities.length > 0) result = result.filter((issue) => state.priorities.includes(issue.priority));
|
||||||
|
|||||||
Reference in new issue
Block a user