mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 11:47:42 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - 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>
530 lines
18 KiB
TypeScript
530 lines
18 KiB
TypeScript
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,
|
|
]);
|
|
});
|
|
});
|