feat(issues): add canonical structured coordination parity across API, OpenAPI, CLI, and public MCP (#23410)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work, where agents and humans coordinate tasks through the REST API,
`paperclipai` CLI, Native Runner API catalog, and Public MCP tools.
> - Structured coordination primitives (`channel`, `kvLabels`,
`resultSchemaRef`, and `schemaBlocks`) previously worked on `/headless`
endpoints, while canonical `/api/issues` routes, `GET
/api/issues/:id/heartbeat-context`, `paperclipai issue` CLI commands,
and Public MCP task tools did not accept or surface those fields
consistently, and OpenAPI exposed headless routes with summary-only
stubs.
> - Because agents wake up from `heartbeat-context`, inspect endpoint
schemas through OpenAPI and `runnerApiReference`, or mutate tasks
through canonical `POST`/`PATCH /api/issues` routes, CLI flags, and
Public MCP tools, missing fields on those surfaces forced callers onto
parallel endpoints or caused agents to miss required deliverable schemas
until after closing a task.
> - We chose to wire structured coordination directly onto the canonical
issue validators, routes, `heartbeat-context`, CLI flags, OpenAPI
schemas, `runnerApiReference` examples, and Public MCP task tools while
reusing existing channel-privacy and JSON Schema registries.
> - For Markdown ```` ```json schema=<name>@<version> ```` extraction in
issue descriptions and comments, we avoided multi-line backtracking
regular expressions and implemented a single-pass $O(N)$ CommonMark
character-index line scanner with strict input, fence-body, and block
caps so adversarial unclosed fences remain linear.
> - When an agent transitions an issue with `resultSchemaRef` to final
status `done`, `PATCH /api/issues/:id` now verifies that a valid
matching schema block exists across incoming or stored issue/comment
blocks and returns a self-documenting HTTP `422`
(`result_schema_validation_failed` with `requiredResultSchema` and
`jsonSchema`) while still allowing human board actors to close tasks
manually.

## Linked Issues or Issue Description

**What existing behavior does this improve?**
Canonical issue creation, updates, comments, list filters,
`heartbeat-context`, OpenAPI schemas, `runnerApiReference` examples,
`paperclipai issue` CLI commands, and Public MCP task tools now support
structured coordination fields (`channel`, `kvLabels`,
`resultSchemaRef`, and `schemaBlocks`) with full parity alongside
existing headless routes.

**Subsystem affected**
Server API (`packages/shared/src/validators/issue.ts`,
`server/src/routes/issues.ts`, `server/src/services/issues.ts`,
`server/src/routes/openapi.ts`,
`server/src/services/native-runtime/runner-api-reference.ts`,
`server/src/services/public-mcp/*`) and CLI
(`cli/src/commands/client/issue.ts`).

**Current behavior**
- `createIssueSchema`, `updateIssueSchema`, and `addIssueCommentSchema`
do not accept `channel`, `kvLabels`, `resultSchemaRef`, or
`schemaBlocks`.
- Canonical `GET /api/companies/:companyId/issues` does not filter by
`?channel=` or `?kvLabel=`, `GET /api/issues/:id/heartbeat-context`
omits `channelId`, `channelPath`, `kvLabels`, `resultSchemaRef`, and
`schemaBlocks`, and `PATCH /api/issues/:id` does not enforce
`resultSchemaRef` when an agent marks an issue `done`.
- `server/src/routes/openapi.ts` registers headless
channel/schema/kv-label/batch/queue/schedule/event endpoints with
summary-only stubs without `parameters` or `requestBody` schemas, and
`runnerApiReference` lacks examples for key headless coordination
routes.
- `paperclipai issue` (`create`, `update`, `comment`, `list`) and Public
MCP (`paperclip_search_tasks`, `paperclip_create_task`,
`paperclip_update_task`, `paperclip_add_comment`) do not expose channel,
key-value label, result schema, or schema block inputs/outputs.

**Proposed behavior**
- Extend `@paperclipai/shared` issue validators
(`createIssueBaseSchema`, `updateIssueSchema`, `addIssueCommentSchema`)
with validated `kvLabels`, `resultSchemaRef`, `channel`, `schemaBlocks`,
`commentKvLabels`, and `commentSchemaBlocks`.
- Add a linear $O(N)$ single-pass CommonMark schema fence scanner
(`server/src/services/schema-fence-scanner.ts`) with zero regexes and
strict input/fence caps (`512 KiB` text, `64 KiB` fence body, `64`
candidate fences, `32` blocks).
- Support `channel`, `kvLabels`, `resultSchemaRef`, and explicit/fenced
`schemaBlocks` on `POST /api/companies/:companyId/issues`, `POST
/api/issues/:id/children`, `PATCH /api/issues/:id`, `POST
/api/issues/:id/comments`, `GET /api/companies/:companyId/issues`
(`?channel=` and `?kvLabel=`), and `GET
/api/issues/:id/heartbeat-context`, enforcing private-channel access
rules and HTTP `422` `result_schema_validation_failed` (with
`requiredResultSchema` and `jsonSchema`) when an agent transitions an
issue with `resultSchemaRef` to final status `done`.
- Replace summary-only headless OpenAPI stubs with full `query` and
`requestBody` schemas, document `channel` and `kvLabel` query parameters
on `GET /api/companies/{companyId}/issues`, and add `runnerApiReference`
examples for `PATCH /api/issues/{}/kv-labels`, `POST
/api/companies/{}/channels/posts`, `POST /api/companies/{}/schemas`, and
`POST /api/companies/{}/issues/batch`.
- Add `--kv`, `--unset-kv`, `--result-schema`, `--channel`, and
`--schema-block` flags to `paperclipai issue` (`create`, `update`,
`comment`, `list`), and expose structured fields and inputs on Public
MCP task tools and projections.

**Reason and benefit**
Agents and humans can use one canonical set of issue endpoints, CLI
flags, Native Runner API discovery schemas, and Public MCP tools to
route work into channels, filter and patch structured `kvLabels`, attach
validated `schemaBlocks`, and enforce `resultSchemaRef` deliverables at
completion time with immediate JSON Schema feedback.

**Breaking changes**
No — purely additive on canonical issue schemas, CLI flags, OpenAPI
definitions, and Public MCP tools. Existing callers without
`resultSchemaRef` or structured fields behave identically, and human
board actors (`req.actor.type === "board"`) can still close tasks with
`resultSchemaRef` without attaching a schema block.

## What Changed

- **Shared Issue Validators
(`packages/shared/src/validators/issue.ts`)**: Added
`issueKvLabelsSchema`, `issueKvLabelsPatchSchema` (`null` unsets keys),
`issueResultSchemaRefSchema`, `issueChannelInputSchema`, and
`issueSchemaBlocksSchema`; extended `createIssueBaseSchema`,
`updateIssueSchema`, and `addIssueCommentSchema`; refreshed
`tests/runner-e2e/source-sdk-public-inputs.json`.
- **Linear Schema Fence Scanner & Structured Helpers
(`server/src/services/schema-fence-scanner.ts`,
`server/src/services/issue-structured-fields.ts`,
`server/src/services/issue-visibility.ts`)**: Implemented a
character-index single-pass CommonMark fence scanner with no
backtracking regexes, plus channel resolution/privacy helpers,
`kvLabels` merge/filter helpers, schema block validation, and agent
`done` deliverable enforcement.
- **Canonical Issue Routes & Service (`server/src/routes/issues.ts`,
`server/src/services/issues.ts`,
`server/src/routes/headless-channels-schemas.ts`)**: Wired `channel`,
`kvLabels`, `resultSchemaRef`, and `schemaBlocks` across create, child
create, update, comment, list (`?channel=`, `?kvLabel=`), and
`heartbeat-context` (`channelId`, privacy-checked `channelPath`,
`kvLabels`, `resultSchemaRef`, `schemaBlocks`), plus HTTP `422`
`result_schema_validation_failed` enforcement when an agent marks an
issue `done` without a valid deliverable block.
- **OpenAPI, Docs & Runner API Reference
(`server/src/routes/openapi.ts`,
`server/src/services/native-runtime/runner-api-reference.ts`,
`docs/api/issues.md`)**: Replaced summary-only headless OpenAPI entries
with full `query` and `requestBody` schemas reusing shared channel/batch
schemas across all 27 headless endpoints, documented `channel` and
`kvLabel` on `GET /api/companies/{companyId}/issues`, documented all new
canonical issue fields and `422 result_schema_validation_failed`
behavior in `docs/api/issues.md`, and added `runnerApiReference`
examples for `PATCH /api/issues/{}/kv-labels`, `POST
/api/companies/{}/channels/posts`, `POST /api/companies/{}/schemas`, and
`POST /api/companies/{}/issues/batch`.
- **CLI & Public MCP (`cli/src/commands/client/issue.ts`,
`server/src/services/public-mcp/{contracts,capabilities,expanded-capabilities}.ts`)**:
Added `--kv`, `--unset-kv`, `--result-schema`, `--channel`, and
`--schema-block` flags to `paperclipai issue` (`create`, `update`,
`comment`, `list`) and added structured fields and parameters to Public
MCP task contracts and tools (`paperclip_search_tasks`,
`paperclip_create_task`, `paperclip_update_task`,
`paperclip_add_comment`).

## Verification

- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/shared typecheck` — passed.
- `pnpm exec vitest run packages/shared/src/validators/issue.test.ts` —
65/65 passed (including Zod `z.toJSONSchema` compatibility).
- `pnpm exec vitest run
server/src/__tests__/schema-fence-scanner.test.ts` — 4/4 passed (`5,000`
repeated unterminated ```` ```json ```` lines scanned in `< 50ms`).
- `pnpm exec vitest run
server/src/__tests__/canonical-issue-structured-parity.test.ts
server/src/__tests__/headless-channels-schemas-batch.test.ts
server/src/__tests__/headless-e2e-sdk-cli.test.ts` — 14/14 passed.
(During initial test execution, an invalid `resultSchemaRef` fence on
`PATCH /api/issues/:id { status: "done", comment }` hit generic
`schema_validation_failed` before
`assertAgentResultSchemaSatisfiedOnDone`; reordered
`assertAgentResultSchemaSatisfiedOnDone` ahead of `validateSchemaBlocks`
so agents consistently receive `result_schema_validation_failed` with
`requiredResultSchema` and `jsonSchema`, then re-ran green.)
- `pnpm exec vitest run server/src/__tests__/openapi-routes.test.ts
server/src/services/native-runtime/runner-api.test.ts
server/src/services/native-runtime/runner-api-reference.test.ts` —
2,444/2,444 passed.
- `pnpm exec vitest run cli/src/__tests__/issue-subresources.test.ts` —
7/7 passed.
- `pnpm exec vitest run server/src/__tests__/public-mcp.test.ts` — 84/84
passed.
- `(cd server && node scripts/typecheck-layers.mjs)` and `pnpm --filter
paperclipai typecheck` — passed all typecheck layers.
- `node scripts/check-module-boundaries.mjs`, `node
scripts/check-agent-lifecycle-boundaries.mjs`, `node
scripts/check-test-budget.mjs`, and `node
tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse HEAD)
--check` — passed.
- `pnpm verify` — exited `2` (`Broad input:
tests/runner-e2e/source-sdk-public-inputs.json`) after refreshing
`source-sdk-public-inputs.json`; focused Vitest suites and layered
typechecks passed locally and broad coverage runs in required PR CI.
- **Round 1 PR CI & review follow-up**: Initial PR CI caught a circular
module initialization (`openapi.ts` importing
`ResolveInteractionInputSchema` from
`services/headless-events-schedules-interactions.ts`, leaving
`runnerApiCallSchema` undefined in `native-workflow-tools.ts`), and code
review flagged private-channel issue/child `visibility` inheritance,
locked-row `resultSchemaRef` enforcement + agent immutability, follow-up
edits on already-`done` tasks, SDK non-UUID retry-key routing on `POST
/issues/:id/comments`, strict `> 512 KiB` fence rejection,
`schemaBlocks` on `paperclip_create_task`/`paperclip_update_task`,
`timeout` query param on `/events/wait`, and `docs/api/issues.md`
updates. Removed the `services/*` import from `openapi.ts`, fixed each
review finding, and verified `tool-input-variant-admission.test.ts`,
`teams-catalog-service.test.ts`,
`canonical-issue-structured-parity.test.ts`, `public-mcp.test.ts`,
`headless-channels-schemas-batch.test.ts`,
`headless-e2e-sdk-cli.test.ts`, `headless-identity-auth.test.ts`, and
`schema-fence-scanner.test.ts` (2,663/2,663 tests passing across 13
suites).

## Risks

- **Private channel existence or path leakage**: Mitigated by checking
`canAccessChannel` on canonical channel writes, list filters
(`?channel=`), and `GET /api/issues/:id/heartbeat-context` (failing
closed with `404` on inaccessible private channel targets and returning
`channelPath: null` when a private channel is not accessible to the
caller).
- **Adversarial Markdown payloads on issue/comment writes**: Mitigated
by scanning fences with a pure character-index single-pass CommonMark
line scanner with zero regular expressions, bounded at `512 KiB` input
text, `64 KiB` per fence body, `64` candidate fences, and `32` schema
blocks.
- **`resultSchemaRef` completion blocking**: Mitigated by enforcing
`422` `result_schema_validation_failed` only when `req.actor.type ===
"agent"` and the effective target status after execution-policy routing
is `"done"`, preserving manual task closure for board humans and
intermediate `in_review` transitions.

## Model Used

Google DeepMind `gemini-3.1-pro` via Antigravity agentic coding harness
(1M context window, high reasoning effort, native workspace/file/test
tool execution).

## Checklist

- [x] I searched the [GitHub PR
list](https://github.com/paperclipai/paperclip/pulls?q=is%3Apr) (open +
recently closed) for similar PRs and confirmed this is not a duplicate
- [x] My code follows the project's [code
comments](CONTRIBUTING.md#code-comments) guidelines (self-documenting,
minimal comments)
- [x] `pnpm -r typecheck` passes (verified locally across
`@paperclipai/shared`, `server` layered typecheck, and `paperclipai`
CLI; full workspace `typecheck_release_registry` verified in PR CI)
- [x] `pnpm test:run` passes (focused owner Vitest suites passed
locally; full CI matrix verified in PR CI)
- [ ] `pnpm build` passes
- [ ] If I changed `packages/db`, I ran `pnpm db:generate` and committed
the migration
- [x] If I added a user-facing capability, I updated `README.md` or
relevant docs (`docs/api/issues.md`)
- [x] This PR focuses on a single concern (no unrelated changes bundled)

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-12-01 21:53:58 +00:00
1 parent 3833e1c8e8
commit 16614f4fda
26 files changed
+3434 -130

No files matched your search

@@ -0,0 +1,764 @@
import { createHash, randomUUID } from "node:crypto";
import express from "express";
import request from "supertest";
import { eq } from "drizzle-orm";
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import {
activityLog,
agentApiKeys,
agents,
authUsers,
boardEvents,
channelAccessMembers,
channels,
companies,
companyMemberships,
companySchemas,
createDb,
heartbeatRuns,
issueComments,
issueCreateIdempotencyKeys,
issueLabels,
issueRelations,
issues,
type Db,
} from "@paperclipai/db";
import { actorMiddleware } from "../middleware/auth.js";
import { errorHandler } from "../middleware/error-handler.js";
import { headlessChannelsSchemasRoutes } from "../routes/headless-channels-schemas.js";
import { headlessIdentityRoutes } from "../routes/headless-identity.js";
import { issueRoutes } from "../routes/issues.js";
import { createLocalDiskStorageProvider } from "../storage/local-disk-provider.js";
import { createStorageService } from "../storage/service.js";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported
? describe
: describe.skip;
describeEmbeddedPostgres(
"canonical issue routes structured coordination parity",
() => {
let db!: Db;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null =
null;
let companyId!: string;
const ownerUserId = "user-parity-owner";
const peerUserId = "user-parity-peer";
let workerAgentId!: string;
let reviewerAgentId!: string;
let workerToken!: string;
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase(
"paperclip-canonical-structured-parity-",
);
db = createDb(tempDb.connectionString);
}, 60_000);
afterAll(async () => {
await tempDb?.cleanup();
});
function buildApp() {
const app = express();
app.use(express.json());
app.use(
actorMiddleware(db, {
deploymentMode: "authenticated",
resolveSession: async (req) => {
const uid = req.header("x-test-user-id");
if (!uid) return null;
return {
session: { id: `sess-${uid}`, userId: uid },
user: { id: uid, name: uid, email: `${uid}@example.test` },
};
},
}),
);
const storage = createStorageService(
createLocalDiskStorageProvider("/tmp/paperclip-parity-unused-storage"),
);
app.use(
"/api",
headlessIdentityRoutes(db, { deploymentMode: "authenticated" }),
);
app.use(
"/api",
headlessChannelsSchemasRoutes(db, { deploymentMode: "authenticated" }),
);
app.use("/api", issueRoutes(db, storage));
app.use(errorHandler);
return app;
}
beforeEach(async () => {
await db.delete(activityLog);
await db.delete(boardEvents);
await db.delete(issueComments);
await db.delete(issueRelations);
await db.delete(issueLabels);
await db.delete(issueCreateIdempotencyKeys);
await db.delete(heartbeatRuns);
await db.delete(issues);
await db.delete(channelAccessMembers);
await db.delete(channels);
await db.delete(companySchemas);
await db.delete(agentApiKeys);
await db.delete(agents);
await db.delete(companyMemberships);
await db.delete(companies);
await db.delete(authUsers);
await db.insert(authUsers).values([
{
id: ownerUserId,
name: "Owner User",
email: "owner@example.test",
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: peerUserId,
name: "Peer User",
email: "peer@example.test",
createdAt: new Date(),
updatedAt: new Date(),
},
]);
const [company] = await db
.insert(companies)
.values({
name: "Structured Parity Co",
issuePrefix: "PAR",
defaultResponsibleUserId: ownerUserId,
})
.returning();
companyId = company!.id;
await db.insert(companyMemberships).values([
{
companyId,
principalType: "user",
principalId: ownerUserId,
membershipRole: "owner",
status: "active",
},
{
companyId,
principalType: "user",
principalId: peerUserId,
membershipRole: "member",
status: "active",
},
]);
const [workerAgent, reviewerAgent] = await db
.insert(agents)
.values([
{
companyId,
name: "worker-bot",
role: "engineer",
adapterType: "process",
status: "idle",
},
{
companyId,
name: "reviewer-bot",
role: "qa",
adapterType: "process",
status: "idle",
},
])
.returning();
workerAgentId = workerAgent!.id;
reviewerAgentId = reviewerAgent!.id;
workerToken = `pcp_test_${randomUUID()}`;
await db.insert(agentApiKeys).values({
agentId: workerAgentId,
companyId,
name: "worker-test-key",
keyHash: createHash("sha256").update(workerToken, "utf8").digest("hex"),
responsibleUserId: ownerUserId,
});
});
async function bindRunningAgentRun(issueId: string, agentId: string) {
const [run] = await db
.insert(heartbeatRuns)
.values({
id: randomUUID(),
companyId,
agentId,
invocationSource: "assignment",
status: "running",
responsibleUserId: ownerUserId,
startedAt: new Date(),
contextSnapshot: { issueId, taskId: issueId },
})
.returning();
await db
.update(issues)
.set({
status: "in_progress",
checkoutRunId: run!.id,
executionRunId: run!.id,
executionLockedAt: new Date(),
})
.where(eq(issues.id, issueId));
return run!;
}
it("creates, updates, comments, lists, and exposes heartbeat-context with channels, kvLabels, schemaBlocks, and private channel isolation", async () => {
const app = buildApp();
// Owner creates a private channel; peerUserId must fail closed with 404 on canonical issue create
const privCh = await request(app)
.post(`/api/companies/${companyId}/channels`)
.set("x-test-user-id", ownerUserId)
.send({ path: "sec/incident", visibility: "private" })
.expect(201);
await request(app)
.post(`/api/companies/${companyId}/issues`)
.set("x-test-user-id", peerUserId)
.send({
title: "Unauthorized private channel task",
channel: "sec/incident",
})
.expect(404);
await request(app)
.post(`/api/companies/${companyId}/issues`)
.set("x-test-user-id", peerUserId)
.send({
title: "Unauthorized private channel UUID task",
channel: privCh.body.id,
})
.expect(404);
// Owner creates canonical issue in #build/auth with kvLabels, resultSchemaRef, explicit + fenced schemaBlocks
const descriptionWithFence = [
"Investigate auth cookie handling.",
"",
"```json schema=finding@1",
'{"severity":"high","title":"Missing HttpOnly flag"}',
"```",
].join("\n");
const createdRes = await request(app)
.post(`/api/companies/${companyId}/issues`)
.set("x-test-user-id", ownerUserId)
.send({
title: "Harden auth cookies",
description: descriptionWithFence,
channel: "#build/auth",
resultSchemaRef: "test-report@1",
kvLabels: { stage: "triage", env: "staging" },
schemaBlocks: [
// Duplicate of fenced block with reversed key order -> deduplicated to 1 finding@1 block
{
schema: "finding",
version: 1,
data: { title: "Missing HttpOnly flag", severity: "high" },
},
],
})
.expect(201);
expect(createdRes.body.scope).toBe("channel");
expect(createdRes.body.channelId).toBeTruthy();
expect(createdRes.body.channelPath).toBe("build/auth");
expect(createdRes.body.resultSchemaRef).toBe("test-report@1");
expect(createdRes.body.kvLabels).toEqual({
stage: "triage",
env: "staging",
});
expect(createdRes.body.schemaBlocks).toEqual([
{
schema: "finding",
version: 1,
data: { title: "Missing HttpOnly flag", severity: "high" },
},
]);
const issueId = createdRes.body.id as string;
// Heartbeat context returns channelId, channelPath, kvLabels, resultSchemaRef, schemaBlocks
const hbRes = await request(app)
.get(`/api/issues/${issueId}/heartbeat-context`)
.set("x-test-user-id", ownerUserId)
.expect(200);
expect(hbRes.body.issue).toMatchObject({
id: issueId,
channelId: createdRes.body.channelId,
channelPath: "build/auth",
kvLabels: { stage: "triage", env: "staging" },
resultSchemaRef: "test-report@1",
schemaBlocks: [
{
schema: "finding",
version: 1,
data: { title: "Missing HttpOnly flag", severity: "high" },
},
],
});
// Scoped caller without build/* channel scope gets channelPath: null on heartbeat-context
const scopedHbRes = await request(app)
.get(`/api/issues/${issueId}/heartbeat-context`)
.set("x-test-user-id", peerUserId)
.set(
"x-paperclip-actor-scopes",
JSON.stringify({ channels: ["ops/*"] }),
)
.expect(200);
expect(scopedHbRes.body.issue.channelPath).toBeNull();
// Owner also creates an issue in private channel sec/incident
const privIssueRes = await request(app)
.post(`/api/companies/${companyId}/issues`)
.set("x-test-user-id", ownerUserId)
.send({
title: "Confidential incident task",
channel: "sec/incident",
kvLabels: { stage: "triage" },
})
.expect(201);
// Peer gets 404 on heartbeat-context of private-channel issue
await request(app)
.get(`/api/issues/${privIssueRes.body.id}/heartbeat-context`)
.set("x-test-user-id", peerUserId)
.expect(404);
// Canonical GET /api/companies/:companyId/issues supports ?channel=build/* & ?kvLabel= and hides private channels
const subtreeListRes = await request(app)
.get(`/api/companies/${companyId}/issues`)
.set("x-test-user-id", peerUserId)
.query({ channel: "build/*", kvLabel: "stage=triage" })
.expect(200);
expect(Array.isArray(subtreeListRes.body)).toBe(true);
expect(subtreeListRes.body.map((r: { id: string }) => r.id)).toEqual([
issueId,
]);
const peerPrivateChannelList = await request(app)
.get(`/api/companies/${companyId}/issues`)
.set("x-test-user-id", peerUserId)
.query({ channel: "sec/*" })
.expect(200);
expect(peerPrivateChannelList.body).toEqual([]);
const peerKvList = await request(app)
.get(`/api/companies/${companyId}/issues`)
.set("x-test-user-id", peerUserId)
.query({ kvLabel: "stage=triage" })
.expect(200);
expect(peerKvList.body.map((r: { id: string }) => r.id)).toEqual([
issueId,
]);
// Canonical POST /api/issues/:id/comments extracts schema fences + explicit schemaBlocks + kvLabels
const commentRes = await request(app)
.post(`/api/issues/${issueId}/comments`)
.set("x-test-user-id", ownerUserId)
.send({
body: "Added second finding:\n\n```json schema=finding@1\n{\"severity\":\"medium\",\"title\":\"Missing Secure attribute\"}\n```",
kvLabels: { phase: "audit" },
schemaBlocks: [
{
schema: "git-commit",
version: 1,
data: { sha: "abcdef1234567" },
},
],
})
.expect(201);
expect(commentRes.body.kvLabels).toEqual({ phase: "audit" });
expect(commentRes.body.schemaBlocks).toEqual([
{
schema: "git-commit",
version: 1,
data: { sha: "abcdef1234567" },
},
{
schema: "finding",
version: 1,
data: { severity: "medium", title: "Missing Secure attribute" },
},
]);
// Canonical PATCH /api/issues/:id merges kvLabels (set + null unset) and clears channel -> resets scope to board
const clearedChannelPatch = await request(app)
.patch(`/api/issues/${issueId}`)
.set("x-test-user-id", ownerUserId)
.send({
kvLabels: { stage: "review", env: null },
channel: null,
})
.expect(200);
expect(clearedChannelPatch.body.channelId).toBeNull();
expect(clearedChannelPatch.body.channelPath).toBeNull();
expect(clearedChannelPatch.body.scope).toBe("board");
expect(clearedChannelPatch.body.kvLabels).toEqual({ stage: "review" });
});
it("enforces resultSchemaRef with 422 result_schema_validation_failed when an agent transitions to done, while allowing in_review stage yields and board overrides", async () => {
const app = buildApp();
// Register a custom schema to prove custom + built-in schema resolution
await request(app)
.post(`/api/companies/${companyId}/schemas`)
.set("x-test-user-id", ownerUserId)
.send({
ref: "audit-verdict@1",
jsonSchema: {
type: "object",
required: ["approved", "checksRun"],
additionalProperties: false,
properties: {
approved: { type: "boolean" },
checksRun: { type: "integer", minimum: 1 },
},
},
})
.expect(201);
// 1. Task with review stage: agent marking done transitions to in_review (NOT done) -> allowed without result block
const stagedRes = await request(app)
.post(`/api/companies/${companyId}/issues`)
.set("x-test-user-id", ownerUserId)
.send({
title: "Staged review task",
assigneeAgentId: workerAgentId,
status: "todo",
resultSchemaRef: "audit-verdict@1",
executionPolicy: {
stages: [
{
type: "review",
participants: [{ type: "agent", agentId: reviewerAgentId }],
},
],
},
})
.expect(201);
const stagedRun = await bindRunningAgentRun(
stagedRes.body.id,
workerAgentId,
);
const yieldToReviewRes = await request(app)
.patch(`/api/issues/${stagedRes.body.id}`)
.set("Authorization", `Bearer ${workerToken}`)
.set("x-paperclip-run-id", stagedRun.id)
.send({ status: "done", comment: "Ready for review stage." })
.expect(200);
expect(yieldToReviewRes.body.status).toBe("in_review");
// 2. Direct completion task: agent marking done without valid audit-verdict@1 block -> 422 self-documenting error
const directRes = await request(app)
.post(`/api/companies/${companyId}/issues`)
.set("x-test-user-id", ownerUserId)
.send({
title: "Direct structured deliverable task",
assigneeAgentId: workerAgentId,
status: "todo",
resultSchemaRef: "audit-verdict@1",
})
.expect(201);
const directIssueId = directRes.body.id as string;
const directRun = await bindRunningAgentRun(directIssueId, workerAgentId);
const missingBlockRes = await request(app)
.patch(`/api/issues/${directIssueId}`)
.set("Authorization", `Bearer ${workerToken}`)
.set("x-paperclip-run-id", directRun.id)
.send({ status: "done", comment: "Finished without structured block." })
.expect(422);
expect(missingBlockRes.body.code).toBe("result_schema_validation_failed");
expect(missingBlockRes.body.details).toMatchObject({
code: "result_schema_validation_failed",
requiredResultSchema: "audit-verdict@1",
jsonSchema: {
type: "object",
required: ["approved", "checksRun"],
},
});
// Invalid data against JSON Schema also fails with 422
const invalidBlockRes = await request(app)
.patch(`/api/issues/${directIssueId}`)
.set("Authorization", `Bearer ${workerToken}`)
.set("x-paperclip-run-id", directRun.id)
.send({
status: "done",
comment:
'```json schema=audit-verdict@1\n{"approved":true,"checksRun":0}\n```',
})
.expect(422);
expect(invalidBlockRes.body.code).toBe("result_schema_validation_failed");
// Agent cannot clear or swap resultSchemaRef to bypass the completion requirement
await request(app)
.patch(`/api/issues/${directIssueId}`)
.set("Authorization", `Bearer ${workerToken}`)
.set("x-paperclip-run-id", directRun.id)
.send({ status: "done", resultSchemaRef: null })
.expect(403);
await request(app)
.patch(`/api/issues/${directIssueId}`)
.set("Authorization", `Bearer ${workerToken}`)
.set("x-paperclip-run-id", directRun.id)
.send({
status: "done",
resultSchemaRef: "finding@1",
comment: '```json schema=finding@1\n{"severity":"low","title":"Swap"}\n```',
})
.expect(403);
// Valid fenced block in closure comment -> 200 done + persisted on comment
const validDoneRes = await request(app)
.patch(`/api/issues/${directIssueId}`)
.set("Authorization", `Bearer ${workerToken}`)
.set("x-paperclip-run-id", directRun.id)
.send({
status: "done",
comment:
'Completed audit.\n\n```json schema=audit-verdict@1\n{"approved":true,"checksRun":5}\n```',
})
.expect(200);
expect(validDoneRes.body.status).toBe("done");
expect(validDoneRes.body.comment.schemaBlocks).toEqual([
{
schema: "audit-verdict",
version: 1,
data: { approved: true, checksRun: 5 },
},
]);
// 3. Board human actor remains allowed to manually close a task without the result schema block,
// and follow-up agent edits (comments / kvLabels) on the already-closed task keep working
const boardCloseTask = await request(app)
.post(`/api/companies/${companyId}/issues`)
.set("x-test-user-id", ownerUserId)
.send({
title: "Manual board override task",
assigneeAgentId: workerAgentId,
resultSchemaRef: "audit-verdict@1",
})
.expect(201);
const boardClosed = await request(app)
.patch(`/api/issues/${boardCloseTask.body.id}`)
.set("x-test-user-id", ownerUserId)
.send({ status: "done" })
.expect(200);
expect(boardClosed.body.status).toBe("done");
const followUpOriginTask = await request(app)
.post(`/api/companies/${companyId}/issues`)
.set("x-test-user-id", ownerUserId)
.send({
title: "Active run task for cross-issue follow-up",
status: "backlog",
})
.expect(201);
const followUpRun = await bindRunningAgentRun(
followUpOriginTask.body.id as string,
workerAgentId,
);
const agentFollowUpOnClosed = await request(app)
.patch(`/api/issues/${boardCloseTask.body.id}`)
.set("Authorization", `Bearer ${workerToken}`)
.set("x-paperclip-run-id", followUpRun.id)
.send({
kvLabels: { postmortem: "filed" },
comment: "Recorded post-closure follow-up note.",
})
.expect(200);
expect(agentFollowUpOnClosed.body.status).toBe("done");
expect(agentFollowUpOnClosed.body.kvLabels).toEqual({ postmortem: "filed" });
expect(agentFollowUpOnClosed.body.comment.body).toBe(
"Recorded post-closure follow-up note.",
);
// 4. Private channel creation, child inheritance without explicit channel, and channel moves preserve privacy
await request(app)
.post(`/api/companies/${companyId}/channels`)
.set("x-test-user-id", ownerUserId)
.send({ path: "secret/ops", visibility: "private" })
.expect(201);
const privateParentRes = await request(app)
.post(`/api/companies/${companyId}/issues`)
.set("x-test-user-id", ownerUserId)
.send({
title: "Private channel parent task",
channel: "secret/ops",
})
.expect(201);
expect(privateParentRes.body.visibility).toBe("private");
const privateChildRes = await request(app)
.post(`/api/issues/${privateParentRes.body.id}/children`)
.set("x-test-user-id", ownerUserId)
.send({
title: "Child under private channel parent without explicit channel",
})
.expect(201);
expect(privateChildRes.body.visibility).toBe("private");
await request(app)
.get(`/api/issues/${privateChildRes.body.id}`)
.set("x-test-user-id", peerUserId)
.expect(404);
const openTaskRes = await request(app)
.post(`/api/companies/${companyId}/issues`)
.set("x-test-user-id", ownerUserId)
.send({ title: "Open task moved to private channel" })
.expect(201);
expect(openTaskRes.body.visibility).toBe("open");
const movedToPrivateRes = await request(app)
.patch(`/api/issues/${openTaskRes.body.id}`)
.set("x-test-user-id", ownerUserId)
.send({ channel: "secret/ops" })
.expect(200);
expect(movedToPrivateRes.body.visibility).toBe("private");
await request(app)
.get(`/api/issues/${openTaskRes.body.id}`)
.set("x-test-user-id", peerUserId)
.expect(404);
// 5. SDK non-UUID retry keys stay on headless comment path while canonical { body, kvLabels } goes canonical on channel tasks
const sdkReply1 = await request(app)
.post(`/api/issues/${privateParentRes.body.id}/comments`)
.set("x-test-user-id", ownerUserId)
.send({
body: "SDK reply with non-UUID retry key",
idempotencyKey: "reply-audit-1",
clientRequestId: "reply-audit-1",
})
.expect(201);
expect(sdkReply1.body.body).toBe("SDK reply with non-UUID retry key");
const sdkReplyReplay = await request(app)
.post(`/api/issues/${privateParentRes.body.id}/comments`)
.set("x-test-user-id", ownerUserId)
.send({
body: "SDK reply with non-UUID retry key",
idempotencyKey: "reply-audit-1",
clientRequestId: "reply-audit-1",
})
.expect(200);
expect(sdkReplyReplay.body.id).toBe(sdkReply1.body.id);
const canonicalChannelComment = await request(app)
.post(`/api/issues/${privateParentRes.body.id}/comments`)
.set("x-test-user-id", ownerUserId)
.send({
body: "Canonical comment with kvLabels on channel task",
kvLabels: { kind: "canonical" },
})
.expect(201);
expect(canonicalChannelComment.body.kvLabels).toEqual({ kind: "canonical" });
expect("eventCursor" in canonicalChannelComment.body).toBe(false);
// 6. Guarded agent backlog-to-todo promotion (expectedStatusVersion) succeeds, and rejected PATCHes do not create orphan channels
const preparedBacklog = await request(app)
.post(`/api/companies/${companyId}/issues`)
.set("x-test-user-id", ownerUserId)
.send({
title: "Prepared backlog task for guarded agent promotion",
assigneeAgentId: workerAgentId,
status: "backlog",
})
.expect(201);
expect(preparedBacklog.body.status).toBe("backlog");
const promotedRes = await request(app)
.patch(`/api/issues/${preparedBacklog.body.id}`)
.set("Authorization", `Bearer ${workerToken}`)
.set("x-paperclip-run-id", followUpRun.id)
.send({
status: "todo",
expectedStatusVersion: preparedBacklog.body.statusVersion,
})
.expect(200);
expect(promotedRes.body.status).toBe("todo");
const orphanGuardTask = await request(app)
.post(`/api/companies/${companyId}/issues`)
.set("x-test-user-id", ownerUserId)
.send({
title: "Task whose invalid done transition must not create a channel",
assigneeAgentId: workerAgentId,
status: "todo",
resultSchemaRef: "audit-verdict@1",
})
.expect(201);
const orphanGuardRun = await bindRunningAgentRun(
orphanGuardTask.body.id as string,
workerAgentId,
);
await request(app)
.patch(`/api/issues/${orphanGuardTask.body.id}`)
.set("Authorization", `Bearer ${workerToken}`)
.set("x-paperclip-run-id", orphanGuardRun.id)
.send({ status: "done", channel: "orphan/never-created" })
.expect(422);
const orphanChannels = await db
.select({ id: channels.id })
.from(channels)
.where(eq(channels.path, "orphan/never-created"));
expect(orphanChannels).toHaveLength(0);
// Reassigning a running task with a nonexistent channel UUID fails with 404 BEFORE cancelling the active run
await request(app)
.patch(`/api/issues/${orphanGuardTask.body.id}`)
.set("x-test-user-id", ownerUserId)
.send({
assigneeAgentId: reviewerAgentId,
channel: randomUUID(),
})
.expect(404);
const [stillRunningAfterBadChannel] = await db
.select({ status: heartbeatRuns.status })
.from(heartbeatRuns)
.where(eq(heartbeatRuns.id, orphanGuardRun.id));
expect(stillRunningAfterBadChannel?.status).toBe("running");
// Agent clearing channel: null resets scope from "channel" to "agent" (never "board")
const agentChannelTask = await request(app)
.post(`/api/companies/${companyId}/issues`)
.set("x-test-user-id", ownerUserId)
.send({
title: "Channel task cleared by agent",
assigneeAgentId: workerAgentId,
status: "todo",
channel: "build/agent-clear",
})
.expect(201);
expect(agentChannelTask.body.scope).toBe("channel");
const agentClearedChannel = await request(app)
.patch(`/api/issues/${agentChannelTask.body.id}`)
.set("Authorization", `Bearer ${workerToken}`)
.set("x-paperclip-run-id", orphanGuardRun.id)
.send({ channel: null })
.expect(200);
expect(agentClearedChannel.body.channelId).toBeNull();
expect(agentClearedChannel.body.scope).toBe("agent");
});
},
);
+125
View File
@@ -21,6 +21,7 @@ import { McpApiError, createMcpApiDispatch, createPublicMcpExecutor, publicMcpCa
import { publicMcpIngressRoutes, publicMcpManagementRoutes } from "../routes/public-mcp.js";
import { authorizationService } from "../services/authorization.js";
import { issueRoutes } from "../routes/issues.js";
import { headlessChannelsSchemasRoutes } from "../routes/headless-channels-schemas.js";
import { activityRoutes } from "../routes/activity.js";
import { accessRoutes } from "../routes/access.js";
import { documentService } from "../services/documents.js";
@@ -1058,6 +1059,130 @@ describe.skipIf(!support.supported)("public MCP OAuth and tool boundary", () =>
} finally { await f.cleanup(); }
});
it("passes structured channel, kvLabels, resultSchemaRef, and schemaBlocks through Public MCP task and comment tools", async () => {
const f = await fixture("owner", true, false);
const storageDir = await mkdtemp(join(tmpdir(), "mcp-structured-"));
try {
const storage = createStorageService(createLocalDiskStorageProvider(storageDir));
const api = express.Router();
api.use(boardMutationGuard());
api.use(headlessChannelsSchemasRoutes(db, { deploymentMode: "authenticated" }));
api.use(issueRoutes(db, storage));
api.use(activityRoutes(db));
const execute = createPublicMcpExecutor(db, oauth, createMcpApiDispatch(api));
const call = (name: string, a: Record<string, unknown> = {}): Promise<Record<string, unknown>> =>
execute(f.tokens.access_token, name, { companyId: f.company.id, ...a });
const created = await call("paperclip_create_task", {
requestId: randomUUID(),
title: "Structured MCP task",
description: "Verify channel + kvLabels + resultSchemaRef + schemaBlocks passthrough",
channel: "#build/mcp",
kvLabels: { stage: "triage", source: "mcp" },
resultSchemaRef: "finding@1",
schemaBlocks: [
{
schema: "finding",
version: 1,
data: { severity: "low", title: "Initial MCP block" },
},
],
});
const createdTask = created.task as Record<string, unknown>;
expect(createdTask).toMatchObject({
title: "Structured MCP task",
channelPath: "build/mcp",
kvLabels: { stage: "triage", source: "mcp" },
resultSchemaRef: "finding@1",
schemaBlocks: [
{
schema: "finding",
version: 1,
data: { severity: "low", title: "Initial MCP block" },
},
],
});
const taskId = String(createdTask.id);
const searched = await call("paperclip_search_tasks", {
channel: "build/*",
kvLabel: "stage=triage",
});
const searchedTasks = searched.tasks as Array<Record<string, unknown>>;
expect(searchedTasks.map((t) => t.id)).toEqual([taskId]);
expect(searchedTasks[0]?.channelPath).toBe("build/mcp");
const readWithChannel = await call("paperclip_read_task", { taskId });
expect((readWithChannel.task as Record<string, unknown>).channelPath).toBe("build/mcp");
const commented = await call("paperclip_add_comment", {
taskId,
requestId: randomUUID(),
body: "Attached structured finding",
kvLabels: { verdict: "confirmed" },
schemaBlocks: [
{
schema: "finding",
version: 1,
data: { severity: "medium", title: "Checked via MCP" },
},
],
});
expect(commented.comment).toMatchObject({
kvLabels: { verdict: "confirmed" },
schemaBlocks: [
{
schema: "finding",
version: 1,
data: { severity: "medium", title: "Checked via MCP" },
},
],
});
const updated = await call("paperclip_update_task", {
taskId,
requestId: randomUUID(),
changes: {
kvLabels: { stage: "done", source: null },
resultSchemaRef: null,
channel: null,
schemaBlocks: [
{
schema: "finding",
version: 1,
data: { severity: "high", title: "Updated MCP block" },
},
],
},
});
expect(updated.task).toMatchObject({
id: taskId,
channelId: null,
channelPath: null,
kvLabels: { stage: "done" },
resultSchemaRef: null,
schemaBlocks: [
{
schema: "finding",
version: 1,
data: { severity: "high", title: "Updated MCP block" },
},
],
});
const readBack = await call("paperclip_read_task", { taskId });
expect(readBack.task).toMatchObject({
id: taskId,
kvLabels: { stage: "done" },
});
expect((readBack.comments as Array<Record<string, unknown>>)[0]).toMatchObject({
kvLabels: { verdict: "confirmed" },
});
} finally {
await rm(storageDir, { recursive: true, force: true });
}
});
it("exposes discovery and individually named protocol tools, with CSRF-protected management", async () => {
const f = await fixture();
const dispatch = vi.fn().mockResolvedValue([{ id: randomUUID(), name: "Engineer", adapterConfig: { secret: "hidden" } }]);
@@ -0,0 +1,98 @@
import { performance } from "node:perf_hooks";
import { describe, expect, it } from "vitest";
import {
dedupeSchemaBlocks,
scanSchemaFences,
} from "../services/schema-fence-scanner.js";
describe("scanSchemaFences (linear O(N) CommonMark scanner)", () => {
it("completes 5,000 repeated unterminated ```json lines in under 50ms without quadratic rescanning", () => {
const adversarial = "```json\n".repeat(5_000);
// Warm up JIT once so timing reflects steady-state scanner complexity
scanSchemaFences("```json\n```");
const start = performance.now();
const blocks = scanSchemaFences(adversarial, { strict: true });
const elapsedMs = performance.now() - start;
expect(blocks).toEqual([]);
expect(elapsedMs).toBeLessThan(50);
});
it("extracts backtick and tilde schema fences while ignoring nested example fences", () => {
const markdown = [
"Summary before deliverable:",
"",
"```json schema=finding@1",
'{ "severity": "high", "title": "SQL injection in filter" }',
"```",
"",
"~~~~markdown",
"Example that should not be parsed:",
"```json schema=finding@1",
'{ "severity": "critical", "title": "Ignored nested block" }',
"```",
"~~~~",
"",
"~~~json schema=Test-Report@1",
'{ "passed": true, "total": 18 }',
"~~~",
].join("\n");
const blocks = scanSchemaFences(markdown, { strict: true });
expect(blocks).toEqual([
{
schema: "finding",
version: 1,
data: { severity: "high", title: "SQL injection in filter" },
},
{
schema: "test-report",
version: 1,
data: { passed: true, total: 18 },
},
]);
});
it("rejects malformed schema refs, invalid JSON, non-object JSON, and unclosed schema fences in strict mode", () => {
expect(() =>
scanSchemaFences("```json schema=bad_ref\n{}\n```", { strict: true }),
).toThrow(/Invalid schema reference/);
expect(() =>
scanSchemaFences("```json schema=finding@1\n{not-json}\n```", { strict: true }),
).toThrow(/invalid JSON/);
expect(() =>
scanSchemaFences("```json schema=finding@1\n[1, 2, 3]\n```", { strict: true }),
).toThrow(/must be a JSON object/);
expect(() =>
scanSchemaFences("```json schema=finding@1\n{\"a\":1}\n", { strict: true }),
).toThrow(/Unterminated fenced JSON block/);
// Non-strict mode skips malformed historical fences cleanly
expect(
scanSchemaFences("```json schema=finding@1\n{not-json}\n```", { strict: false }),
).toEqual([]);
});
it("deduplicates semantically identical schema blocks regardless of key order", () => {
const deduped = dedupeSchemaBlocks([
{ schema: "finding", version: 1, data: { title: "A", severity: "high" } },
{ schema: "finding", version: 1, data: { severity: "high", title: "A" } },
{ schema: "finding", version: 1, data: { severity: "low", title: "B" } },
]);
expect(deduped).toHaveLength(2);
});
it("rejects oversized markdown (> 512 KiB) in strict mode instead of silently dropping trailing fences", () => {
const oversized =
"a".repeat(512 * 1024 + 16) +
"\n```json schema=finding@1\n{\"severity\":\"high\",\"title\":\"Tail\"}\n```";
expect(() => scanSchemaFences(oversized, { strict: true })).toThrow(
/exceeds maximum schema-fence scan size/,
);
expect(scanSchemaFences(oversized, { strict: false })).toEqual([]);
});
});