diff --git a/cli/src/__tests__/issue-subresources.test.ts b/cli/src/__tests__/issue-subresources.test.ts index 26e70ae4c25..4218e5282cc 100644 --- a/cli/src/__tests__/issue-subresources.test.ts +++ b/cli/src/__tests__/issue-subresources.test.ts @@ -274,6 +274,133 @@ describe("issue subresource commands", () => { const file = (init.body as FormData).get("file") as File; expect(file.type).toBe("text/html"); }); + + it("supports structured --kv, --unset-kv, --result-schema, --channel, and --schema-block flags across create, update, comment, and list", async () => { + const fetchMock = vi + .fn() + .mockImplementation((url: string) => + Promise.resolve( + url.includes("/issues?") ? jsonResponse([]) : jsonResponse(), + ), + ); + vi.stubGlobal("fetch", fetchMock); + + await run([ + "issue", + "create", + "-C", + COMPANY_ID, + "--title", + "Audit auth cookies", + "--channel", + "#build/auth", + "--result-schema", + "finding@1", + "--kv", + "stage=triage", + "--kv", + "env=staging", + "--schema-block", + 'finding@1={"severity":"high","title":"Missing SameSite"}', + ]); + + await run([ + "issue", + "update", + ISSUE_ID, + "--kv", + "stage=verified", + "--unset-kv", + "stale_key", + "--result-schema", + "none", + "--channel", + "", + "--schema-block", + JSON.stringify({ + ref: "test-report@1", + data: { passed: true, total: 8 }, + }), + ]); + + await run([ + "issue", + "comment", + ISSUE_ID, + "--body", + "Attached verification report", + "--kv", + "verdict=pass", + "--schema-block", + 'test-report@1={"passed":true}', + ]); + + await run([ + "issue", + "list", + "-C", + COMPANY_ID, + "--channel", + "build/*", + "--kv", + "stage=verified", + "--json", + ]); + + expect(fetchMock).toHaveBeenCalledTimes(4); + + expect(fetchMock.mock.calls[0]?.[0]).toBe( + `http://localhost:3100/api/companies/${COMPANY_ID}/issues`, + ); + expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toMatchObject({ + title: "Audit auth cookies", + channel: "#build/auth", + resultSchemaRef: "finding@1", + kvLabels: { stage: "triage", env: "staging" }, + schemaBlocks: [ + { + schema: "finding", + version: 1, + data: { severity: "high", title: "Missing SameSite" }, + }, + ], + }); + + expect(fetchMock.mock.calls[1]?.[0]).toBe( + `http://localhost:3100/api/issues/${ISSUE_ID}`, + ); + expect(JSON.parse(String(fetchMock.mock.calls[1]?.[1]?.body))).toEqual({ + kvLabels: { stale_key: null, stage: "verified" }, + resultSchemaRef: null, + channel: null, + schemaBlocks: [ + { + schema: "test-report", + version: 1, + data: { passed: true, total: 8 }, + }, + ], + }); + + expect(fetchMock.mock.calls[2]?.[0]).toBe( + `http://localhost:3100/api/issues/${ISSUE_ID}/comments`, + ); + expect(JSON.parse(String(fetchMock.mock.calls[2]?.[1]?.body))).toEqual({ + body: "Attached verification report", + kvLabels: { verdict: "pass" }, + schemaBlocks: [ + { + schema: "test-report", + version: 1, + data: { passed: true }, + }, + ], + }); + + expect(fetchMock.mock.calls[3]?.[0]).toBe( + `http://localhost:3100/api/companies/${COMPANY_ID}/issues?channel=${encodeURIComponent("build/*")}&kvLabel=${encodeURIComponent("stage=verified")}`, + ); + }); }); function jsonResponse(body: unknown = { ok: true }, init: ResponseInit = { status: 200 }): Response { diff --git a/cli/src/commands/client/issue.ts b/cli/src/commands/client/issue.ts index e2c067a1593..0ae8f96005e 100644 --- a/cli/src/commands/client/issue.ts +++ b/cli/src/commands/client/issue.ts @@ -20,6 +20,9 @@ import { respondIssueThreadInteractionSchema, resolveIssueRecoveryActionSchema, restoreIssueDocumentRevisionSchema, + parseSchemaRef, + schemaBlockSchema, + type SchemaBlock, updateIssueSchema, updateIssueWorkProductSchema, type Issue, @@ -47,6 +50,8 @@ interface IssueBaseOptions extends BaseClientOptions { status?: string; assigneeAgentId?: string; projectId?: string; + channel?: string; + kv?: string[]; match?: string; } @@ -62,6 +67,10 @@ interface IssueCreateOptions extends BaseClientOptions { standalone?: boolean; requestDepth?: string; billingCode?: string; + kv?: string[]; + resultSchema?: string; + channel?: string; + schemaBlock?: string[]; } interface IssueUpdateOptions extends BaseClientOptions { @@ -77,11 +86,18 @@ interface IssueUpdateOptions extends BaseClientOptions { billingCode?: string; comment?: string; hiddenAt?: string; + kv?: string[]; + unsetKv?: string[]; + resultSchema?: string; + channel?: string; + schemaBlock?: string[]; } interface IssueCommentOptions extends BaseClientOptions { body: string; attachmentId?: string[]; + kv?: string[]; + schemaBlock?: string[]; reopen?: boolean; resume?: boolean; } @@ -180,6 +196,8 @@ export function registerIssueCommands(program: Command): void { .option("--status ", "Comma-separated statuses") .option("--assignee-agent-id ", "Filter by assignee agent ID") .option("--project-id ", "Filter by project ID") + .option("--channel ", "Filter by channel path, subtree ('prefix/*'), or UUID") + .option("--kv ", "Filter by key-value label ('key', 'key=value', or 'key=v1|v2')", collectStringOption) .option("--match ", "Local text match on identifier/title/description") .action(async (opts: IssueBaseOptions) => { try { @@ -188,6 +206,10 @@ export function registerIssueCommands(program: Command): void { if (opts.status) params.set("status", opts.status); if (opts.assigneeAgentId) params.set("assigneeAgentId", opts.assigneeAgentId); if (opts.projectId) params.set("projectId", opts.projectId); + if (opts.channel) params.set("channel", opts.channel); + for (const filterExpr of opts.kv ?? []) { + params.append("kvLabel", filterExpr); + } const query = params.toString(); const path = `${apiPath`/api/companies/${ctx.companyId}/issues`}${query ? `?${query}` : ""}`; @@ -293,6 +315,14 @@ export function registerIssueCommands(program: Command): void { ) .option("--request-depth ", "Request depth integer") .option("--billing-code ", "Billing code") + .option("--kv ", "Set key-value label (repeatable)", collectStringOption) + .option("--result-schema ", "Required result schema reference (e.g. finding@1)") + .option("--channel ", "Channel path (e.g. build/auth) or UUID") + .option( + "--schema-block ", + "Attach structured schema block (@= or JSON envelope, repeatable)", + collectStringOption, + ) .action(async (opts: IssueCreateOptions) => { try { if (opts.standalone && opts.parentId) { @@ -310,6 +340,10 @@ export function registerIssueCommands(program: Command): void { parentId: opts.standalone ? null : opts.parentId, requestDepth: parseOptionalInt(opts.requestDepth), billingCode: opts.billingCode, + kvLabels: parseKvPairs(opts.kv), + resultSchemaRef: opts.resultSchema, + channel: opts.channel, + schemaBlocks: parseSchemaBlockOptions(opts.schemaBlock), }); const created = await ctx.api.post(apiPath`/api/companies/${ctx.companyId}/issues`, payload); @@ -338,6 +372,15 @@ export function registerIssueCommands(program: Command): void { .option("--billing-code ", "Billing code") .option("--comment ", "Optional comment to add with update") .option("--hidden-at ", "Set hiddenAt timestamp or literal 'null'") + .option("--kv ", "Set key-value label (repeatable)", collectStringOption) + .option("--unset-kv ", "Unset key-value label key (repeatable)", collectStringOption) + .option("--result-schema ", "Set required result schema ref, or pass 'none'/'' to clear") + .option("--channel ", "Move issue to channel path/UUID, or pass 'none'/'' to clear") + .option( + "--schema-block ", + "Replace issue schema blocks (@= or JSON envelope, repeatable)", + collectStringOption, + ) .action(async (issueId: string, opts: IssueUpdateOptions) => { try { const ctx = resolveCommandContext(opts); @@ -354,6 +397,10 @@ export function registerIssueCommands(program: Command): void { billingCode: opts.billingCode, comment: opts.comment, hiddenAt: parseHiddenAt(opts.hiddenAt), + kvLabels: parseKvPatch(opts.kv, opts.unsetKv), + resultSchemaRef: parseNullableClearableOption(opts.resultSchema), + channel: parseNullableClearableOption(opts.channel), + schemaBlocks: parseSchemaBlockOptions(opts.schemaBlock), }); const updated = await ctx.api.patch(apiPath`/api/issues/${issueId}`, payload); @@ -374,6 +421,12 @@ export function registerIssueCommands(program: Command): void { "--attachment-id ", "Bind uploaded issue attachments to this comment", ) + .option("--kv ", "Set comment key-value label (repeatable)", collectStringOption) + .option( + "--schema-block ", + "Attach structured schema block (@= or JSON envelope, repeatable)", + collectStringOption, + ) .option("--reopen", "Reopen if issue is done/cancelled") .option("--resume", "Request explicit follow-up and wake the assignee when resumable") .action(async (issueId: string, opts: IssueCommentOptions) => { @@ -382,6 +435,8 @@ export function registerIssueCommands(program: Command): void { const payload = addIssueCommentSchema.parse({ body: opts.body, attachmentIds: opts.attachmentId, + kvLabels: parseKvPairs(opts.kv), + schemaBlocks: parseSchemaBlockOptions(opts.schemaBlock), reopen: opts.reopen, resume: opts.resume, }); @@ -1380,6 +1435,137 @@ function parseOptionalInt(value: string | undefined): number | undefined { return parsed; } +function collectStringOption(value: string, previous: string[] = []): string[] { + return [...previous, value]; +} + +function parseKvPairs(entries: string[] | undefined): Record | undefined { + if (!entries || entries.length === 0) return undefined; + const out: Record = {}; + for (const raw of entries) { + const eqIdx = raw.indexOf("="); + if (eqIdx <= 0) { + throw new Error(`Invalid --kv '${raw}': expected key=value`); + } + const key = raw.slice(0, eqIdx).trim(); + const value = raw.slice(eqIdx + 1); + if (!key || value.length === 0) { + throw new Error(`Invalid --kv '${raw}': key and value must be non-empty`); + } + out[key] = value; + } + return out; +} + +function parseKvPatch( + setEntries: string[] | undefined, + unsetKeys: string[] | undefined, +): Record | undefined { + if ( + (!setEntries || setEntries.length === 0) && + (!unsetKeys || unsetKeys.length === 0) + ) { + return undefined; + } + const patch: Record = {}; + for (const rawKey of unsetKeys ?? []) { + const key = rawKey.trim(); + if (!key) { + throw new Error("Invalid --unset-kv: key must be non-empty"); + } + patch[key] = null; + } + const pairs = parseKvPairs(setEntries); + if (pairs) { + for (const [key, value] of Object.entries(pairs)) { + if (Object.prototype.hasOwnProperty.call(patch, key) && patch[key] === null) { + throw new Error(`Conflicting --kv and --unset-kv for key '${key}'`); + } + patch[key] = value; + } + } + return patch; +} + +function parseNullableClearableOption( + value: string | undefined, +): string | null | undefined { + if (value === undefined) return undefined; + const trimmed = value.trim(); + if ( + trimmed === "" || + trimmed.toLowerCase() === "none" || + trimmed.toLowerCase() === "null" + ) { + return null; + } + return trimmed; +} + +function parseSchemaBlockOptions( + entries: string[] | undefined, +): SchemaBlock[] | undefined { + if (!entries || entries.length === 0) return undefined; + return entries.map(parseSingleSchemaBlockOption); +} + +function parseSingleSchemaBlockOption(raw: string): SchemaBlock { + const trimmed = raw.trim(); + if (trimmed.startsWith("{")) { + let parsed: unknown; + try { + parsed = JSON.parse(trimmed); + } catch { + throw new Error(`Invalid --schema-block JSON envelope: ${raw}`); + } + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { + throw new Error(`Invalid --schema-block '${raw}': expected JSON object`); + } + const obj = parsed as Record; + if ( + typeof obj.ref === "string" || + (typeof obj.schema === "string" && obj.schema.includes("@")) + ) { + const refStr = typeof obj.ref === "string" ? obj.ref : String(obj.schema); + const parsedRef = parseSchemaRef(refStr.trim().toLowerCase()); + return schemaBlockSchema.parse({ + schema: parsedRef.name, + version: parsedRef.version, + data: obj.data, + }); + } + return schemaBlockSchema.parse(obj); + } + + const eqIdx = trimmed.indexOf("="); + if (eqIdx <= 0) { + throw new Error( + `Invalid --schema-block '${raw}': expected @= or JSON envelope`, + ); + } + const refStr = trimmed.slice(0, eqIdx).trim().toLowerCase(); + const jsonPart = trimmed.slice(eqIdx + 1).trim(); + const parsedRef = parseSchemaRef(refStr); + let parsedData: unknown; + try { + parsedData = JSON.parse(jsonPart); + } catch { + throw new Error( + `Invalid --schema-block '${raw}': payload after '=' must be valid JSON`, + ); + } + if (!parsedData || typeof parsedData !== "object" || Array.isArray(parsedData)) { + throw new Error( + `Invalid --schema-block '${raw}': payload after '=' must be a JSON object`, + ); + } + return schemaBlockSchema.parse({ + schema: parsedRef.name, + version: parsedRef.version, + data: parsedData, + }); +} + function parseHiddenAt(value: string | undefined): string | null | undefined { if (value === undefined) return undefined; if (value.trim().toLowerCase() === "null") return null; diff --git a/docs/api/issues.md b/docs/api/issues.md index be23f2bcd13..a770ef8cb5c 100644 --- a/docs/api/issues.md +++ b/docs/api/issues.md @@ -38,6 +38,8 @@ Query parameters: | `scope` | Filter by surface scope (`board`, `channel`, `agent`, `chat`); accepts comma-separated values (`scope=board,agent`) or repeated query parameters (`scope=board&scope=agent`). Invalid values return `400` | | `assigneeAgentId` | Filter by assigned agent | | `projectId` | Filter by project | +| `channel` | Filter by channel UUID, exact channel path (`build/auth` or `#build/auth`), or subtree prefix (`build/` or `build/*`). Inaccessible private channels are excluded | +| `kvLabel` | Filter by key-value label expression (`key`, `key=value`, or `key=v1\|v2`). Repeat `kvLabel` up to 16 times to combine filters with `AND`. Invalid expressions return `400` | | `view` | `index`: collection rows without bodies or diagnostics; `rows`: rows with diagnostic summaries but no bodies; `compact`: existing board row contract | | `ids` | One to 100 comma-separated task UUIDs; requires `view=index` or `view=rows` without `attention` | | `parentIds` | One to 100 comma-separated parent UUIDs for batched child context; same projection restriction as `ids` | @@ -49,7 +51,7 @@ Query parameters: Results sorted by priority. -Default exclusions: when `scope`, `q`, and `ids` are omitted, `GET /api/companies/{companyId}/issues` and `GET /api/companies/{companyId}/issues/count` exclude `chat` and `channel` scoped issues. `GET /api/companies/{companyId}/issues/count` accepts the same `scope` query syntax and returns `400` on invalid values. +Default exclusions: when `scope`, `q`, `ids`, `channel`, and `kvLabel` are omitted, `GET /api/companies/{companyId}/issues` and `GET /api/companies/{companyId}/issues/count` exclude `chat` and `channel` scoped issues (`channel` and `kvLabel` queries include `channel` scoped issues while still excluding `chat` unless `scope=chat` is requested). `GET /api/companies/{companyId}/issues/count` accepts the same `scope` query syntax and returns `400` on invalid values. `inboxArchive` requires a signed-in board user. The filter cannot be combined with `attention`. When `inboxArchive` is present, each result includes the @@ -106,11 +108,22 @@ POST /api/companies/{companyId}/issues "assigneeAgentId": "{agentId}", "parentId": "{parentIssueId}", "projectId": "{projectId}", - "goalId": "{goalId}" + "goalId": "{goalId}", + "channel": "build/cache", + "kvLabels": { "stage": "implement" }, + "resultSchemaRef": "test-report@1", + "schemaBlocks": [] } ``` -`scope` is optional (`board` | `channel` | `agent` | `chat`). When omitted, the server derives `chat` for 1:1 conversations, `board` for manual human issues and explicit chat-to-board handoffs, and `agent` for agent-created or automated issues. Passing a non-`chat` scope on a 1:1 conversation or `scope: "chat"` on a non-conversation issue returns `422`. Agent actors cannot pass `scope: "board"` directly (`403`). +`scope` is optional (`board` | `channel` | `agent` | `chat`). When omitted, the server derives `chat` for 1:1 conversations, `channel` when `channel` is supplied, `board` for manual human issues and explicit chat-to-board handoffs, and `agent` for agent-created or automated issues. Passing a non-`chat` scope on a 1:1 conversation or `scope: "chat"` on a non-conversation issue returns `422`. Agent actors cannot pass `scope: "board"` directly (`403`). + +Structured coordination fields on `POST /api/companies/{companyId}/issues` and `POST /api/issues/{issueId}/children`: + +- `channel`: optional channel UUID or normalized path (`build/cache` or `#build/cache`). Resolves an existing channel (failing closed with `404` if a private channel is inaccessible to the caller) or creates an open channel when authorized. Creating a task in a private channel sets `visibility: "private"` on the task, and child tasks created under a private-channel parent inherit private visibility. +- `kvLabels`: optional `Record` (at most 64 keys; `paperclip.*` keys are reserved and rejected). +- `resultSchemaRef`: optional `@` schema reference (for example `test-report@1`); validated against built-in and company schemas. +- `schemaBlocks`: optional array of `{ schema, version, data }` blocks (at most 32), combined and deduplicated with any fenced ```` ```json schema=@ ```` blocks in `description` and validated against registered JSON Schemas. ## Update Issue @@ -119,13 +132,21 @@ PATCH /api/issues/{issueId} Headers: X-Paperclip-Run-Id: {runId} { "status": "done", - "comment": "Implemented caching with 90% hit rate." + "comment": "Implemented caching with 90% hit rate.\n\n```json schema=test-report@1\n{\"passed\":42,\"failed\":0}\n```" } ``` The optional `comment` field adds a comment in the same call. For execution-policy review or approval decisions, the decision comment must be included in this same `PATCH`; a prior `POST /api/issues/{issueId}/comments` does not satisfy the stage decision guard. -Updatable fields: `title`, `description`, `status`, `scope`, `priority`, `assigneeAgentId`, `projectId`, `goalId`, `parentId`, `billingCode`. Existing 1:1 conversation issues must keep `scope: "chat"` and non-conversation issues cannot be set to `scope: "chat"` (`422`). Agent actors cannot promote issues to `scope: "board"` (`403`). +Updatable fields: `title`, `description`, `status`, `scope`, `priority`, `assigneeAgentId`, `projectId`, `goalId`, `parentId`, `billingCode`, `channel`, `kvLabels`, `resultSchemaRef`, `schemaBlocks`, `commentKvLabels`, `commentSchemaBlocks`. Existing 1:1 conversation issues must keep `scope: "chat"` and non-conversation issues cannot be set to `scope: "chat"` (`422`). Agent actors cannot promote issues to `scope: "board"` (`403`). + +Structured coordination update rules: + +- `channel`: string resolves and attaches the channel (applying `visibility: "private"` when moving into a private channel); `null` clears `channelId` and resets `scope` from `channel` to `board` for board users (or `agent` for agent callers) when no explicit `scope` is supplied. +- `kvLabels`: `Record` merged onto existing `kvLabels` under the task row lock (`null` removes a key; `paperclip.*` keys are rejected; at most 64 resulting keys). +- `resultSchemaRef`: `@` sets the required completion schema; `null` clears it. Only board actors can clear or change an existing `resultSchemaRef` (`403` for agent callers). +- `schemaBlocks` / `commentSchemaBlocks` / `commentKvLabels`: explicit blocks and fenced ```` ```json schema=@ ```` blocks in `description` or `comment` are validated and saved on the issue or created comment. +- **Agent completion requirement (`422 result_schema_validation_failed`)**: when an agent (`req.actor.type === "agent"`) transitions a task into `done` (or approves its final execution-policy stage) and the task has a non-null `resultSchemaRef`, at least one valid matching schema block must exist across the incoming `PATCH` (`schemaBlocks`, `commentSchemaBlocks`, `description`, or `comment`) or existing stored issue/comment blocks. Otherwise the server returns `422` with `{ code: "result_schema_validation_failed", requiredResultSchema, jsonSchema, errors }` so the caller can attach a conforming deliverable block and retry. Human board closures and follow-up edits to tasks that are already `done` are not blocked. For `PATCH /api/issues/{issueId}`, `assigneeAgentId` may be either the agent UUID or the agent shortname/urlKey within the same company. @@ -277,9 +298,19 @@ GET /api/issues/{issueId}/comments ``` POST /api/issues/{issueId}/comments -{ "body": "Progress update in markdown..." } +{ + "body": "Progress update in markdown...", + "kvLabels": { "phase": "verify" }, + "schemaBlocks": [ + { "schema": "finding", "version": 1, "data": { "severity": "medium", "title": "Cache stampede risk" } } + ] +} ``` +Optional `kvLabels` (`Record`, max 64 keys, `paperclip.*` reserved) and `schemaBlocks` (combined and deduplicated with any fenced ```` ```json schema=@ ```` blocks in `body`, validated against registered schemas) are stored on the created comment. + +`GET /api/issues/{issueId}/heartbeat-context` also includes `channelId`, privacy-checked `channelPath` (`null` when unset or inaccessible), `kvLabels`, `resultSchemaRef`, and `schemaBlocks` on `issue`. + Agent @-mentions are context only and do not trigger heartbeats. Normal comment feedback can still wake the current assignee. Use explicit assignment or a review request to ask another agent to act. #### Start a Google Antigravity swarm diff --git a/packages/shared/src/headless/leases.ts b/packages/shared/src/headless/leases.ts index 0615826ad9b..c5370155f85 100644 --- a/packages/shared/src/headless/leases.ts +++ b/packages/shared/src/headless/leases.ts @@ -122,6 +122,17 @@ export const OneLineConfirmSchema = z export type OneLineConfirmInput = z.input; +export const ResolveInteractionInputSchema = z + .object({ + note: z.string().optional(), + reason: z.string().optional(), + answer: z.string().optional(), + interactionId: z.string().uuid().optional(), + }) + .strict(); + +export type ResolveInteractionInput = z.input; + export const SchedulePostSchema = z .object({ target: z.string().min(1), diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 776afee882c..ecc9ea3b705 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -2149,6 +2149,7 @@ export { COMPANY_SEARCH_MAX_TOKENS, type CompanySearchExtractQuery, type CompanySearchQuery, + MAX_ISSUE_KV_LABELS, createIssueSchema, issueSummariesQuerySchema, issueChatBootstrapQuerySchema, diff --git a/packages/shared/src/validators/index.ts b/packages/shared/src/validators/index.ts index e5cc6c6d323..c96d9929e41 100644 --- a/packages/shared/src/validators/index.ts +++ b/packages/shared/src/validators/index.ts @@ -424,6 +424,7 @@ export { } from "./document-annotation.js"; export { + MAX_ISSUE_KV_LABELS, createIssueSchema, issueSummariesQuerySchema, issueChatBootstrapQuerySchema, diff --git a/packages/shared/src/validators/issue.test.ts b/packages/shared/src/validators/issue.test.ts index 7584bcce33a..370c30797de 100644 --- a/packages/shared/src/validators/issue.test.ts +++ b/packages/shared/src/validators/issue.test.ts @@ -1,8 +1,14 @@ import { describe, expect, it } from "vitest"; +import { z } from "zod"; import { MAX_ISSUE_REQUEST_DEPTH } from "../index.js"; import { addIssueCommentSchema, addIssueSwarmCommentSchema, + issueChannelInputSchema, + issueKvLabelsPatchSchema, + issueKvLabelsSchema, + issueResultSchemaRefSchema, + issueSchemaBlocksSchema, paperclipQuestionSetPayloadSchema, issueCommentMetadataSchema, issueDocumentBatchQuerySchema, @@ -808,3 +814,124 @@ describe("persisted canonical question initial text", () => { expect(paperclipQuestionSetPayloadSchema.safeParse(input({ answerMode: "single_select", options: [{ id: "a", label: "A" }], initialText: "a" })).success).toBe(false); }); }); + +describe("structured parity fields on canonical issue and comment validators", () => { + it("validates kvLabels, resultSchemaRef, channel, and schemaBlocks on createIssueSchema", () => { + const parsed = createIssueSchema.parse({ + title: "Structured task", + kvLabels: { "stage.phase": "triage", severity: "high" }, + resultSchemaRef: " Finding@1 ", + channel: " #build/auth ", + schemaBlocks: [ + { schema: "finding", version: 1, data: { severity: "high", title: "Leak" } }, + ], + }); + expect(parsed.kvLabels).toEqual({ "stage.phase": "triage", severity: "high" }); + expect(parsed.resultSchemaRef).toBe("finding@1"); + expect(parsed.channel).toBe("#build/auth"); + expect(parsed.schemaBlocks).toEqual([ + { schema: "finding", version: 1, data: { severity: "high", title: "Leak" } }, + ]); + + expect( + createIssueSchema.parse({ + title: "UUID channel", + channel: "11111111-1111-4111-8111-111111111111", + resultSchemaRef: null, + }), + ).toMatchObject({ + channel: "11111111-1111-4111-8111-111111111111", + resultSchemaRef: null, + }); + + // Reject reserved paperclip.* keys, >64 kvLabels, invalid schema refs, subtree/blank channels, >32 schemaBlocks + expect( + createIssueSchema.safeParse({ + title: "Reserved key", + kvLabels: { "paperclip.internal": "1" }, + }).success, + ).toBe(false); + expect( + createIssueSchema.safeParse({ + title: "Too many labels", + kvLabels: Object.fromEntries(Array.from({ length: 65 }, (_, i) => [`k${i}`, "v"])), + }).success, + ).toBe(false); + for (const badRef of ["finding", "finding@0", "@1", "", "bad name@1"]) { + expect( + createIssueSchema.safeParse({ title: "Bad ref", resultSchemaRef: badRef }).success, + ).toBe(false); + } + for (const badChannel of ["", " ", "#", "build/auth/", "build/*", "bad space"]) { + expect( + createIssueSchema.safeParse({ title: "Bad channel", channel: badChannel }).success, + ).toBe(false); + } + expect( + createIssueSchema.safeParse({ + title: "Too many blocks", + schemaBlocks: Array.from({ length: 33 }, () => ({ + schema: "finding", + version: 1, + data: {}, + })), + }).success, + ).toBe(false); + }); + + it("supports kvLabels set/unset, null clears, and comment structured fields on updateIssueSchema and addIssueCommentSchema", () => { + const patch = updateIssueSchema.parse({ + kvLabels: { stage: "review", stale_key: null }, + resultSchemaRef: null, + channel: null, + schemaBlocks: [{ schema: "test-report", version: 1, data: { passed: true } }], + comment: "Verified locally", + commentKvLabels: { verdict: "pass" }, + commentSchemaBlocks: [{ schema: "test-report", version: 1, data: { passed: true } }], + }); + expect(patch.kvLabels).toEqual({ stage: "review", stale_key: null }); + expect(patch.resultSchemaRef).toBeNull(); + expect(patch.channel).toBeNull(); + expect(patch.schemaBlocks).toHaveLength(1); + expect(patch.commentKvLabels).toEqual({ verdict: "pass" }); + expect(patch.commentSchemaBlocks).toHaveLength(1); + + // Omitted fields remain undefined (no injected defaults) + const emptyPatch = updateIssueSchema.parse({}); + expect(emptyPatch.kvLabels).toBeUndefined(); + expect(emptyPatch.resultSchemaRef).toBeUndefined(); + expect(emptyPatch.channel).toBeUndefined(); + expect(emptyPatch.schemaBlocks).toBeUndefined(); + + // Reserved keys rejected on unset too + expect( + updateIssueSchema.safeParse({ kvLabels: { "paperclip.system": null } }).success, + ).toBe(false); + + const comment = addIssueCommentSchema.parse({ + body: "Found issue", + kvLabels: { kind: "audit" }, + schemaBlocks: [{ schema: "finding", version: 1, data: { severity: "low", title: "Nit" } }], + }); + expect(comment.kvLabels).toEqual({ kind: "audit" }); + expect(comment.schemaBlocks).toHaveLength(1); + expect( + addIssueCommentSchema.safeParse({ + body: "Bad key", + kvLabels: { "paperclip.secret": "no" }, + }).success, + ).toBe(false); + + // Ensure Zod v4 z.toJSONSchema succeeds for Public MCP tool input schemas + const jsonSchema = z.toJSONSchema( + z.object({ + kvLabels: issueKvLabelsSchema.optional(), + kvPatch: issueKvLabelsPatchSchema.optional(), + resultSchemaRef: issueResultSchemaRefSchema.nullable().optional(), + channel: issueChannelInputSchema.nullable().optional(), + schemaBlocks: issueSchemaBlocksSchema.optional(), + }), + ); + expect(jsonSchema).toMatchObject({ type: "object" }); + }); +}); diff --git a/packages/shared/src/validators/issue.ts b/packages/shared/src/validators/issue.ts index 6f581b6392c..4c12ab467ae 100644 --- a/packages/shared/src/validators/issue.ts +++ b/packages/shared/src/validators/issue.ts @@ -49,6 +49,15 @@ import { } from "./trust-policy.js"; import { objectWithoutDefaults } from "./partial.js"; import { questionSetToAskUserQuestionsPayload } from "../question-set.js"; +import { + kvLabelValueSchema, + writableKvLabelKeySchema, +} from "../headless/labels.js"; +import { + SCHEMA_REF_REGEX, + normalizeChannelPath, +} from "../headless/pure.js"; +import { schemaBlockSchema } from "../headless/schemas.js"; export const issueSummariesQuerySchema = z.object({ navigation: z.literal("true").optional(), @@ -59,6 +68,62 @@ export const issueSummariesQuerySchema = z.object({ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +export const MAX_ISSUE_KV_LABELS = 64; +const MAX_ISSUE_SCHEMA_BLOCKS = 32; + +export const issueKvLabelsSchema = z + .record(writableKvLabelKeySchema, kvLabelValueSchema) + .refine((labels) => Object.keys(labels).length <= MAX_ISSUE_KV_LABELS, { + message: `kvLabels may contain at most ${MAX_ISSUE_KV_LABELS} entries`, + }); + +export const issueKvLabelsPatchSchema = z + .record(writableKvLabelKeySchema, kvLabelValueSchema.nullable()) + .refine( + (labels) => + Object.keys(labels).length <= MAX_ISSUE_KV_LABELS * 2 && + Object.values(labels).filter((value) => value !== null).length <= + MAX_ISSUE_KV_LABELS, + { + message: `kvLabels may contain at most ${MAX_ISSUE_KV_LABELS} non-null entries`, + }, + ); + +export const issueResultSchemaRefSchema = z + .string() + .trim() + .toLowerCase() + .regex( + SCHEMA_REF_REGEX, + "resultSchemaRef must match @ (e.g. finding@1)", + ); + +function isValidIssueChannelInput(value: string): boolean { + const trimmed = value.trim(); + if (!trimmed || trimmed.length > 140) return false; + if (UUID_RE.test(trimmed)) return true; + try { + normalizeChannelPath(trimmed, { allowSubtreePrefix: false }); + return true; + } catch { + return false; + } +} + +export const issueChannelInputSchema = z + .string() + .trim() + .min(1) + .max(140) + .refine(isValidIssueChannelInput, { + message: + "channel must be a channel UUID or path like 'build/auth' or '#build/auth'", + }); + +export const issueSchemaBlocksSchema = z + .array(schemaBlockSchema) + .max(MAX_ISSUE_SCHEMA_BLOCKS); + /** A task reference as the UI routes use it: a UUID or an identifier such as `ABC-12`. */ function normalizeIssueRef(value: string): string | null { const trimmed = value.trim(); @@ -865,6 +930,10 @@ const createIssueBaseSchema = z.object({ .optional() .nullable(), labelIds: z.array(z.string().guid()).optional(), + kvLabels: issueKvLabelsSchema.optional(), + resultSchemaRef: issueResultSchemaRefSchema.optional().nullable(), + channel: issueChannelInputSchema.optional().nullable(), + schemaBlocks: issueSchemaBlocksSchema.optional(), watchdogDiscovery: z .object({ kind: z.enum(ISSUE_WATCHDOG_DISCOVERY_KINDS), @@ -1021,8 +1090,11 @@ export const updateIssueSchema = objectWithoutDefaults( expectedExecutionPolicy: z.record(z.string(), z.unknown()).optional().nullable(), requestDepth: issueRequestDepthInputSchema.optional(), assigneeAgentId: z.string().trim().min(1).optional().nullable(), + kvLabels: issueKvLabelsPatchSchema.optional(), comment: multilineTextSchema.pipe(z.string().min(1)).optional(), commentClientRequestId: z.string().uuid().optional(), + commentKvLabels: issueKvLabelsSchema.optional(), + commentSchemaBlocks: issueSchemaBlocksSchema.optional(), /** Only valid with a comment; the route binds these in the update transaction. */ attachmentIds: issueCommentAttachmentIdsSchema.optional(), onBehalfOfUserId: z.string().trim().min(1).optional().nullable(), @@ -1215,6 +1287,8 @@ export const addIssueCommentSchema = z.object({ clientRequestId: z.string().uuid().optional(), body: multilineTextSchema.pipe(z.string().min(1)), attachmentIds: issueCommentAttachmentIdsSchema.optional(), + kvLabels: issueKvLabelsSchema.optional(), + schemaBlocks: issueSchemaBlocksSchema.optional(), onBehalfOfUserId: z.string().trim().min(1).optional().nullable(), authorType: issueCommentAuthorTypeSchema.optional(), presentation: issueCommentPresentationSchema.nullable().optional(), diff --git a/server/src/__tests__/canonical-issue-structured-parity.test.ts b/server/src/__tests__/canonical-issue-structured-parity.test.ts new file mode 100644 index 00000000000..ae42cd8a393 --- /dev/null +++ b/server/src/__tests__/canonical-issue-structured-parity.test.ts @@ -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> | 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"); + }); + }, +); diff --git a/server/src/__tests__/public-mcp.test.ts b/server/src/__tests__/public-mcp.test.ts index a958b1a0cea..fa5b302ca58 100644 --- a/server/src/__tests__/public-mcp.test.ts +++ b/server/src/__tests__/public-mcp.test.ts @@ -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 = {}): Promise> => + 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; + 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>; + 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).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>)[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" } }]); diff --git a/server/src/__tests__/schema-fence-scanner.test.ts b/server/src/__tests__/schema-fence-scanner.test.ts new file mode 100644 index 00000000000..88548833d7f --- /dev/null +++ b/server/src/__tests__/schema-fence-scanner.test.ts @@ -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([]); + }); +}); diff --git a/server/src/routes/headless-channels-schemas.ts b/server/src/routes/headless-channels-schemas.ts index 68550999ef1..8e9cba12512 100644 --- a/server/src/routes/headless-channels-schemas.ts +++ b/server/src/routes/headless-channels-schemas.ts @@ -403,16 +403,34 @@ export function headlessChannelsSchemasRoutes( req.body && typeof req.body === "object" ? (req.body as Record) : {}; + const hasNonUuidClientRequestId = + typeof b.clientRequestId === "string" && + b.clientRequestId.trim().length > 0 && + !isUuidLike(b.clientRequestId.trim()); const hasHeadlessBody = - b.kvLabels !== undefined || b.labels !== undefined || b.blocks !== undefined || b.schema !== undefined || b.after !== undefined || b.afterCommentId !== undefined || b.internal !== undefined || - b.idempotencyKey !== undefined; + b.idempotencyKey !== undefined || + (b.text !== undefined && b.body === undefined) || + hasNonUuidClientRequestId; + const hasCanonicalOnlyBody = + b.kvLabels !== undefined || + b.schemaBlocks !== undefined || + b.attachmentIds !== undefined || + (typeof b.clientRequestId === "string" && + isUuidLike(b.clientRequestId.trim())) || + b.reopen !== undefined || + b.resume !== undefined || + b.interrupt !== undefined || + b.presentation !== undefined || + b.metadata !== undefined || + b.nativeCommand !== undefined; const hasProfileHeader = Boolean(req.header("x-paperclip-actor-profile")); + const isExplicitHeadless = hasHeadlessBody || hasProfileHeader; let targetIssue: typeof issues.$inferSelect; try { @@ -426,7 +444,9 @@ export function headlessChannelsSchemasRoutes( } const isHeadless = - hasHeadlessBody || hasProfileHeader || targetIssue.channelId !== null; + req.actor?.source !== "mcp_oauth" && + (isExplicitHeadless || + (!hasCanonicalOnlyBody && targetIssue.channelId !== null)); const isRestrictedKey = isRestrictedBoardKeyRequest(req); if (!isHeadless && !isRestrictedKey) { next(); @@ -691,11 +711,11 @@ export function headlessChannelsSchemasRoutes( ? (req.body as Record) : {}; const isHeadless = - b.kvLabels !== undefined || - b.labels !== undefined || - b.for !== undefined || - b.resultSchema !== undefined || - Boolean(req.header("x-paperclip-actor-profile")); + req.actor?.source !== "mcp_oauth" && + (b.labels !== undefined || + b.for !== undefined || + b.resultSchema !== undefined || + Boolean(req.header("x-paperclip-actor-profile"))); const isRestrictedKey = isRestrictedBoardKeyRequest(req); if (!isHeadless && !isRestrictedKey) { @@ -1075,13 +1095,13 @@ export function headlessChannelsSchemasRoutes( const labelParams = toStringArray(req.query.label); const explicitHeadless = req.query.headless === "1" || req.query.headless === "true"; const isHeadless = - explicitHeadless || - req.query.channel !== undefined || - req.query.ready !== undefined || - req.query.after !== undefined || - req.query.assignee !== undefined || - req.query.project !== undefined || - labelParams.some((l) => l.includes("=")); + req.actor?.source !== "mcp_oauth" && + (explicitHeadless || + req.query.ready !== undefined || + req.query.after !== undefined || + req.query.assignee !== undefined || + req.query.project !== undefined || + labelParams.some((l) => l.includes("="))); if (!isHeadless) { next(); @@ -1380,7 +1400,7 @@ export function headlessChannelsSchemasRoutes( await assertCanonicalIssueAccess(db, req, targetIssue, "issue:read"); await assertIssueChannelScopeAccess(db, targetIssue, actor); - if (!explicitThreadView && isBrowserRequest) { + if (!explicitThreadView && (isBrowserRequest || req.actor?.source === "mcp_oauth")) { next(); return; } diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index 91e9c836355..0048ee3535e 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -251,6 +251,23 @@ import { findInaccessibleChannelIds, resolveHeadlessActor, } from "../services/headless-common.js"; +import { validateSchemaBlocks } from "../services/headless-schemas.js"; +import { mergeIssueKvLabelsOrThrow } from "../services/issue-visibility.js"; +import { + assertAgentCannotModifyExistingResultSchemaRef, + assertAgentResultSchemaSatisfiedOnDone, + parseCanonicalKvLabelFilters, + prepareCanonicalChannelForWrite, + prepareValidatedSchemaBlocks, + resolveCanonicalChannelListFilter, + resolveStructuredIssueCreateFields, + resolveValidatedResultSchemaRef, + validateIssueKvLabelsOrThrow, +} from "../services/issue-structured-fields.js"; +import { + dedupeSchemaBlocks, + scanSchemaFences, +} from "../services/schema-fence-scanner.js"; import { runnerGoalService, RunnerGoalActionError, @@ -9148,11 +9165,26 @@ export function issueRoutes( return; } const uuidFilters = uuidQuery.values; + const channelIds = + req.query.channel !== undefined + ? await resolveCanonicalChannelListFilter( + db, + req, + companyId, + req.query.channel, + ) + : undefined; + const kvLabelFilters = + req.query.kvLabel !== undefined + ? parseCanonicalKvLabelFilters(req.query.kvLabel) + : undefined; const offset = parsedOffset ?? 0; const listFilters: IssueFilters = { issueIds, parentIds, + channelIds, + kvLabelFilters, oneChildPerParent, listProjection: view === "index" || view === "rows" ? view : undefined, readCondition: await issueReadSqlCondition(db, req.actor), @@ -9652,6 +9684,7 @@ export function issueRoutes( continuationSummary, currentExecutionWorkspace, activeRecoveryAction, + heartbeatChannelPath, ] = await Promise.all([ resolveIssueProjectAndGoal(issue), svc.getAncestors(issue.id), @@ -9672,6 +9705,7 @@ export function issueRoutes( ), currentExecutionWorkspacePromise, recoveryActionsSvc.getActiveForIssue(issue.companyId, issue.id), + resolveVisibleChannelPathForIssue(req, issue), ]); const visibleProject = await visibleIssueProject(req, project); const recoveryActionsByRelationIssue = await relationRecoveryActionMap( @@ -9733,6 +9767,11 @@ export function issueRoutes( activeRecoveryAction: revalidatedActiveRecoveryAction, priority: issue.priority, projectId: issue.projectId, + channelId: issue.channelId ?? null, + channelPath: heartbeatChannelPath, + kvLabels: issue.kvLabels ?? {}, + resultSchemaRef: issue.resultSchemaRef ?? null, + schemaBlocks: issue.schemaBlocks ?? [], goalId: goal?.id ?? issue.goalId, parentId: issue.parentId, blockedBy: visibleRelations.blockedBy, @@ -13346,8 +13385,12 @@ export function issueRoutes( const { watchdogDiscovery: rawWatchdogDiscovery, onboardingFirstTask: rawOnboardingFirstTask, + channel: rawChannel, ...rawCreateBody } = sanitizedBody; + if (rawChannel != null && rawCreateBody.scope === "chat") { + throw unprocessable("Conversation issues cannot belong to a channel"); + } // The onboarding first-task marker grants privileged, server-owned behavior: // it stamps the onboarding origin (which suppresses the seeded description in // the UI) and seeds a comment authored *as the assigned agent*. Honor it only @@ -13381,7 +13424,7 @@ export function issueRoutes( watchdogDiscovery, ); if (watchdogProductBugFollowUp === false) return; - const conversationAgentId = !rawCreateBody.assigneeAgentId && !rawCreateBody.assigneeUserId + const conversationAgentId = !rawCreateBody.assigneeAgentId && !rawCreateBody.assigneeUserId && rawChannel == null ? await resolveRunConversationAgentId(req, companyId) : null; const normalizedAssigneeAgentId = await normalizeIssueAssigneeAgentReference( @@ -13625,8 +13668,19 @@ export function issueRoutes( let deduplicationReason: "idempotency_key" | "recent_open_title" | null = null; assertActorMayWriteIssueScope(req, createBody.scope); + const { + channelPublications: createChannelPublications, + patch: structuredCreatePatch, + } = await resolveStructuredIssueCreateFields(db, req, companyId, { + rawChannel, + kvLabels: createBody.kvLabels, + resultSchemaRef: createBody.resultSchemaRef, + schemaBlocks: createBody.schemaBlocks, + description: createBody.description, + }); const createInput = { ...createBody, + ...structuredCreatePatch, workspaceSelectionActor: req.actor, projectId: createAssignmentScope.projectId, ...(taskBridgeOriginForActor(req) ?? {}), @@ -13674,11 +13728,15 @@ export function issueRoutes( createInput; issue = await createAcceptedIssue(ordinaryCreateInput); } + for (const pub of createChannelPublications) { + publishActivity(pub); + } if (deduplicationReason) { const referenceSummary = await issueReferencesSvc.listIssueReferenceSummary(issue.id); const visibleReferenceSummary = await redactIssueReferenceEdges(req, companyId, referenceSummary); res.status(200).json({ ...stripIssueClaimTokenHash(issue), + channelPath: await resolveVisibleChannelPathForIssue(req, issue), deduplicated: true, deduplicationReason, relatedWork: visibleReferenceSummary, @@ -13894,6 +13952,7 @@ export function issueRoutes( const visibleReferenceSummary = await redactIssueReferenceEdges(req, companyId, referenceSummary); res.status(201).json({ ...stripIssueClaimTokenHash(issue), + channelPath: await resolveVisibleChannelPathForIssue(req, issue), relatedWork: visibleReferenceSummary, referencedIssueIdentifiers: visibleReferenceSummary.outbound.map((item) => item.issue.identifier ?? item.issue.id), }); @@ -13955,13 +14014,24 @@ export function issueRoutes( parentIssueId: parent.id, assigneeAgentId: normalizedAssigneeAgentId ?? null, }); + const { channel: rawChildChannel, ...rawChildBody } = sanitizedBody; const createBody = { - ...sanitizedBody, + ...rawChildBody, ...(normalizedAssigneeAgentId !== undefined ? { assigneeAgentId: normalizedAssigneeAgentId } : {}), }; assertActorMayWriteIssueScope(req, createBody.scope); + const { + channelPublications: childChannelPublications, + patch: structuredChildPatch, + } = await resolveStructuredIssueCreateFields(db, req, parent.companyId, { + rawChannel: rawChildChannel, + kvLabels: createBody.kvLabels, + resultSchemaRef: createBody.resultSchemaRef, + schemaBlocks: createBody.schemaBlocks, + description: createBody.description, + }); // Board users nest freely, and watchdog follow-ups are located by parent. // Other agents build at most parent → child trees: a child of a child is // placed beside it instead (never rejected). @@ -14047,6 +14117,7 @@ export function issueRoutes( ); const { issue, parentBlockerAdded } = await svc.createChild(parent.id, { ...createBody, + ...structuredChildPatch, parentDepthPolicy: childParentDepthPolicy, ...(childParentDepthPolicy === "flatten" ? { expectedParentId: childPlacement.effectiveParentId } : {}), workspaceSelectionActor: req.actor, @@ -14074,6 +14145,9 @@ export function issueRoutes( watchdogActorRunId: actor.runId, assertCanReuseIssue: (existing) => assertCanReuseCreatedIssue(req, existing), }); + for (const pub of childChannelPublications) { + publishActivity(pub); + } await externalObjectsSvc.syncIssueSafely(issue.id); await logActivity(db, { @@ -14174,7 +14248,10 @@ export function issueRoutes( }); await queueTaskWatchdogEvaluation(issue, actor.runId); - res.status(201).json(issue); + res.status(201).json({ + ...stripIssueClaimTokenHash(issue), + channelPath: await resolveVisibleChannelPathForIssue(req, issue), + }); }, ); @@ -15086,7 +15163,7 @@ export function issueRoutes( return; } const commentOnlyUpdate = Boolean(req.body.comment) && Object.keys(req.body).every(key => - ["comment", "commentClientRequestId", "attachmentIds", "onBehalfOfUserId"].includes(key)); + ["comment", "commentClientRequestId", "commentKvLabels", "commentSchemaBlocks", "attachmentIds", "onBehalfOfUserId"].includes(key)); const issueMutationAccess = commentOnlyUpdate ? await assertAgentIssueCommentAllowed(req, res, existing) : await assertAgentIssueMutationAllowed( req, res, @@ -15120,7 +15197,11 @@ export function issueRoutes( const { comment: commentBody, commentClientRequestId, + commentKvLabels: rawCommentKvLabels, + commentSchemaBlocks: rawCommentSchemaBlocks, attachmentIds: commentAttachmentIds, + channel: rawChannelPatch, + kvLabels: rawKvLabelsPatch, reviewInteractionId: requestedReviewInteractionId, reviewRequest, reopen: reopenRequested, @@ -15133,6 +15214,87 @@ export function issueRoutes( onBehalfOfUserId: _requestedOnBehalfOfUserId, ...updateFields } = req.body; + if ( + (rawCommentKvLabels !== undefined || rawCommentSchemaBlocks !== undefined) && + !commentBody + ) { + res.status(400).json({ + error: "commentKvLabels and commentSchemaBlocks require a comment", + }); + return; + } + if (req.actor.type === "agent") { + assertAgentCannotModifyExistingResultSchemaRef( + existing.resultSchemaRef, + updateFields.resultSchemaRef, + ); + } + if (rawKvLabelsPatch !== undefined) { + mergeIssueKvLabelsOrThrow(existing.kvLabels ?? {}, rawKvLabelsPatch); + } + if (updateFields.resultSchemaRef !== undefined) { + updateFields.resultSchemaRef = await resolveValidatedResultSchemaRef( + db, + existing.companyId, + updateFields.resultSchemaRef, + ); + if (req.actor.type === "agent") { + assertAgentCannotModifyExistingResultSchemaRef( + existing.resultSchemaRef, + updateFields.resultSchemaRef, + ); + } + } + const explicitIssueSchemaBlocks = + updateFields.schemaBlocks !== undefined + ? dedupeSchemaBlocks([ + ...updateFields.schemaBlocks, + ...(updateFields.description !== undefined + ? scanSchemaFences(updateFields.description, { strict: true }) + : []), + ]) + : undefined; + const descriptionOnlyFenceBlocks = + updateFields.schemaBlocks === undefined && + updateFields.description !== undefined + ? scanSchemaFences(updateFields.description, { strict: true }) + : []; + const preLockCandidateIssueSchemaBlocks = + explicitIssueSchemaBlocks !== undefined + ? explicitIssueSchemaBlocks + : descriptionOnlyFenceBlocks.length > 0 + ? dedupeSchemaBlocks([ + ...(Array.isArray(existing.schemaBlocks) + ? existing.schemaBlocks + : []), + ...descriptionOnlyFenceBlocks, + ]) + : undefined; + const validatedPatchCommentKvLabels = + rawCommentKvLabels !== undefined + ? validateIssueKvLabelsOrThrow(rawCommentKvLabels) + : undefined; + const rawCandidateCommentSchemaBlocks = commentBody + ? dedupeSchemaBlocks([ + ...(rawCommentSchemaBlocks ?? []), + ...scanSchemaFences(commentBody, { strict: true }), + ]) + : []; + if ( + typeof rawChannelPatch === "string" && + (existing.conversationAgentId || req.body.scope === "chat") + ) { + throw unprocessable("Conversation issues cannot belong to a channel"); + } + const preparedPatchChannel = + typeof rawChannelPatch === "string" + ? await prepareCanonicalChannelForWrite( + db, + req, + existing.companyId, + rawChannelPatch, + ) + : null; if (commentBody && req.actor.type === "agent") { await assertAgentInteraction(db, { companyId: existing.companyId, actorAgentId: req.actor.agentId, operation: "comment", issueId: existing.id, texts: [commentBody] }); @@ -15422,6 +15584,8 @@ export function issueRoutes( const isAgentWorkUpdate = req.actor.type === "agent" && (Object.keys(updateFields).length > 0 || + rawChannelPatch !== undefined || + rawKvLabelsPatch !== undefined || reviewRequest !== undefined || hiddenAtRaw !== undefined); @@ -15620,6 +15784,43 @@ export function issueRoutes( const nextStatus = updateFields.status ?? existing.status; if (!(await assertAgentMayLeaveBlocked(req, res, existing, nextStatus))) return; + const completesTaskOrFinalStage = + (updateFields.status === "done" && existing.status !== "done") || + deferredNativeStageApproval; + if (req.actor.type === "agent" && completesTaskOrFinalStage) { + await assertAgentResultSchemaSatisfiedOnDone(db, { + companyId: existing.companyId, + issue: existing, + nextResultSchemaRef: updateFields.resultSchemaRef, + nextDescription: updateFields.description, + nextIssueSchemaBlocks: preLockCandidateIssueSchemaBlocks, + incomingCommentBody: commentBody, + incomingCommentSchemaBlocks: rawCandidateCommentSchemaBlocks, + }); + } + if (explicitIssueSchemaBlocks !== undefined) { + updateFields.schemaBlocks = await validateSchemaBlocks( + db, + existing.companyId, + explicitIssueSchemaBlocks, + ); + } + const validatedDescriptionOnlyFenceBlocks = + descriptionOnlyFenceBlocks.length > 0 + ? await validateSchemaBlocks( + db, + existing.companyId, + descriptionOnlyFenceBlocks, + ) + : []; + const validatedPatchCommentSchemaBlocks = + rawCandidateCommentSchemaBlocks.length > 0 + ? await validateSchemaBlocks( + db, + existing.companyId, + rawCandidateCommentSchemaBlocks, + ) + : []; if (updateFields.unblockDescriptor && nextStatus !== "blocked") { throw unprocessable("unblockDescriptor requires blocked status"); } @@ -16009,10 +16210,77 @@ export function issueRoutes( const stopRelayResult: { value: Awaited>; } = { value: null }; - const postCommitActivityPublications: ActivityPublication[] = []; + const patchChannelPublications: ActivityPublication[] = []; + if (rawChannelPatch === null) { + updateFields.channelId = null; + if (req.body.scope === undefined && existing.scope === "channel") { + updateFields.scope = req.actor.type === "agent" ? "agent" : "board"; + } + } else if (preparedPatchChannel) { + const resolvedPatchChannel = await preparedPatchChannel.materialize({ + publications: patchChannelPublications, + }); + updateFields.channelId = resolvedPatchChannel.id; + if (req.body.scope === undefined && existing.scope !== "chat") { + updateFields.scope = "channel"; + } + } + assertActorMayWriteIssueScope(req, updateFields.scope, existing.scope); + const postCommitActivityPublications: ActivityPublication[] = [ + ...patchChannelPublications, + ]; const postCommitIssueActions: IssuePostCommitAction[] = []; + const needsAgentResultSchemaLockGuard = + req.actor.type === "agent" && + (updateFields.resultSchemaRef !== undefined || + updateFields.status === "done" || + deferredNativeStageApproval); + const needsLockedIssueHook = + needsAgentResultSchemaLockGuard || + validatedDescriptionOnlyFenceBlocks.length > 0; const issueUpdateData = { ...updateFields, + ...(rawKvLabelsPatch !== undefined ? { kvLabelsPatch: rawKvLabelsPatch } : {}), + ...(needsLockedIssueHook + ? { + beforeLockedUpdate: async ( + tx: Parameters[0], + lockedIssue: typeof issueRows.$inferSelect, + lockedPatch: Partial, + ) => { + if (validatedDescriptionOnlyFenceBlocks.length > 0) { + lockedPatch.schemaBlocks = dedupeSchemaBlocks([ + ...(Array.isArray(lockedIssue.schemaBlocks) + ? lockedIssue.schemaBlocks + : []), + ...validatedDescriptionOnlyFenceBlocks, + ]); + } + if (!needsAgentResultSchemaLockGuard) return; + assertAgentCannotModifyExistingResultSchemaRef( + lockedIssue.resultSchemaRef, + updateFields.resultSchemaRef, + ); + const lockedCompletesTask = + ((lockedPatch.status ?? lockedIssue.status) === "done" && + lockedIssue.status !== "done") || + deferredNativeStageApproval; + if (!lockedCompletesTask) return; + await assertAgentResultSchemaSatisfiedOnDone(tx, { + companyId: lockedIssue.companyId, + issue: lockedIssue, + nextResultSchemaRef: updateFields.resultSchemaRef, + nextDescription: updateFields.description, + nextIssueSchemaBlocks: + lockedPatch.schemaBlocks !== undefined + ? (lockedPatch.schemaBlocks as typeof validatedDescriptionOnlyFenceBlocks) + : explicitIssueSchemaBlocks, + incomingCommentBody: commentBody, + incomingCommentSchemaBlocks: rawCandidateCommentSchemaBlocks, + }); + }, + } + : {}), ...(updateFields.parentId !== undefined ? { parentDepthPolicy } : {}), ...(expectedParentId !== undefined ? { expectedParentId } : {}), workspaceSelectionActor: req.actor, @@ -16170,14 +16438,21 @@ export function issueRoutes( const commentWithAdapterOverrides = Boolean( commentBody && updateFields.assigneeAdapterOverrides !== undefined, ); + const commentWithStructuredPayload = Boolean( + commentBody && + (validatedPatchCommentSchemaBlocks.length > 0 || + rawCommentSchemaBlocks !== undefined || + validatedPatchCommentKvLabels !== undefined), + ); const agentCommentUpdate = Boolean(commentBody && actor.actorType === "agent"); - const transactionalCommentSourceTrust = commentAttachmentIds?.length || commentWithAdapterOverrides || agentCommentUpdate + const transactionalCommentSourceTrust = commentAttachmentIds?.length || commentWithAdapterOverrides || commentWithStructuredPayload || agentCommentUpdate ? await sourceTrustForActorWrite(existing, actor) : undefined; const shouldUseTransactionalIssueUpdate = Boolean(commentAttachmentIds?.length) || agentCommentUpdate || commentWithAdapterOverrides || + commentWithStructuredPayload || Boolean(decision) || shouldRelayStop || persistReviewActivityTransactionally || @@ -16202,7 +16477,7 @@ export function issueRoutes( return null; const updated = await updateIssue(tx); if (!updated) return null; - if (commentAttachmentIds?.length || commentWithAdapterOverrides || agentCommentUpdate) { + if (commentAttachmentIds?.length || commentWithAdapterOverrides || commentWithStructuredPayload || agentCommentUpdate) { // Adapter settings, reassignment, comment and upload binding commit together. // A failed comment or invalid receipt rolls back the issue update. transactionalComment = await svc.addComment( @@ -16217,6 +16492,13 @@ export function issueRoutes( }, { attachmentIds: commentAttachmentIds, + ...(validatedPatchCommentKvLabels !== undefined + ? { kvLabels: validatedPatchCommentKvLabels } + : {}), + ...(validatedPatchCommentSchemaBlocks.length > 0 || + rawCommentSchemaBlocks !== undefined + ? { schemaBlocks: validatedPatchCommentSchemaBlocks } + : {}), clientRequestId: actor.actorType === "user" ? commentClientRequestId : undefined, mirrorToSlack: actor.actorType === "user", authorizationReason: issueMutationAuthorizationReason, @@ -16836,6 +17118,13 @@ export function issueRoutes( }, { authorizationReason: issueMutationAuthorizationReason, + ...(validatedPatchCommentKvLabels !== undefined + ? { kvLabels: validatedPatchCommentKvLabels } + : {}), + ...(validatedPatchCommentSchemaBlocks.length > 0 || + rawCommentSchemaBlocks !== undefined + ? { schemaBlocks: validatedPatchCommentSchemaBlocks } + : {}), clientRequestId: actor.actorType === "user" ? commentClientRequestId : undefined, mirrorToSlack: actor.actorType === "user", sourceTrust: await sourceTrustForActorWrite(issue, actor), @@ -19793,6 +20082,16 @@ export function issueRoutes( return; } } + const validatedCommentKvLabels = + req.body.kvLabels !== undefined + ? validateIssueKvLabelsOrThrow(req.body.kvLabels) + : undefined; + const validatedCommentSchemaBlocks = await prepareValidatedSchemaBlocks( + db, + issue.companyId, + req.body.schemaBlocks, + req.body.body, + ); if (issue.conversationAgentId && req.actor.type === "board") { if (!req.actor.userId) throw forbidden("Board user access required"); if (req.actor.userId !== issue.conversationUserId) throw forbidden("Only the conversation owner can send messages or start a new session"); @@ -19812,6 +20111,10 @@ export function issueRoutes( )); const saved = await svc.addComment(issue.id, req.body.body, { userId }, { clientRequestId: req.body.clientRequestId, authorType: "user", attachmentIds: req.body.attachmentIds, + ...(validatedCommentKvLabels !== undefined ? { kvLabels: validatedCommentKvLabels } : {}), + ...(validatedCommentSchemaBlocks.length > 0 || req.body.schemaBlocks !== undefined + ? { schemaBlocks: validatedCommentSchemaBlocks } + : {}), }, tx); if (!existing) await logActivity(tx as unknown as Db, { companyId: issue.companyId, actorType: actor.actorType, actorId: actor.actorId, @@ -20245,6 +20548,13 @@ export function issueRoutes( presentation: commentPresentation, metadata: req.body.metadata ?? null, attachmentIds: req.body.attachmentIds, + ...(validatedCommentKvLabels !== undefined + ? { kvLabels: validatedCommentKvLabels } + : {}), + ...(validatedCommentSchemaBlocks.length > 0 || + req.body.schemaBlocks !== undefined + ? { schemaBlocks: validatedCommentSchemaBlocks } + : {}), clientRequestId: actor.actorType === "user" ? req.body.clientRequestId : undefined, mirrorToSlack: actor.actorType === "user", sourceTrust, @@ -20364,6 +20674,13 @@ export function issueRoutes( presentation: commentPresentation, metadata: req.body.metadata ?? null, attachmentIds: req.body.attachmentIds, + ...(validatedCommentKvLabels !== undefined + ? { kvLabels: validatedCommentKvLabels } + : {}), + ...(validatedCommentSchemaBlocks.length > 0 || + req.body.schemaBlocks !== undefined + ? { schemaBlocks: validatedCommentSchemaBlocks } + : {}), clientRequestId: actor.actorType === "user" ? req.body.clientRequestId : undefined, mirrorToSlack: actor.actorType === "user", authorizationReason: commentAuthorizationReason, diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts index fe8be1a89b6..a99577c17df 100644 --- a/server/src/routes/openapi.ts +++ b/server/src/routes/openapi.ts @@ -1,4 +1,23 @@ import { createAgentSetupProgressSchema, setAgentSetupChecklistSchema, updateAgentSetupItemSchema, finishAgentSetupSchema } from "@paperclipai/shared"; +import { + agentIdentityPolicySchema, + BatchCreateIssuesSchema, + channelPostInputSchema, + createChannelInputSchema, + createCompanySchemaInputSchema, + KvLabelMutationSchema, + OneLineAskSchema, + OneLineConfirmSchema, + ResolveInteractionInputSchema, + SCHEMA_REF_REGEX, + SchedulePostSchema, + TaskClaimRequestSchema, + TaskCompleteSchema, + TaskFailSchema, + TaskReleaseSchema, + TaskRenewSchema, + writableKvLabelsRecordSchema, +} from "@paperclipai/shared"; import { catalogTeamInstallSchema, catalogTeamPreviewSchema, updateWorkspacePreferenceSchema, issueDocumentBatchQuerySchema } from "@paperclipai/shared"; import { MUSE_ASSET_VERSION, museStopBoundarySchema, museDetectorCleanupAttestationSchema, createGrokInvitationSchema, configureGrokRoutineSchema, verifyGrokRoutineSchema, recoverGrokRoutineSchema, pairGrokBindingSchema, stopGrokWorkSchema, retryGrokDeliverySchema, updateFastResponseSchema } from "@paperclipai/shared"; import { slackTestMessageSchema, slackTestMessageResultSchema, slackManagerAuthorizationSchema, slackSetupOptionsSchema, slackManagedProvisionSchema, slackManagedResultSchema, slackRegistrationSchema, slackSetupActionSchema, slackInstallAuthorizationSchema, slackRegistrationStateSchema, slackAppConfigurationSchema, slackAvatarStateSchema, slackAccountStateSchema } from "@paperclipai/shared"; @@ -4651,6 +4670,8 @@ registry.registerPath({ sortField: z.enum(["updated", "created", "id"]).optional(), sortDir: z.enum(["asc", "desc"]).optional(), afterId: z.string().uuid().optional().describe("Cursor paging: return rows after this task UUID; requires sortField=id, sortDir=asc and no offset. Use X-Paperclip-Next-After-Id (call_api: pagination.nextAfterId)."), + channel: z.string().max(140).optional().describe("Filter by channel UUID, exact path ('build/auth' or '#build/auth'), or subtree prefix ('build/' or 'build/*'). Inaccessible private channels are excluded."), + kvLabel: z.union([z.string().max(256), z.array(z.string().max(256)).max(16)]).optional().describe("Filter by key-value label expression ('key', 'key=value', or 'key=v1|v2'). Repeat to combine with AND."), }).passthrough(), }, responses: { @@ -14474,43 +14495,254 @@ for (const [method, path, summary] of [ }, }); -for (const [method, path, tag, summary, status] of [ - ["get", "/api/companies/{companyId}/channels", "headless", "List accessible channels in a company", 200], - ["post", "/api/companies/{companyId}/channels", "headless", "Create or update a channel", 201], - ["post", "/api/companies/{companyId}/channels/posts", "headless", "Create a channel post or queued task", 201], - ["get", "/api/companies/{companyId}/channels/threads", "headless", "List threads and posts in a channel or subtree", 200], - ["patch", "/api/issues/{id}/kv-labels", "headless", "Atomically update key-value labels with CAS preconditions", 200], - ["get", "/api/companies/{companyId}/schemas", "headless", "List company JSON schemas", 200], - ["get", "/api/companies/{companyId}/schemas/{ref}", "headless", "Get a versioned company JSON schema", 200], - ["post", "/api/companies/{companyId}/schemas", "headless", "Create an immutable versioned JSON schema", 201], - ["post", "/api/companies/{companyId}/issues/batch", "headless", "Create a topological DAG batch of tasks", 201], - ["post", "/api/companies/{companyId}/tasks/claim", "headless", "Atomically claim a ready task from a queue", 200], - ["post", "/api/issues/{id}/claim/renew", "headless", "Renew an active fenced task claim lease", 200], - ["post", "/api/issues/{id}/claim/release", "headless", "Release an active fenced task claim lease", 200], - ["post", "/api/issues/{id}/claim/complete", "headless", "Complete a claimed task with optional structured result", 200], - ["post", "/api/issues/{id}/claim/fail", "headless", "Fail or requeue a claimed task", 200], - ["post", "/api/issues/{id}/ask", "headless", "Post a question interaction and release claim", 200], - ["post", "/api/issues/{id}/confirm", "headless", "Post a confirmation interaction and release claim", 200], - ["post", "/api/issues/{id}/approve", "headless", "Approve or answer a pending interaction", 200], - ["post", "/api/issues/{id}/reject", "headless", "Reject a pending interaction", 200], - ["post", "/api/companies/{companyId}/schedules", "headless", "Schedule a delayed or recurring board post", 201], - ["get", "/api/companies/{companyId}/schedules", "headless", "List scheduled board posts", 200], - ["delete", "/api/companies/{companyId}/schedules/{id}", "headless", "Cancel a scheduled board post", 200], - ["get", "/api/companies/{companyId}/events/wait", "headless", "Wait for the next matching board event", 200], - ["get", "/api/companies/{companyId}/events/stream", "headless", "Stream matching board events over SSE", 200], - ["get", "/api/companies/resolve-default", "headless", "Resolve or bootstrap the default company", 200], - ["get", "/api/whoami", "headless", "Inspect current authenticated board or agent identity", 200], - ["post", "/api/companies/{companyId}/agents/connect", "headless", "Create or mint an API key for a headless agent", 201], - ["patch", "/api/companies/{companyId}/agent-identity-policy", "headless", "Update company agent identity policy", 200], +const headlessOpenApiChannelPostSchema = channelPostInputSchema + .extend({ + status: z.enum(["backlog", "todo"]).optional(), + for: z.string().min(1).optional(), + assigneeAgentId: z.string().uuid().nullable().optional(), + resultSchema: z + .string() + .refine((v) => SCHEMA_REF_REGEX.test(v.trim()), { + message: "resultSchema must match @", + }) + .optional(), + kvLabels: writableKvLabelsRecordSchema.optional(), + }) + .passthrough(); + +const headlessOpenApiEventQueryFields = { + channel: z.string().optional().describe("Channel path or subtree prefix"), + issueId: z.string().optional().describe("Issue UUID or identifier"), + event: z.union([z.string(), z.array(z.string())]).optional().describe("Comma-separated or repeated BoardEventType values"), + label: z.union([z.string(), z.array(z.string())]).optional().describe("Label filter expression(s)"), + mentions: z.string().optional().describe("Filter events mentioning @agent or profile"), + schema: z.string().optional().describe("Filter events carrying blocks for @"), + after: z.string().optional().describe("Event cursor evt_"), +}; + +for (const route of [ + { + method: "get", + path: "/api/companies/{companyId}/channels", + summary: "List accessible channels in a company", + status: 200, + query: z.object({ + prefix: z.string().optional().describe("Optional channel path prefix such as 'security/'"), + }), + }, + { + method: "post", + path: "/api/companies/{companyId}/channels", + summary: "Create or update a channel", + status: 201, + body: createChannelInputSchema, + }, + { + method: "post", + path: "/api/companies/{companyId}/channels/posts", + summary: "Create a channel post or queued task", + status: 201, + body: headlessOpenApiChannelPostSchema, + }, + { + method: "get", + path: "/api/companies/{companyId}/channels/threads", + summary: "List threads and posts in a channel or subtree", + status: 200, + query: z.object({ + channel: z.string().optional().describe("Channel path or subtree prefix (defaults to 'general')"), + status: z.union([z.string(), z.array(z.string())]).optional(), + label: z.union([z.string(), z.array(z.string())]).optional(), + after: z.string().optional().describe("Event cursor evt_"), + limit: z.number().int().min(1).max(200).optional(), + }), + }, + { + method: "patch", + path: "/api/issues/{id}/kv-labels", + summary: "Atomically update key-value labels with CAS preconditions", + status: 200, + body: KvLabelMutationSchema, + }, + { + method: "get", + path: "/api/companies/{companyId}/schemas", + summary: "List company JSON schemas", + status: 200, + }, + { + method: "get", + path: "/api/companies/{companyId}/schemas/{ref}", + summary: "Get a versioned company JSON schema", + status: 200, + }, + { + method: "post", + path: "/api/companies/{companyId}/schemas", + summary: "Create an immutable versioned JSON schema", + status: 201, + body: createCompanySchemaInputSchema, + }, + { + method: "post", + path: "/api/companies/{companyId}/issues/batch", + summary: "Create a topological DAG batch of tasks", + status: 201, + body: BatchCreateIssuesSchema, + }, + { + method: "post", + path: "/api/companies/{companyId}/tasks/claim", + summary: "Atomically claim a ready task from a queue", + status: 200, + body: TaskClaimRequestSchema, + }, + { + method: "post", + path: "/api/issues/{id}/claim/renew", + summary: "Renew an active fenced task claim lease", + status: 200, + body: TaskRenewSchema, + }, + { + method: "post", + path: "/api/issues/{id}/claim/release", + summary: "Release an active fenced task claim lease", + status: 200, + body: TaskReleaseSchema, + }, + { + method: "post", + path: "/api/issues/{id}/claim/complete", + summary: "Complete a claimed task with optional structured result", + status: 200, + body: TaskCompleteSchema, + }, + { + method: "post", + path: "/api/issues/{id}/claim/fail", + summary: "Fail or requeue a claimed task", + status: 200, + body: TaskFailSchema, + }, + { + method: "post", + path: "/api/issues/{id}/ask", + summary: "Post a question interaction and release claim", + status: 200, + body: OneLineAskSchema, + }, + { + method: "post", + path: "/api/issues/{id}/confirm", + summary: "Post a confirmation interaction and release claim", + status: 200, + body: OneLineConfirmSchema, + }, + { + method: "post", + path: "/api/issues/{id}/approve", + summary: "Approve or answer a pending interaction", + status: 200, + body: ResolveInteractionInputSchema, + }, + { + method: "post", + path: "/api/issues/{id}/reject", + summary: "Reject a pending interaction", + status: 200, + body: ResolveInteractionInputSchema, + }, + { + method: "post", + path: "/api/companies/{companyId}/schedules", + summary: "Schedule a delayed or recurring board post", + status: 201, + body: SchedulePostSchema, + }, + { + method: "get", + path: "/api/companies/{companyId}/schedules", + summary: "List scheduled board posts", + status: 200, + query: z.object({ + target: z.string().optional().describe("Filter schedules by target channel path or issue identifier/UUID"), + }), + }, + { + method: "delete", + path: "/api/companies/{companyId}/schedules/{id}", + summary: "Cancel a scheduled board post", + status: 200, + }, + { + method: "get", + path: "/api/companies/{companyId}/events/wait", + summary: "Wait for the next matching board event", + status: 200, + query: z.object({ + ...headlessOpenApiEventQueryFields, + timeoutMs: z.number().int().nonnegative().optional().describe("Long-poll wait duration in milliseconds"), + timeout: z.string().optional().describe("Duration string such as '5s' or '30s'"), + }), + }, + { + method: "get", + path: "/api/companies/{companyId}/events/stream", + summary: "Stream matching board events over SSE", + status: 200, + query: z.object(headlessOpenApiEventQueryFields), + }, + { + method: "get", + path: "/api/companies/resolve-default", + summary: "Resolve or bootstrap the default company", + status: 200, + query: z.object({ + company: z.string().optional().describe("Optional company ID, issue prefix, or name"), + }), + }, + { + method: "get", + path: "/api/whoami", + summary: "Inspect current authenticated board or agent identity", + status: 200, + query: z.object({ + companyId: z.string().optional(), + company: z.string().optional(), + }), + }, + { + method: "post", + path: "/api/companies/{companyId}/agents/connect", + summary: "Create or mint an API key for a headless agent", + status: 201, + body: z.object({ + name: z.string().trim().min(1).max(120), + role: z.string().trim().min(1).max(60).optional(), + ttlSec: z.number().int().positive().optional(), + }), + }, + { + method: "patch", + path: "/api/companies/{companyId}/agent-identity-policy", + summary: "Update company agent identity policy", + status: 200, + body: z.object({ + agentIdentityPolicy: agentIdentityPolicySchema, + }), + }, ] as const) { registerCurrentRoute({ - method, - path, - tags: [tag], - summary, + method: route.method, + path: route.path, + tags: ["headless"], + summary: route.summary, + ...("query" in route ? { query: route.query } : {}), + ...("body" in route ? { body: route.body } : {}), responses: { - [status]: r.ok(), - ...(path === "/api/companies/{companyId}/tasks/claim" || path === "/api/companies/{companyId}/events/wait" + [route.status]: r.ok(), + ...(route.path === "/api/companies/{companyId}/tasks/claim" || route.path === "/api/companies/{companyId}/events/wait" ? { 204: { description: "No matching work or event before timeout" } } : {}), 400: r.badRequest, diff --git a/server/src/services/headless-channels.ts b/server/src/services/headless-channels.ts index 565a1c95991..09777fc6db7 100644 --- a/server/src/services/headless-channels.ts +++ b/server/src/services/headless-channels.ts @@ -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 { - 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", { diff --git a/server/src/services/headless-events-schedules-interactions.ts b/server/src/services/headless-events-schedules-interactions.ts index f0866f81cbe..0e186bfcf8e 100644 --- a/server/src/services/headless-events-schedules-interactions.ts +++ b/server/src/services/headless-events-schedules-interactions.ts @@ -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; diff --git a/server/src/services/issue-structured-fields.ts b/server/src/services/issue-structured-fields.ts new file mode 100644 index 00000000000..f812c0149aa --- /dev/null +++ b/server/src/services/issue-structured-fields.ts @@ -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, +): Record { + 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; +} + +export async function prepareCanonicalChannelForWrite( + dbOrTx: DbOrTx, + req: Request, + companyId: string, + rawChannel: string, +): Promise { + 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 { + 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 { + 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 { + 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 { + 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 | undefined; + resultSchemaRef: string | null | undefined; + schemaBlocks: readonly SchemaBlock[] | undefined; + description: string | null | undefined; + }, +): Promise<{ + channelPublications: ActivityPublication[]; + patch: { + channelId?: string; + kvLabels?: Record; + 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 { + const effectiveRef = + args.issue.resultSchemaRef ?? + (args.nextResultSchemaRef !== undefined ? args.nextResultSchemaRef : null); + if (!effectiveRef) return; + + let parsedRef: ReturnType; + 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>; + 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, + }, + ); +} diff --git a/server/src/services/issue-visibility.ts b/server/src/services/issue-visibility.ts index 1e34e4fe4e6..54b94102cce 100644 --- a/server/src/services/issue-visibility.ts +++ b/server/src/services/issue-visibility.ts @@ -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 { + switch (expr.kind) { + case "equals": + return sql`${issues.kvLabels}->>${expr.key} = ${expr.value}`; + case "in": + return sql`${issues.kvLabels}->>${expr.key} IN (${sql.join( + expr.values.map((v) => sql`${v}`), + sql`, `, + )})`; + case "exists": + return sql`(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 | null | undefined, + patch: Record, +): Record { + const next: Record = { ...(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() || diff --git a/server/src/services/issues.ts b/server/src/services/issues.ts index fce18873a81..38c6afc0e33 100644 --- a/server/src/services/issues.ts +++ b/server/src/services/issues.ts @@ -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`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 & { labelIds?: string[]; + kvLabelsPatch?: Record; + beforeLockedUpdate?: ( + tx: any, + lockedIssue: typeof issues.$inferSelect, + lockedPatch: Partial, + ) => Promise; 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; + 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 diff --git a/server/src/services/native-runtime/runner-api-reference.test.ts b/server/src/services/native-runtime/runner-api-reference.test.ts index 33bb2467d13..72bbcbbbe0e 100644 --- a/server/src/services/native-runtime/runner-api-reference.test.ts +++ b/server/src/services/native-runtime/runner-api-reference.test.ts @@ -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"])); + }); }); diff --git a/server/src/services/native-runtime/runner-api-reference.ts b/server/src/services/native-runtime/runner-api-reference.ts index 0ff4be47633..6f38cd9dec2 100644 --- a/server/src/services/native-runtime/runner-api-reference.ts +++ b/server/src/services/native-runtime/runner-api-reference.ts @@ -79,7 +79,7 @@ export const runnerApiReference: Record@`) 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" } } + ] + } + } + ] } }; diff --git a/server/src/services/public-mcp/capabilities.ts b/server/src/services/public-mcp/capabilities.ts index 442c40253f1..afb0986bb7a 100644 --- a/server/src/services/public-mcp/capabilities.ts +++ b/server/src/services/public-mcp/capabilities.ts @@ -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.", diff --git a/server/src/services/public-mcp/contracts.ts b/server/src/services/public-mcp/contracts.ts index ead3d812619..3c564ce3924 100644 --- a/server/src/services/public-mcp/contracts.ts +++ b/server/src/services/public-mcp/contracts.ts @@ -24,8 +24,8 @@ export const boundedLimit = z.number().int().min(1).max(100).default(30); export const object = (v: unknown): Record => v !== null && typeof v === "object" && !Array.isArray(v) ? v as Record : {}; 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) => { diff --git a/server/src/services/public-mcp/expanded-capabilities.ts b/server/src/services/public-mcp/expanded-capabilities.ts index 7a8ce01808c..45cd05afc09 100644 --- a/server/src/services/public-mcp/expanded-capabilities.ts +++ b/server/src/services/public-mcp/expanded-capabilities.ts @@ -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(); diff --git a/server/src/services/schema-fence-scanner.ts b/server/src/services/schema-fence-scanner.ts new file mode 100644 index 00000000000..2c90a5c4c0e --- /dev/null +++ b/server/src/services/schema-fence-scanner.ts @@ -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=@ ```` 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, + }); + } + 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(); + 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; +} diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index abd639d8a62..f50f66c530a 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -281,7 +281,7 @@ "packages/shared/src/headless/identity.ts": "aef0e7ee58f458f3ea0a956d8b4041e8998ce717", "packages/shared/src/headless/index.ts": "011e7b457f61d2fbd1bec7827985b6b689c7f22f", "packages/shared/src/headless/labels.ts": "18cb9acceeb27ed4cb75aa592786e3d845fcc70f", - "packages/shared/src/headless/leases.ts": "0615826ad9bf8d346ab507de300a3fb82acf4462", + "packages/shared/src/headless/leases.ts": "c5370155f85ebde371952da07d8cf2d9d8427b52", "packages/shared/src/headless/plans.ts": "9755160a884569aff9cfaaac8330486e392951ee", "packages/shared/src/headless/pure.ts": "962757460d6e60494bbb75d2f476fb2be1e530dc", "packages/shared/src/headless/schemas.ts": "eb0716395a15111699d18ec209a2fda4990b9e4d", @@ -290,7 +290,7 @@ "packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d", "packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca", "packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699", - "packages/shared/src/index.ts": "776afee882c64d1eaa5736b8a971a521232c02e8", + "packages/shared/src/index.ts": "ecc9ea3b705c264939c941e673f21c2dbbcd1b7f", "packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca", "packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075", "packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9", @@ -540,13 +540,13 @@ "packages/shared/src/validators/folder.ts": "b486444ab09ec3d5a9afec7dbd2e71c1bc2beb67", "packages/shared/src/validators/goal.ts": "602724134915e1e83c50115abba36b288c0abd3d", "packages/shared/src/validators/inbox-agent-policy.ts": "29cef157f4d9b564fd813868038aa8c813df4a7b", - "packages/shared/src/validators/index.ts": "e5cc6c6d323e97ed17c16ed20ad3a9371fbb0727", + "packages/shared/src/validators/index.ts": "c96d9929e410dc95a8b2e0325b37e6c303711ebe", "packages/shared/src/validators/instance.test.ts": "a8eac3e9a6eed97d6aa4f54e14e77c44720600af", "packages/shared/src/validators/instance.ts": "9cfe716ebf4dc1e24324e162ca096cdacbe97c4a", "packages/shared/src/validators/issue-chat-bootstrap.test.ts": "e1ebb9aa94da22c825bc3ddd32ce2cfc98bfe645", "packages/shared/src/validators/issue-tree-control.ts": "7144ef86a83e008ac0626e1d62a1d6164c46f438", - "packages/shared/src/validators/issue.test.ts": "7584bcce33a933ebcb02695b439767163e5ef61a", - "packages/shared/src/validators/issue.ts": "6f581b6392cc1005b3dfdb2af2084773721410e8", + "packages/shared/src/validators/issue.test.ts": "370c30797dedb3cad8fdf26a5ee4d2dbb0ba0c25", + "packages/shared/src/validators/issue.ts": "4c12ab467aee250dc726728a2627f2915ad3c71d", "packages/shared/src/validators/json-schema.ts": "b6cba6a3f76b49afce1c7dc1c2f086ab946c6133", "packages/shared/src/validators/native-finalization.test.ts": "40c68bdd1d0e8a77cd70c4576fae53334fe5be0d", "packages/shared/src/validators/native-finalization.ts": "d4e674de6ac7d36385e6f6c2172fa16ffc9b1830",