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

+69 -29
View File
@@ -306,6 +306,72 @@ export interface EnsureChannelInput {
queueConfig?: ChannelQueueConfig;
}
export async function assertChannelPathWritePreconditions(
dbOrTx: DbOrTx,
companyId: string,
actor: HeadlessActorContext,
rawPath: string,
): Promise<{
normalizedPath: string;
existingChannel: typeof channels.$inferSelect | null;
hasPrivateAncestor: boolean;
}> {
const normalized = normalizeChannelPathOrThrow(rawPath, {
allowSubtreePrefix: false,
});
enforceHeadlessScopes(actor, { channelPath: normalized.path });
let hasPrivateAncestor = false;
const parts = normalized.path.split("/");
if (parts.length > 1) {
const ancestorPaths: string[] = [];
for (let i = 1; i < parts.length; i += 1) {
ancestorPaths.push(parts.slice(0, i).join("/"));
}
const ancestors = await dbOrTx
.select()
.from(channels)
.where(
and(
eq(channels.companyId, companyId),
inArray(channels.path, ancestorPaths),
isNull(channels.archivedAt),
),
);
for (const anc of ancestors) {
if (anc.visibility === "private") {
await assertChannelAccess(dbOrTx, anc, actor);
hasPrivateAncestor = true;
}
}
}
const [existing] = await dbOrTx
.select()
.from(channels)
.where(and(eq(channels.companyId, companyId), eq(channels.path, normalized.path)))
.limit(1);
if (existing) {
if (existing.archivedAt !== null) {
throw notFound(`Channel '${normalized.path}' not found`);
}
if (existing.visibility === "private") {
await assertChannelAccess(dbOrTx, existing, actor);
}
return {
normalizedPath: normalized.path,
existingChannel: existing,
hasPrivateAncestor,
};
}
return {
normalizedPath: normalized.path,
existingChannel: null,
hasPrivateAncestor,
};
}
export async function ensureChannel(
dbOrTx: DbOrTx,
companyId: string,
@@ -313,10 +379,9 @@ export async function ensureChannel(
input: EnsureChannelInput | CreateChannelInput,
opts: { allowUpdateExisting?: boolean; publications?: ActivityPublication[] } = {},
): Promise<typeof channels.$inferSelect> {
const normalized = normalizeChannelPathOrThrow(input.path, {
allowSubtreePrefix: false,
});
enforceHeadlessScopes(actor, { channelPath: normalized.path });
const { normalizedPath, hasPrivateAncestor } =
await assertChannelPathWritePreconditions(dbOrTx, companyId, actor, input.path);
const normalized = { path: normalizedPath };
let resolvedDefaultProjectId: string | null | undefined;
if (input.defaultProjectId !== undefined) {
@@ -352,31 +417,6 @@ export async function ensureChannel(
});
}
// Always check ancestor privacy and access so private parents cannot spawn open children
let hasPrivateAncestor = false;
const parts = normalized.path.split("/");
if (parts.length > 1) {
const ancestorPaths: string[] = [];
for (let i = 1; i < parts.length; i += 1) {
ancestorPaths.push(parts.slice(0, i).join("/"));
}
const ancestors = await dbOrTx
.select()
.from(channels)
.where(
and(
eq(channels.companyId, companyId),
inArray(channels.path, ancestorPaths),
isNull(channels.archivedAt),
),
);
for (const anc of ancestors) {
if (anc.visibility === "private") {
await assertChannelAccess(dbOrTx, anc, actor);
hasPrivateAncestor = true;
}
}
}
if (hasPrivateAncestor) {
if (visibility === "open") {
throw forbidden("Cannot create or expose an open channel under a private ancestor", {
@@ -30,6 +30,7 @@ import {
parseEventCursor,
parseLabelFilterExpr,
parseSchemaRef,
ResolveInteractionInputSchema,
SchedulePostSchema,
splitMessageIntoTitleAndDescription,
type AskUserQuestionsPayload,
@@ -78,14 +79,7 @@ function isIssueReferenceTarget(target: string): boolean {
return isUuidLike(trimmed) || ISSUE_REF_RE.test(trimmed);
}
export const ResolveInteractionInputSchema = z
.object({
note: z.string().optional(),
reason: z.string().optional(),
answer: z.string().optional(),
interactionId: z.string().uuid().optional(),
})
.strict();
export { ResolveInteractionInputSchema };
export interface BoardEventFilterInput {
channel?: string;
@@ -0,0 +1,480 @@
import type { Request } from "express";
import { and, asc, eq, isNull } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { channels, issueComments } from "@paperclipai/db";
import {
isUuidLike,
MAX_ISSUE_KV_LABELS,
parseLabelFilterExpr,
parseSchemaRef,
validateAgainstJsonSchema,
type LabelFilterExpr,
type SchemaBlock,
} from "@paperclipai/shared";
import { badRequest, forbidden, HttpError, notFound, unprocessable } from "../errors.js";
import type { ActivityPublication } from "./activity-log.js";
import {
assertChannelPathWritePreconditions,
ensureChannel,
normalizeChannelPathOrThrow,
validateWritableKvLabelsOrThrow,
} from "./headless-channels.js";
import {
assertChannelAccess,
channelSubtreeCondition,
findInaccessibleChannelIds,
resolveHeadlessActor,
type DbOrTx,
} from "./headless-common.js";
import {
assertSchemaExists,
getCompanySchema,
validateSchemaBlocks,
} from "./headless-schemas.js";
import { dedupeSchemaBlocks, scanSchemaFences } from "./schema-fence-scanner.js";
const MAX_KV_LABEL_FILTER_EXPRESSIONS = 16;
export function assertAgentCannotModifyExistingResultSchemaRef(
existingResultSchemaRef: string | null | undefined,
nextResultSchemaRef: string | null | undefined,
): void {
if (
existingResultSchemaRef != null &&
nextResultSchemaRef !== undefined &&
nextResultSchemaRef !== existingResultSchemaRef
) {
throw forbidden(
"Only board users can clear or change an existing resultSchemaRef",
{ code: "result_schema_ref_immutable_for_agent" },
);
}
}
export function validateIssueKvLabelsOrThrow(
rawLabels: Record<string, unknown>,
): Record<string, string> {
const validated = validateWritableKvLabelsOrThrow(rawLabels);
if (Object.keys(validated).length > MAX_ISSUE_KV_LABELS) {
throw badRequest(`kvLabels may contain at most ${MAX_ISSUE_KV_LABELS} entries`, {
error: "validation_error",
code: "validation_error",
});
}
return validated;
}
export interface PreparedCanonicalChannelWrite {
existingChannel: typeof channels.$inferSelect | null;
materialize: (opts?: {
publications?: ActivityPublication[];
}) => Promise<typeof channels.$inferSelect>;
}
export async function prepareCanonicalChannelForWrite(
dbOrTx: DbOrTx,
req: Request,
companyId: string,
rawChannel: string,
): Promise<PreparedCanonicalChannelWrite> {
const headlessActor = await resolveHeadlessActor(dbOrTx as Db, req, companyId, {
requiredAction: "write",
});
const trimmed = rawChannel.trim();
if (isUuidLike(trimmed)) {
const channelId = trimmed.toLowerCase();
const [existing] = await dbOrTx
.select()
.from(channels)
.where(
and(
eq(channels.id, channelId),
eq(channels.companyId, companyId),
isNull(channels.archivedAt),
),
)
.limit(1);
if (!existing) {
throw notFound(`Channel '${trimmed}' not found`);
}
await assertChannelAccess(dbOrTx, existing, headlessActor);
return {
existingChannel: existing,
materialize: async () => existing,
};
}
const { normalizedPath, existingChannel } =
await assertChannelPathWritePreconditions(
dbOrTx,
companyId,
headlessActor,
trimmed,
);
if (existingChannel) {
return {
existingChannel,
materialize: async () => existingChannel,
};
}
return {
existingChannel: null,
materialize: (opts = {}) =>
ensureChannel(
dbOrTx,
companyId,
headlessActor,
{ path: normalizedPath },
{ allowUpdateExisting: false, publications: opts.publications },
),
};
}
export async function resolveCanonicalChannelForWrite(
dbOrTx: DbOrTx,
req: Request,
companyId: string,
rawChannel: string,
opts: { publications?: ActivityPublication[] } = {},
): Promise<typeof channels.$inferSelect> {
const prepared = await prepareCanonicalChannelForWrite(
dbOrTx,
req,
companyId,
rawChannel,
);
return prepared.materialize(opts);
}
export async function resolveCanonicalChannelListFilter(
db: Db,
req: Request,
companyId: string,
rawChannelQuery: unknown,
): Promise<string[]> {
if (typeof rawChannelQuery !== "string" || !rawChannelQuery.trim()) {
throw badRequest("channel must be a non-empty channel UUID or path", {
error: "invalid_channel_path",
code: "invalid_channel_path",
});
}
const headlessActor = await resolveHeadlessActor(db, req, companyId, {
requiredAction: "read",
});
const trimmed = rawChannelQuery.trim();
if (isUuidLike(trimmed)) {
const channelId = trimmed.toLowerCase();
const [ch] = await db
.select({
id: channels.id,
companyId: channels.companyId,
path: channels.path,
visibility: channels.visibility,
createdByUserId: channels.createdByUserId,
createdByAgentId: channels.createdByAgentId,
})
.from(channels)
.where(
and(
eq(channels.companyId, companyId),
eq(channels.id, channelId),
isNull(channels.archivedAt),
),
)
.limit(1);
if (!ch) return [];
const inaccessible = await findInaccessibleChannelIds(db, companyId, headlessActor, [ch]);
return inaccessible.length > 0 ? [] : [ch.id];
}
const subtreeNormalizedInput =
trimmed.endsWith("/*") && trimmed.length > 2 ? trimmed.slice(0, -1) : trimmed;
const normalized = normalizeChannelPathOrThrow(subtreeNormalizedInput, {
allowSubtreePrefix: true,
});
const matchingChannels = await db
.select({
id: channels.id,
companyId: channels.companyId,
path: channels.path,
visibility: channels.visibility,
createdByUserId: channels.createdByUserId,
createdByAgentId: channels.createdByAgentId,
})
.from(channels)
.where(
and(
eq(channels.companyId, companyId),
isNull(channels.archivedAt),
normalized.isSubtreePrefix
? channelSubtreeCondition(normalized.path)
: eq(channels.path, normalized.path),
),
);
if (matchingChannels.length === 0) return [];
const inaccessibleIds = new Set(
await findInaccessibleChannelIds(db, companyId, headlessActor, matchingChannels),
);
return matchingChannels
.filter((ch) => !inaccessibleIds.has(ch.id))
.map((ch) => ch.id);
}
export function parseCanonicalKvLabelFilters(
rawKvLabelQuery: unknown,
): LabelFilterExpr[] {
if (rawKvLabelQuery === undefined) return [];
const rawValues = Array.isArray(rawKvLabelQuery)
? rawKvLabelQuery
: [rawKvLabelQuery];
if (
rawValues.length === 0 ||
rawValues.length > MAX_KV_LABEL_FILTER_EXPRESSIONS ||
rawValues.some((entry) => typeof entry !== "string" || !entry.trim())
) {
throw badRequest(
`kvLabel must provide 1 to ${MAX_KV_LABEL_FILTER_EXPRESSIONS} non-empty filter expressions`,
{
error: "invalid_label_filter",
code: "invalid_label_filter",
},
);
}
return (rawValues as string[]).map((expr) => {
try {
return parseLabelFilterExpr(expr);
} catch (err) {
throw badRequest(
err instanceof Error ? err.message : `Invalid label filter '${expr}'`,
{
error: "invalid_label_filter",
code: "invalid_label_filter",
},
);
}
});
}
export async function resolveValidatedResultSchemaRef(
dbOrTx: DbOrTx,
companyId: string,
rawRef: string | null | undefined,
): Promise<string | null | undefined> {
if (rawRef === undefined) return undefined;
if (rawRef === null) return null;
return assertSchemaExists(dbOrTx, companyId, rawRef);
}
export async function prepareValidatedSchemaBlocks(
dbOrTx: DbOrTx,
companyId: string,
explicitBlocks: readonly SchemaBlock[] | undefined,
markdownText: string | null | undefined,
): Promise<SchemaBlock[]> {
const fencedBlocks = markdownText
? scanSchemaFences(markdownText, { strict: true })
: [];
const combined = dedupeSchemaBlocks([
...(explicitBlocks ?? []),
...fencedBlocks,
]);
if (combined.length === 0) return [];
return validateSchemaBlocks(dbOrTx, companyId, combined);
}
export async function resolveStructuredIssueCreateFields(
db: Db,
req: Request,
companyId: string,
input: {
rawChannel: string | null | undefined;
kvLabels: Record<string, unknown> | undefined;
resultSchemaRef: string | null | undefined;
schemaBlocks: readonly SchemaBlock[] | undefined;
description: string | null | undefined;
},
): Promise<{
channelPublications: ActivityPublication[];
patch: {
channelId?: string;
kvLabels?: Record<string, string>;
resultSchemaRef?: string | null;
schemaBlocks?: SchemaBlock[];
};
}> {
const validatedKvLabels =
input.kvLabels !== undefined
? validateIssueKvLabelsOrThrow(input.kvLabels)
: undefined;
const validatedResultSchemaRef = await resolveValidatedResultSchemaRef(
db,
companyId,
input.resultSchemaRef,
);
const validatedSchemaBlocks =
input.schemaBlocks !== undefined || Boolean(input.description)
? await prepareValidatedSchemaBlocks(
db,
companyId,
input.schemaBlocks,
input.description,
)
: undefined;
const channelPublications: ActivityPublication[] = [];
const resolvedChannel =
input.rawChannel != null
? await resolveCanonicalChannelForWrite(db, req, companyId, input.rawChannel, {
publications: channelPublications,
})
: null;
return {
channelPublications,
patch: {
...(resolvedChannel ? { channelId: resolvedChannel.id } : {}),
...(validatedKvLabels !== undefined ? { kvLabels: validatedKvLabels } : {}),
...(validatedResultSchemaRef !== undefined
? { resultSchemaRef: validatedResultSchemaRef }
: {}),
...(validatedSchemaBlocks !== undefined
? { schemaBlocks: validatedSchemaBlocks }
: {}),
},
};
}
export async function assertAgentResultSchemaSatisfiedOnDone(
dbOrTx: DbOrTx,
args: {
companyId: string;
issue: {
id: string;
description: string | null;
schemaBlocks?: SchemaBlock[] | null;
resultSchemaRef?: string | null;
};
nextResultSchemaRef?: string | null;
nextDescription?: string | null;
nextIssueSchemaBlocks?: SchemaBlock[];
incomingCommentBody?: string;
incomingCommentSchemaBlocks?: SchemaBlock[];
},
): Promise<void> {
const effectiveRef =
args.issue.resultSchemaRef ??
(args.nextResultSchemaRef !== undefined ? args.nextResultSchemaRef : null);
if (!effectiveRef) return;
let parsedRef: ReturnType<typeof parseSchemaRef>;
try {
parsedRef = parseSchemaRef(effectiveRef);
} catch (err) {
throw unprocessable(
err instanceof Error
? err.message
: `Invalid resultSchemaRef '${effectiveRef}'`,
{
code: "result_schema_validation_failed",
requiredResultSchema: effectiveRef,
jsonSchema: null,
},
);
}
let schemaView: Awaited<ReturnType<typeof getCompanySchema>>;
try {
schemaView = await getCompanySchema(dbOrTx, args.companyId, parsedRef.ref);
} catch (err) {
if (err instanceof HttpError && err.status === 404) {
throw unprocessable(`Result schema '${parsedRef.ref}' is not registered`, {
code: "result_schema_validation_failed",
requiredResultSchema: parsedRef.ref,
jsonSchema: null,
errors: [`Schema '${parsedRef.ref}' is not registered`],
});
}
throw err;
}
const validationErrors: string[] = [];
const hasMatchingValidBlock = (candidates: readonly SchemaBlock[]): boolean => {
for (const block of candidates) {
if (block.schema !== parsedRef.name || block.version !== parsedRef.version) {
continue;
}
const check = validateAgainstJsonSchema(schemaView.jsonSchema, block.data);
if (check.valid) return true;
validationErrors.push(...check.errors);
}
return false;
};
const immediateCandidates: SchemaBlock[] = [
...(args.nextIssueSchemaBlocks !== undefined
? args.nextIssueSchemaBlocks
: Array.isArray(args.issue.schemaBlocks)
? args.issue.schemaBlocks
: []),
...(args.nextDescription !== undefined
? scanSchemaFences(args.nextDescription, { strict: true })
: scanSchemaFences(args.issue.description, { strict: false })),
...(args.incomingCommentSchemaBlocks ?? []),
...(args.incomingCommentBody
? scanSchemaFences(args.incomingCommentBody, { strict: true })
: []),
];
if (hasMatchingValidBlock(immediateCandidates)) {
return;
}
const storedComments = await dbOrTx
.select({
body: issueComments.body,
schemaBlocks: issueComments.schemaBlocks,
})
.from(issueComments)
.where(
and(
eq(issueComments.companyId, args.companyId),
eq(issueComments.issueId, args.issue.id),
isNull(issueComments.deletedAt),
),
)
.orderBy(asc(issueComments.createdAt), asc(issueComments.id));
for (const comment of storedComments) {
const commentCandidates: SchemaBlock[] = [
...(Array.isArray(comment.schemaBlocks) ? comment.schemaBlocks : []),
...scanSchemaFences(comment.body, { strict: false }),
];
if (hasMatchingValidBlock(commentCandidates)) {
return;
}
}
const errors =
validationErrors.length > 0
? validationErrors
: [`Missing required result schema block '${parsedRef.ref}'`];
throw unprocessable(
validationErrors.length > 0
? `Result schema '${parsedRef.ref}' validation failed: ${validationErrors.join("; ")}`
: `Task requires a valid '${parsedRef.ref}' schema block before an agent can mark it done`,
{
code: "result_schema_validation_failed",
requiredResultSchema: parsedRef.ref,
jsonSchema: schemaView.jsonSchema,
errors,
},
);
}
+84 -4
View File
@@ -1,10 +1,82 @@
import { nonIdleSlackIssueCondition } from "./slack-conversation-state.js";
import { and, eq, inArray, isNull, isNotNull, ne, or, type SQL } from "drizzle-orm";
import { issues } from "@paperclipai/db";
import { ISSUE_SCOPES, type IssueScope } from "@paperclipai/shared";
import { unprocessable } from "../errors.js";
import { and, eq, inArray, isNull, isNotNull, ne, or, sql, type SQL } from "drizzle-orm";
import { issueLabels, issues, labels } from "@paperclipai/db";
import {
ISSUE_SCOPES,
isReservedKvLabelKey,
isValidKvLabelKey,
isValidKvLabelValue,
MAX_ISSUE_KV_LABELS,
type IssueScope,
type LabelFilterExpr,
} from "@paperclipai/shared";
import { badRequest, unprocessable } from "../errors.js";
import { pendingUserRequestCondition } from "./issue-participation.js";
export function issueKvLabelFilterCondition(expr: LabelFilterExpr): SQL<boolean> {
switch (expr.kind) {
case "equals":
return sql<boolean>`${issues.kvLabels}->>${expr.key} = ${expr.value}`;
case "in":
return sql<boolean>`${issues.kvLabels}->>${expr.key} IN (${sql.join(
expr.values.map((v) => sql`${v}`),
sql`, `,
)})`;
case "exists":
return sql<boolean>`(jsonb_exists(${issues.kvLabels}, ${expr.key}) OR EXISTS (
SELECT 1
FROM ${issueLabels} il
INNER JOIN ${labels} l ON l.id = il.label_id
WHERE il.issue_id = ${issues.id} AND l.name = ${expr.key}
))`;
}
}
export function mergeIssueKvLabelsOrThrow(
current: Record<string, string> | null | undefined,
patch: Record<string, string | null>,
): Record<string, string> {
const next: Record<string, string> = { ...(current ?? {}) };
for (const [key, value] of Object.entries(patch)) {
if (isReservedKvLabelKey(key)) {
throw badRequest("Label keys starting with 'paperclip.' are reserved", {
error: "reserved_label",
code: "reserved_label",
key,
});
}
if (!isValidKvLabelKey(key)) {
throw badRequest(`Invalid label key '${key}'`, {
error: "validation_error",
code: "validation_error",
key,
});
}
if (value === null) {
delete next[key];
continue;
}
if (!isValidKvLabelValue(value)) {
throw badRequest(`Invalid label value for key '${key}'`, {
error: "validation_error",
code: "validation_error",
key,
});
}
next[key] = value;
}
if (Object.keys(next).length > MAX_ISSUE_KV_LABELS) {
throw badRequest(`kvLabels may contain at most ${MAX_ISSUE_KV_LABELS} entries`, {
error: "validation_error",
code: "validation_error",
});
}
return next;
}
export function visibleIssueCondition(): SQL {
return and(isNull(issues.hiddenAt), isNull(issues.harnessKind))!;
}
@@ -73,6 +145,8 @@ export function surfaceScopeCondition(filters?: {
scope?: IssueScope | string | readonly IssueScope[];
q?: string;
issueIds?: string[];
channelIds?: string[];
kvLabelFilters?: readonly unknown[];
assigneeUserId?: string;
touchedByUserId?: string;
unreadForUserId?: string;
@@ -84,6 +158,12 @@ export function surfaceScopeCondition(filters?: {
condition: scopes.length === 1 ? eq(issues.scope, scopes[0]!) : inArray(issues.scope, scopes),
};
}
if (filters?.channelIds !== undefined || (filters?.kvLabelFilters?.length ?? 0) > 0) {
return {
scopes,
condition: and(ne(issues.scope, "chat"), isNull(issues.conversationAgentId))!,
};
}
if (!filters?.q?.trim() && !filters?.issueIds) {
const mineUserId =
filters?.assigneeUserId?.trim() ||
+121 -11
View File
@@ -113,6 +113,7 @@ import {
authUsers,
approvals,
assets,
channels,
companies,
companyMemberships,
documentRevisions,
@@ -163,7 +164,9 @@ import type {
IssueRelationIssueSummary,
IssueScope,
IssueWatchdogSummary,
LabelFilterExpr,
LowTrustBoundary,
SchemaBlock,
SuccessfulRunHandoffState,
} from "@paperclipai/shared";
import {
@@ -269,6 +272,8 @@ import {
type IssueLivenessFinding,
} from "./recovery/issue-graph-liveness.js";
import {
issueKvLabelFilterCondition,
mergeIssueKvLabelsOrThrow,
nonChatAndChannelIssueCondition,
nonChatAndPassiveChannelCondition,
parseScopeFilter,
@@ -1937,6 +1942,8 @@ export interface IssueFilters {
descendantOf?: string;
createdFromIssueId?: string;
labelId?: string;
channelIds?: string[];
kvLabelFilters?: readonly LabelFilterExpr[];
originKind?: string;
originKindPrefix?: string;
originId?: string;
@@ -8655,6 +8662,19 @@ export function issueService(db: Db) {
if (filters.parentIds.length === 0) return [];
conditions.push(inArray(issues.parentId, filters.parentIds));
}
if (filters?.channelIds !== undefined) {
if (filters.channelIds.length === 0) return [];
conditions.push(
filters.channelIds.length === 1
? eq(issues.channelId, filters.channelIds[0]!)
: inArray(issues.channelId, filters.channelIds),
);
}
if (filters?.kvLabelFilters?.length) {
for (const expr of filters.kvLabelFilters) {
conditions.push(issueKvLabelFilterCondition(expr));
}
}
const inboxArchive = filters?.inboxArchive;
const archivedCondition = inboxArchive
? sql<boolean>`NOT (${inboxVisibleForUserCondition(companyId, inboxArchive.userId)})`
@@ -8664,7 +8684,7 @@ export function issueService(db: Db) {
if (scopeCondition) conditions.push(scopeCondition);
// Explicit child navigation includes waiting chat tasks, just like
// readable-child counts. Ambient lists still omit idle conversations.
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") {
if (!filters?.q?.trim() && !filters?.issueIds && filters?.channelIds === undefined && !scopes.includes("channel") && !scopes.includes("chat") && !filters?.parentId && !filters?.parentIds && !filters?.descendantOf && !filters?.touchedByUserId && !filters?.unreadForUserId && !filters?.inboxArchivedByUserId && inboxArchive?.mode !== "archived") {
conditions.push(nonIdleSlackIssueCondition());
}
if (filters?.afterId) conditions.push(gt(issues.id, filters.afterId));
@@ -9065,12 +9085,25 @@ export function issueService(db: Db) {
}
const conditions = [eq(issues.companyId, companyId), visibleIssueCondition()];
if (filters?.channelIds !== undefined) {
if (filters.channelIds.length === 0) return 0;
conditions.push(
filters.channelIds.length === 1
? eq(issues.channelId, filters.channelIds[0]!)
: inArray(issues.channelId, filters.channelIds),
);
}
if (filters?.kvLabelFilters?.length) {
for (const expr of filters.kvLabelFilters) {
conditions.push(issueKvLabelFilterCondition(expr));
}
}
if (filters?.readCondition) conditions.push(filters.readCondition);
const creationCondition = creationVisibilityCondition(companyId, filters);
if (creationCondition) conditions.push(creationCondition);
const { scopes, condition: scopeCondition } = surfaceScopeCondition({ ...filters, companyId });
if (scopeCondition) conditions.push(scopeCondition);
if (!filters?.q?.trim() && !filters?.issueIds && !scopes.includes("channel") && !scopes.includes("chat") && !filters?.parentId && !filters?.parentIds && !filters?.touchedByUserId && !filters?.unreadForUserId && !filters?.inboxArchivedByUserId) {
if (!filters?.q?.trim() && !filters?.issueIds && filters?.channelIds === undefined && !scopes.includes("channel") && !scopes.includes("chat") && !filters?.parentId && !filters?.parentIds && !filters?.touchedByUserId && !filters?.unreadForUserId && !filters?.inboxArchivedByUserId) {
conditions.push(nonIdleSlackIssueCondition());
}
const displayStatuses = parseStatusFilter(filters?.displayStatus);
@@ -11188,8 +11221,13 @@ export function issueService(db: Db) {
const [source] = await tx.select().from(issues)
.where(and(eq(issues.id, privacyParentIssueId), eq(issues.companyId, companyId)));
if (!source) privacyParentIssueId = null;
else if (source.visibility === "private" || (source.projectId && await tx.select({ id: projects.id }).from(projects)
.where(and(eq(projects.id, source.projectId), eq(projects.visibility, "private"))).limit(1).then(rows => rows.length > 0))) {
else if (
source.visibility === "private" ||
(source.projectId && await tx.select({ id: projects.id }).from(projects)
.where(and(eq(projects.id, source.projectId), eq(projects.visibility, "private"))).limit(1).then(rows => rows.length > 0)) ||
(source.channelId && await tx.select({ id: channels.id }).from(channels)
.where(and(eq(channels.id, source.channelId), eq(channels.companyId, companyId), eq(channels.visibility, "private"))).limit(1).then(rows => rows.length > 0))
) {
visibility = "private";
privacyRootIssueId = source.privacyRootIssueId ?? source.id;
inheritedPrivateSubtree = true;
@@ -11216,7 +11254,25 @@ export function issueService(db: Db) {
}
}
if (visibility === "private" && !issueData.projectId && !inheritedPrivateSubtree) {
let inPrivateChannel = false;
if (issueData.channelId) {
const selectedChannel = await tx
.select({ visibility: channels.visibility })
.from(channels)
.where(and(eq(channels.id, issueData.channelId), eq(channels.companyId, companyId)))
.then((rows) => rows[0] ?? null);
if (!selectedChannel) throw notFound("Channel not found");
if (selectedChannel.visibility === "private") {
inPrivateChannel = true;
visibility = "private";
if (!privacyRootIssueId) {
issueData.id ??= randomUUID();
privacyRootIssueId = issueData.id;
}
}
}
if (visibility === "private" && !issueData.projectId && !inheritedPrivateSubtree && !inPrivateChannel) {
if (!responsibleUserId) {
throw unprocessable("Private tasks require a responsible user");
}
@@ -11255,7 +11311,7 @@ export function issueService(db: Db) {
const derivedScope = deriveDefaultIssueScope({
scope: issueData.scope ?? null,
conversationAgentId: issueData.conversationAgentId ?? null,
channelId: null,
channelId: issueData.channelId ?? null,
createdByAgentId: issueData.createdByAgentId ?? null,
createdByUserId: issueData.createdByUserId ?? null,
originKind: issueData.originKind ?? "manual",
@@ -11751,6 +11807,12 @@ export function issueService(db: Db) {
id: string,
data: Partial<typeof issues.$inferInsert> & {
labelIds?: string[];
kvLabelsPatch?: Record<string, string | null>;
beforeLockedUpdate?: (
tx: any,
lockedIssue: typeof issues.$inferSelect,
lockedPatch: Partial<typeof issues.$inferInsert>,
) => Promise<void>;
blockedByIssueIds?: string[];
actorAgentId?: string | null;
actorRunId?: string | null;
@@ -11856,6 +11918,8 @@ export function issueService(db: Db) {
const {
labelIds: nextLabelIds,
kvLabelsPatch,
beforeLockedUpdate,
blockedByIssueIds,
actorAgentId,
actorRunId,
@@ -11875,7 +11939,7 @@ export function issueService(db: Db) {
} = data;
if (expectedStatusVersion !== undefined && (
issueData.status !== "todo" || Object.keys(issueData).some(key => key !== "status") ||
nextLabelIds !== undefined || blockedByIssueIds !== undefined || expectedExecutionPolicy !== undefined
nextLabelIds !== undefined || kvLabelsPatch !== undefined || blockedByIssueIds !== undefined || expectedExecutionPolicy !== undefined
)) {
throw unprocessable("expectedStatusVersion requires a status-only backlog-to-todo promotion");
}
@@ -12119,7 +12183,7 @@ export function issueService(db: Db) {
}
const runUpdate = async (tx: any) => {
const changesPrivacy = issueData.visibility !== undefined || issueData.parentId !== undefined || issueData.projectId !== undefined;
const changesPrivacy = issueData.visibility !== undefined || issueData.parentId !== undefined || issueData.projectId !== undefined || issueData.channelId !== undefined;
if (changesPrivacy) await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`issue-privacy-tree:${existing.companyId}`}, 0))`);
if (issueData.parentId) await assertParentInCompany(tx, existing.companyId, issueData.parentId);
if (lockedParentPlan && issueData.parentId !== undefined) {
@@ -12184,6 +12248,15 @@ export function issueService(db: Db) {
code: "issue_execution_lock_changed",
});
}
if (kvLabelsPatch !== undefined) {
patch.kvLabels = mergeIssueKvLabelsOrThrow(
receiptExisting.kvLabels ?? {},
kvLabelsPatch,
);
}
if (beforeLockedUpdate) {
await beforeLockedUpdate(tx, receiptExisting, patch);
}
if (issueData.executionPolicy !== undefined) assertQualityReviewPolicyMutation({ previousPolicy: receiptExisting.executionPolicy, nextPolicy: issueData.executionPolicy, actorAgentId, actorUserId });
if ((patch.status ?? receiptExisting.status) === "done" &&
(receiptExisting.status !== "done" || issueData.executionPolicy !== undefined)) {
@@ -12250,17 +12323,50 @@ export function issueService(db: Db) {
patch.privacyRootIssueId = receiptExisting.privacyRootIssueId ?? receiptExisting.id;
}
}
const nextChannelId = issueData.channelId !== undefined ? issueData.channelId : receiptExisting.channelId;
const [privacyChannel] = nextChannelId ? await tx.select({ visibility: channels.visibility }).from(channels)
.where(and(eq(channels.id, nextChannelId), eq(channels.companyId, existing.companyId))) : [];
if (issueData.channelId && !privacyChannel) throw notFound("Channel not found");
if (privacyChannel?.visibility === "private") {
if (issueData.visibility === "open") {
throw unprocessable("Move this task out of its private channel before making it public");
}
patch.visibility = "private";
patch.privacyRootIssueId = receiptExisting.privacyRootIssueId ?? receiptExisting.id;
}
const privacyParentId = privacySourceParentId
?? (issueData.parentId !== undefined ? issueData.parentId : receiptExisting.privacyParentIssueId);
const [privacyParent] = privacyParentId ? await tx.select().from(issues)
.where(and(eq(issues.id, privacyParentId), eq(issues.companyId, existing.companyId))) : [];
patch.privacyParentIssueId = privacyParent?.id ?? null;
if (privacyParent && (privacyParent.visibility === "private" || (privacyParent.projectId && await tx.select({ id: projects.id }).from(projects)
.where(and(eq(projects.id, privacyParent.projectId), eq(projects.visibility, "private"))).limit(1).then((rows: Array<{ id: string }>) => rows.length > 0)))) {
if (
privacyParent &&
(privacyParent.visibility === "private" ||
(privacyParent.projectId &&
await tx
.select({ id: projects.id })
.from(projects)
.where(and(eq(projects.id, privacyParent.projectId), eq(projects.visibility, "private")))
.limit(1)
.then((rows: Array<{ id: string }>) => rows.length > 0)) ||
(privacyParent.channelId &&
await tx
.select({ id: channels.id })
.from(channels)
.where(
and(
eq(channels.id, privacyParent.channelId),
eq(channels.companyId, existing.companyId),
eq(channels.visibility, "private"),
),
)
.limit(1)
.then((rows: Array<{ id: string }>) => rows.length > 0)))
) {
if (issueData.visibility === "open") throw unprocessable("A task cannot be made public while it inherits private access");
patch.visibility = "private";
patch.privacyRootIssueId = privacyParent.privacyRootIssueId ?? privacyParent.id;
} else if (issueData.visibility === "private") {
} else if (issueData.visibility === "private" && !patch.privacyRootIssueId) {
patch.privacyRootIssueId = receiptExisting.id;
}
}
@@ -13833,6 +13939,8 @@ export function issueService(db: Db) {
presentation?: IssueCommentPresentation | null;
metadata?: IssueCommentMetadata | null;
attachmentIds?: string[];
kvLabels?: Record<string, string>;
schemaBlocks?: SchemaBlock[];
authorizationReason?: string | null;
/** Server-only final assistant response, never a tool/progress comment. */
completionReply?: boolean;
@@ -14200,6 +14308,8 @@ export function issueService(db: Db) {
clientRequestId: options?.clientRequestId ?? null,
presentation,
metadata,
...(options?.kvLabels !== undefined ? { kvLabels: options.kvLabels } : {}),
...(options?.schemaBlocks !== undefined ? { schemaBlocks: options.schemaBlocks } : {}),
sourceTrust: options?.sourceTrust ?? null,
createdAt: validCreatedAt ?? currentInsertTimestamp!,
...(currentInsertTimestamp
@@ -10,4 +10,45 @@ describe("runner API skill reference enrichment", () => {
expect(match?.skillReference?.description).toContain("rejects `?limit=` and `?offset=`");
expect(match?.skillReference?.description).toContain("page through `GET /api/companies/:companyId/issues`");
});
it("exposes full OpenAPI requestBody schemas and skillReference examples for headless structured coordination routes", () => {
const kvLabelsOp = searchRunnerApi({
query: "PATCH /api/issues/{id}/kv-labels",
limit: 5,
}).results.find((entry) => entry.operationId === "PATCH /api/issues/{id}/kv-labels");
expect(kvLabelsOp).toBeDefined();
const kvBodySchema =
kvLabelsOp?.requestBody?.content?.["application/json"]?.schema;
expect(kvBodySchema?.properties).toMatchObject({
set: expect.any(Object),
unset: expect.any(Object),
if: expect.any(Object),
});
expect(kvLabelsOp?.skillReference?.examples?.length).toBeGreaterThan(0);
for (const opId of [
"POST /api/companies/{companyId}/channels/posts",
"POST /api/companies/{companyId}/schemas",
"POST /api/companies/{companyId}/issues/batch",
]) {
const op = searchRunnerApi({ query: opId, limit: 5 }).results.find(
(entry) => entry.operationId === opId,
);
expect(op, opId).toBeDefined();
expect(
op?.requestBody?.content?.["application/json"]?.schema?.type,
opId,
).toBe("object");
expect(op?.skillReference?.examples?.length, opId).toBeGreaterThan(0);
}
const listIssuesOp = searchRunnerApi({
query: "GET /api/companies/{companyId}/issues",
limit: 5,
}).results.find(
(entry) => entry.operationId === "GET /api/companies/{companyId}/issues",
);
const paramNames = (listIssuesOp?.parameters ?? []).map((p) => p.name);
expect(paramNames).toEqual(expect.arrayContaining(["channel", "kvLabel"]));
});
});
@@ -79,7 +79,7 @@ export const runnerApiReference: Record<string, { section: string; description?:
},
"GET /api/companies/{}/issues": {
"section": "Issues (Tasks)",
"description": "List issues, sorted by priority. Filters: `?status=`, `?assigneeAgentId=`, `?assigneeUserId=`, `?projectId=`, `?labelId=`, `?q=` (full-text search across title, identifier, description, comments)"
"description": "List issues, sorted by priority. Filters: `?status=`, `?assigneeAgentId=`, `?assigneeUserId=`, `?projectId=`, `?labelId=`, `?channel=`, `?kvLabel=`, `?q=` (full-text search across title, identifier, description, comments)"
},
"GET /api/companies/{}/issues/count": {
"section": "Issues (Tasks)",
@@ -907,5 +907,82 @@ export const runnerApiReference: Record<string, { section: string; description?:
"POST /api/agents/me/secrets/{}/value": {
"section": "Secrets",
"description": "Fetch one granted secret value; request body is empty"
},
"PATCH /api/issues/{}/kv-labels": {
"section": "Issues (Tasks)",
"description": "Atomically set or unset issue `kvLabels` with optional compare-and-swap (`if`) preconditions; returns 409 `label_conflict` when preconditions do not match",
"examples": [
{
"body": {
"set": { "stage": "in_review", "reviewer": "qa-bot" },
"unset": ["retry_reason"],
"if": { "stage": "triage", "reviewer": null }
}
}
]
},
"POST /api/companies/{}/channels/posts": {
"section": "Channels & Structured Coordination",
"description": "Post a channel thread (`status: \"backlog\"`) or enqueue an actionable channel task (`status: \"todo\"`) with optional `kvLabels`, `resultSchema`, and structured `blocks`",
"examples": [
{
"body": {
"channel": "build/auth",
"status": "todo",
"title": "Verify session cookie rotation",
"description": "Run the auth cookie regression suite and attach a test-report@1 result.",
"kvLabels": { "stage": "verify", "component": "auth" },
"resultSchema": "test-report@1"
}
},
{
"body": {
"channel": "security/findings",
"text": "Audit finding on token refresh endpoint",
"schema": {
"ref": "finding@1",
"data": { "severity": "high", "title": "Missing CSRF check on refresh fallback" }
}
}
}
]
},
"POST /api/companies/{}/schemas": {
"section": "Channels & Structured Coordination",
"description": "Register an immutable versioned company JSON Schema (`<name>@<positive-integer>`) for `schemaBlocks` and `resultSchemaRef` validation",
"examples": [
{
"body": {
"ref": "deploy-receipt@1",
"description": "Structured deployment verification receipt",
"jsonSchema": {
"type": "object",
"required": ["environment", "commitSha", "healthy"],
"additionalProperties": false,
"properties": {
"environment": { "type": "string", "enum": ["staging", "production"] },
"commitSha": { "type": "string", "minLength": 7 },
"healthy": { "type": "boolean" }
}
}
}
}
]
},
"POST /api/companies/{}/issues/batch": {
"section": "Issues (Tasks)",
"description": "Create a dependency-ordered DAG batch of tasks in one atomic transaction (`needs` wires `blocks` relations automatically; `idempotencyKey` replays safely)",
"examples": [
{
"body": {
"channel": "build/auth",
"idempotencyKey": "plan-auth-rollout-v1",
"tasks": [
{ "key": "implement", "title": "Implement session rotation", "priority": "high", "labels": { "stage": "code" } },
{ "key": "verify", "title": "Run auth regression suite", "needs": ["implement"], "resultSchema": "test-report@1", "labels": { "stage": "verify" } }
]
}
}
]
}
};
+31 -6
View File
@@ -4,7 +4,11 @@ import { inject } from "light-my-request";
import { and, eq } from "drizzle-orm";
import { z } from "zod";
import { type Db, mcpMutationReceipts } from "@paperclipai/db";
import { ISSUE_STATUSES } from "@paperclipai/shared";
import {
ISSUE_STATUSES,
addIssueCommentSchema,
updateIssueSchema,
} from "@paperclipai/shared";
import { errorHandler } from "../../middleware/error-handler.js";
import { DEFAULT_JSON_BODY_LIMIT } from "../../http/body-limits.js";
import { logActivity } from "../activity-log.js";
@@ -90,12 +94,14 @@ export const publicMcpCapabilities: Capability[] = [
},
{
name: "paperclip_search_tasks", description: "Find durable tasks by title or human-readable identifier and read their current status, including work delegated in earlier conversations. Use each returned task's id as taskId in subsequent tools. Search here when the user names a task; do not guess a UUID or ask the user for one before searching.",
schema: z.object({ ...company, query: z.string().max(300).optional(), status: z.enum(ISSUE_STATUSES).optional(), assigneeAgentId: z.uuid().optional(), limit: boundedLimit, offset: z.number().int().min(0).default(0) }).strict(),
schema: z.object({ ...company, query: z.string().max(300).optional(), status: z.enum(ISSUE_STATUSES).optional(), assigneeAgentId: z.uuid().optional(), channel: z.string().max(140).optional(), kvLabel: z.string().max(256).optional(), limit: boundedLimit, offset: z.number().int().min(0).default(0) }).strict(),
run: async (p, a, api) => {
const query = new URLSearchParams({ limit: String(a.limit), offset: String(a.offset) });
if (a.query) query.set("q", String(a.query));
if (a.status) query.set("status", String(a.status));
if (a.assigneeAgentId) query.set("assigneeAgentId", String(a.assigneeAgentId));
if (a.channel) query.set("channel", String(a.channel));
if (a.kvLabel) query.set("kvLabel", String(a.kvLabel));
return { tasks: rows(await api(p, "GET", `/companies/${a.companyId}/issues?${query}`)).map((v) => pick(v, taskFields)), limit: a.limit, offset: a.offset };
},
},
@@ -118,14 +124,23 @@ export const publicMcpCapabilities: Capability[] = [
schema: z.object({ ...company, requestId, title: z.string().trim().min(1).max(200), description: z.string().max(50000),
assigneeAgentId: z.uuid().optional().describe("Agent to assign. May start an agent run that consumes budget. Omit when assigning a person or no one."),
assigneeUserId: z.string().trim().min(1).max(200).optional().describe("Person to assign, as the userId from paperclip_list_people. Does not start an agent run. Omit when assigning an agent or no one."),
projectId: z.uuid().optional() }).strict()
projectId: z.uuid().optional(),
channel: updateIssueSchema.shape.channel,
kvLabels: addIssueCommentSchema.shape.kvLabels,
resultSchemaRef: updateIssueSchema.shape.resultSchemaRef,
schemaBlocks: addIssueCommentSchema.shape.schemaBlocks }).strict()
.refine((a) => !(a.assigneeAgentId && a.assigneeUserId), { message: "Assign either assigneeAgentId or assigneeUserId, not both. Omit both to leave the task unassigned.", path: ["assigneeUserId"] }),
run: async (p, a, api, origin) => {
const result = await api(p, "POST", `/companies/${a.companyId}/issues`, {
title: a.title, description: a.description,
...(a.assigneeAgentId ? { assigneeAgentId: a.assigneeAgentId } : {}),
...(a.assigneeUserId ? { assigneeUserId: a.assigneeUserId } : {}),
...(a.projectId ? { projectId: a.projectId } : {}), status: "todo",
...(a.projectId ? { projectId: a.projectId } : {}),
...(a.channel !== undefined ? { channel: a.channel } : {}),
...(a.kvLabels !== undefined ? { kvLabels: a.kvLabels } : {}),
...(a.resultSchemaRef !== undefined ? { resultSchemaRef: a.resultSchemaRef } : {}),
...(a.schemaBlocks !== undefined ? { schemaBlocks: a.schemaBlocks } : {}),
status: "todo",
idempotencyKey: `mcp:${hashMcpSecret(p.grant.companyId + ":" + p.grant.userId)}:${a.requestId}`,
});
return { task: pick(result, taskFields), url: origin + "/" + pathId(p.company.issuePrefix) + "/issues/" + pathId(object(result).identifier ?? object(result).id),
@@ -136,8 +151,18 @@ export const publicMcpCapabilities: Capability[] = [
{
name: "paperclip_add_comment", write: true,
description: "Add feedback as the connected person. Resolve a user-provided task title or identifier with paperclip_search_tasks first and use the returned id. Comments may wake the assigned agent or queue feedback for a running task, consuming configured execution budget. Does not change identity, decide approvals, or explicitly reopen tasks. Reuse requestId on retries.",
schema: z.object({ ...task, requestId, body: z.string().trim().min(1).max(50000) }).strict(),
run: async (p, a, api) => ({ comment: pick(await api(p, "POST", `/issues/${pathId(a.taskId)}/comments`, { body: a.body, clientRequestId: a.requestId }), commentFields) }),
schema: z.object({ ...task, requestId, body: z.string().trim().min(1).max(50000), kvLabels: addIssueCommentSchema.shape.kvLabels, schemaBlocks: addIssueCommentSchema.shape.schemaBlocks }).strict(),
run: async (p, a, api) => ({
comment: pick(
await api(p, "POST", `/issues/${pathId(a.taskId)}/comments`, {
body: a.body,
clientRequestId: a.requestId,
...(a.kvLabels !== undefined ? { kvLabels: a.kvLabels } : {}),
...(a.schemaBlocks !== undefined ? { schemaBlocks: a.schemaBlocks } : {}),
}),
commentFields,
),
}),
},
{
name: "paperclip_list_deliverables", description: "Retrieve task documents, uploaded attachments and deliverable references, including completed work from earlier conversations. Download attachments with paperclip_get_download_url or through the task page; this tool does not fetch arbitrary URLs.",
+2 -2
View File
@@ -24,8 +24,8 @@ export const boundedLimit = z.number().int().min(1).max(100).default(30);
export const object = (v: unknown): Record<string, unknown> => v !== null && typeof v === "object" && !Array.isArray(v) ? v as Record<string, unknown> : {};
export const pick = (v: unknown, keys: string[]) => Object.fromEntries(keys.filter((k) => k in object(v)).map((k) => [k, object(v)[k]]));
export const rows = (v: unknown) => Array.isArray(v) ? v : [];
export const taskFields = ["id", "companyId", "identifier", "title", "description", "status", "priority", "assigneeAgentId", "assigneeUserId", "projectId", "parentId", "blockedByIssueIds", "unblockDescriptor", "executionState", "createdAt", "updatedAt", "completedAt"];
export const commentFields = ["id", "issueId", "body", "authorUserId", "authorAgentId", "createdAt"];
export const taskFields = ["id", "companyId", "identifier", "title", "description", "status", "priority", "assigneeAgentId", "assigneeUserId", "projectId", "channelId", "channelPath", "kvLabels", "resultSchemaRef", "schemaBlocks", "parentId", "blockedByIssueIds", "unblockDescriptor", "executionState", "createdAt", "updatedAt", "completedAt"];
export const commentFields = ["id", "issueId", "body", "authorUserId", "authorAgentId", "actorProfile", "kvLabels", "schemaBlocks", "createdAt"];
export const documentFields = ["id", "issueId", "key", "title", "format", "body", "latestRevisionId", "latestRevisionNumber", "updatedAt"];
export const pathId = (id: unknown) => encodeURIComponent(String(id));
export const stable = (v: unknown): string => JSON.stringify(v, (_k, value) => {
@@ -13,7 +13,7 @@ const project = { ...company, projectId: z.uuid() };
const skill = { ...company, skillId: z.uuid() };
const key = z.string().regex(/^[a-z0-9][a-z0-9_-]{0,99}$/);
const filePath = z.string().min(1).max(512).refine(v => !v.startsWith("/") && !v.includes("\\") && v.split("/").every(p => p !== ".." && p !== "." && p !== ""), "Use a relative file path without traversal");
const taskChanges = updateIssueSchema.pick({ title: true, description: true, assigneeAgentId: true, assigneeUserId: true, projectId: true, parentId: true, blockedByIssueIds: true, unblockDescriptor: true, status: true, priority: true }).extend({
const taskChanges = updateIssueSchema.pick({ title: true, description: true, assigneeAgentId: true, assigneeUserId: true, projectId: true, parentId: true, blockedByIssueIds: true, unblockDescriptor: true, status: true, priority: true, kvLabels: true, resultSchemaRef: true, channel: true, schemaBlocks: true }).extend({
title: z.string().trim().min(1).max(240).optional(), description: z.string().max(524288).nullable().optional(),
assigneeAgentId: z.uuid().nullable().optional(), blockedByIssueIds: z.array(z.uuid()).max(100).optional(),
}).strict();
+343
View File
@@ -0,0 +1,343 @@
import {
canonicalizeJsonSchema,
parseSchemaRef,
type ParsedSchemaRef,
type SchemaBlock,
} from "@paperclipai/shared";
import { unprocessable } from "../errors.js";
export const MAX_SCANNED_MARKDOWN_CHARS = 512 * 1024;
export const MAX_SCHEMA_FENCE_BODY_CHARS = 64 * 1024;
export const MAX_CANDIDATE_SCHEMA_FENCES = 64;
export const MAX_SCHEMA_BLOCKS = 32;
export interface ScanSchemaFencesOptions {
/**
* When true, malformed `schema=` refs, oversized/unclosed `schema=` fences,
* or invalid/non-object JSON inside a `schema=` fence throw 422 HttpError.
* When false, malformed historical fences are skipped without throwing.
*/
strict?: boolean;
}
function countFenceIndent(text: string, start: number, end: number): number {
let indent = 0;
while (start + indent < end && text[start + indent] === " ") {
indent += 1;
if (indent > 3) return -1;
}
if (start + indent < end && text[start + indent] === "\t") {
return -1;
}
return indent;
}
function countRepeatedChar(
text: string,
start: number,
end: number,
target: string,
): number {
let count = 0;
while (start + count < end && text[start + count] === target) {
count += 1;
}
return count;
}
function isAsciiSpacesOrTabsOnly(text: string, start: number, end: number): boolean {
for (let i = start; i < end; i += 1) {
const ch = text[i];
if (ch !== " " && ch !== "\t") return false;
}
return true;
}
function containsBacktick(text: string, start: number, end: number): boolean {
for (let i = start; i < end; i += 1) {
if (text[i] === "`") return true;
}
return false;
}
function extractSchemaRefFromInfo(
text: string,
start: number,
end: number,
): string | null {
let i = start;
let tokenIndex = 0;
let isJsonFence = false;
while (i < end) {
while (i < end && (text[i] === " " || text[i] === "\t")) {
i += 1;
}
if (i >= end) break;
const tokenStart = i;
while (i < end && text[i] !== " " && text[i] !== "\t") {
i += 1;
}
const token = text.slice(tokenStart, i);
if (tokenIndex === 0) {
if (token.toLowerCase() !== "json") {
return null;
}
isJsonFence = true;
} else if (isJsonFence && token.toLowerCase().startsWith("schema=")) {
return token.slice("schema=".length).trim().toLowerCase();
}
tokenIndex += 1;
}
return null;
}
/**
* Single-pass linear O(N) CommonMark fenced code block scanner for
* ```` ```json schema=<name>@<version> ```` blocks.
*
* Security invariant: NEVER uses multi-line lazy regexes or backreferences.
* Once any CommonMark fence opens (`openFenceChar` + `openFenceLen`), lines are
* consumed linearly until a matching closing fence or EOF, so repeated unclosed
* ```` ```json ```` lines never trigger quadratic rescanning.
*/
export function scanSchemaFences(
markdown: string | null | undefined,
options: ScanSchemaFencesOptions = {},
): SchemaBlock[] {
if (!markdown || markdown.length === 0) return [];
const strict = options.strict ?? false;
if (markdown.length > MAX_SCANNED_MARKDOWN_CHARS) {
if (strict) {
throw unprocessable(
`Markdown input exceeds maximum schema-fence scan size of ${MAX_SCANNED_MARKDOWN_CHARS} characters`,
{
code: "schema_fence_parse_error",
maxChars: MAX_SCANNED_MARKDOWN_CHARS,
},
);
}
}
const text =
markdown.length > MAX_SCANNED_MARKDOWN_CHARS
? markdown.slice(0, MAX_SCANNED_MARKDOWN_CHARS)
: markdown;
const blocks: SchemaBlock[] = [];
let openFenceChar: "`" | "~" | null = null;
let openFenceLen = 0;
let activeSchemaRef: ParsedSchemaRef | null = null;
let bodyChunks: string[] = [];
let bodyChars = 0;
let bodyOverflowed = false;
let candidateFenceCount = 0;
let pos = 0;
const len = text.length;
while (pos <= len) {
if (pos === len) break;
const newlineIdx = text.indexOf("\n", pos);
const nextPos = newlineIdx === -1 ? len + 1 : newlineIdx + 1;
let lineEnd = newlineIdx === -1 ? len : newlineIdx;
if (lineEnd > pos && text[lineEnd - 1] === "\r") {
lineEnd -= 1;
}
const lineStart = pos;
pos = nextPos;
if (openFenceChar === null) {
const indent = countFenceIndent(text, lineStart, lineEnd);
if (indent === -1) continue;
const fenceStart = lineStart + indent;
if (fenceStart >= lineEnd) continue;
const ch = text[fenceStart];
if (ch !== "`" && ch !== "~") continue;
const fenceLen = countRepeatedChar(text, fenceStart, lineEnd, ch);
if (fenceLen < 3) continue;
const infoStart = fenceStart + fenceLen;
if (ch === "`" && containsBacktick(text, infoStart, lineEnd)) {
// CommonMark: backtick fence info strings may not contain backticks.
continue;
}
openFenceChar = ch;
openFenceLen = fenceLen;
activeSchemaRef = null;
bodyChunks = [];
bodyChars = 0;
bodyOverflowed = false;
const rawSchemaRef = extractSchemaRefFromInfo(text, infoStart, lineEnd);
if (rawSchemaRef !== null) {
candidateFenceCount += 1;
if (candidateFenceCount > MAX_CANDIDATE_SCHEMA_FENCES) {
if (strict) {
throw unprocessable(
`Markdown contains more than ${MAX_CANDIDATE_SCHEMA_FENCES} schema code fences`,
{
error: "schema_validation_failed",
code: "schema_validation_failed",
},
);
}
continue;
}
try {
activeSchemaRef = parseSchemaRef(rawSchemaRef);
} catch (err) {
if (strict) {
throw unprocessable(
err instanceof Error
? err.message
: `Invalid schema reference '${rawSchemaRef}'`,
{
error: "invalid_schema_ref",
code: "invalid_schema_ref",
ref: rawSchemaRef,
},
);
}
activeSchemaRef = null;
}
}
continue;
}
// Inside an open fence: check whether this line is a matching closing fence.
const closeIndent = countFenceIndent(text, lineStart, lineEnd);
if (closeIndent !== -1) {
const closeStart = lineStart + closeIndent;
const closeLen = countRepeatedChar(text, closeStart, lineEnd, openFenceChar);
if (
closeLen >= openFenceLen &&
isAsciiSpacesOrTabsOnly(text, closeStart + closeLen, lineEnd)
) {
const closedSchemaRef = activeSchemaRef;
const closedChunks = bodyChunks;
const closedOverflowed = bodyOverflowed;
openFenceChar = null;
openFenceLen = 0;
activeSchemaRef = null;
bodyChunks = [];
bodyChars = 0;
bodyOverflowed = false;
if (closedSchemaRef !== null) {
if (closedOverflowed) {
if (strict) {
throw unprocessable(
`Fenced JSON block for schema '${closedSchemaRef.ref}' exceeds ${MAX_SCHEMA_FENCE_BODY_CHARS} characters`,
{
error: "schema_validation_failed",
code: "schema_validation_failed",
schema: closedSchemaRef.ref,
},
);
}
continue;
}
const rawJson = closedChunks.join("\n").trim();
let parsed: unknown;
try {
parsed = JSON.parse(rawJson);
} catch {
if (strict) {
throw unprocessable(
`Fenced JSON block for schema '${closedSchemaRef.ref}' contains invalid JSON`,
{
error: "schema_validation_failed",
code: "schema_validation_failed",
schema: closedSchemaRef.ref,
},
);
}
continue;
}
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
if (strict) {
throw unprocessable(
`Fenced JSON block for schema '${closedSchemaRef.ref}' must be a JSON object`,
{
error: "schema_validation_failed",
code: "schema_validation_failed",
schema: closedSchemaRef.ref,
},
);
}
continue;
}
blocks.push({
schema: closedSchemaRef.name,
version: closedSchemaRef.version,
data: parsed as Record<string, unknown>,
});
}
continue;
}
}
// Content line inside an open fence: only buffer when tracking a schema fence.
if (activeSchemaRef !== null && !bodyOverflowed) {
const lineLen = lineEnd - lineStart;
const nextChars = bodyChars + (bodyChunks.length > 0 ? 1 : 0) + lineLen;
if (nextChars > MAX_SCHEMA_FENCE_BODY_CHARS) {
bodyOverflowed = true;
bodyChunks = [];
} else {
bodyChunks.push(text.slice(lineStart, lineEnd));
bodyChars = nextChars;
}
}
}
if (openFenceChar !== null && activeSchemaRef !== null && strict) {
throw unprocessable(
`Unterminated fenced JSON block for schema '${activeSchemaRef.ref}'`,
{
error: "schema_validation_failed",
code: "schema_validation_failed",
schema: activeSchemaRef.ref,
},
);
}
return blocks;
}
export function dedupeSchemaBlocks(
blocks: readonly SchemaBlock[],
options: { maxBlocks?: number } = {},
): SchemaBlock[] {
if (blocks.length === 0) return [];
const maxBlocks = options.maxBlocks ?? MAX_SCHEMA_BLOCKS;
const seen = new Set<string>();
const deduped: SchemaBlock[] = [];
for (const block of blocks) {
const key = `${block.schema}@${block.version}:${canonicalizeJsonSchema(block.data)}`;
if (seen.has(key)) continue;
seen.add(key);
deduped.push(block);
if (deduped.length > maxBlocks) {
throw unprocessable(`At most ${maxBlocks} schemaBlocks are allowed`, {
error: "schema_validation_failed",
code: "schema_validation_failed",
});
}
}
return deduped;
}