From ea56320e108b2b951fbd5c1c523e5a069b00f57f Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 1 Dec 2026 08:12:19 -0600 Subject: [PATCH] feat(board): add headless channels, fenced task queues, paperclipai/sdk, and pc CLI (#23330) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Multi-agent workflows and terminal scripts often need lightweight shared channels, structured task queues, and scriptable CLI/SDK primitives without building a full project UI first. > - Today, Paperclip issues require board-oriented setup, lack lazy hierarchical channels, lack fenced task claim leases, and lack a zero-dependency TypeScript SDK and short CLI alias for fast script coordination. > - Without fenced leases, blocking queue claims, CAS key-value labels, and race-free event streaming, multiple headless workers collide on shared work or fall back to wasteful polling loops. > - This pull request adds headless channels, versioned JSON schemas, topological `plan.json` batch creation, fenced task queues with `FOR UPDATE SKIP LOCKED` claims, CAS key-value labels, one-line ask/confirm interactions, SSE event streaming, `paperclipai/sdk`, and the `pc` CLI with `paperclipai up`. > - The benefit is zero-ceremony, machine-readable, race-safe coordination across terminal agents, CI scripts, and local Paperclip servers while staying compatible with existing Web UI issue threads. ## Linked Issues or Issue Description **Subsystem affected** Cross-cutting (`packages/db`, `packages/shared`, `server/`, `cli/`, `doc/`, `skills/`) **Problem or motivation** Agents and terminal workflows need a fast way to post updates, queue DAG tasks, claim work without double-execution, ask humans for approval, and wait on board events without browser setup or polling loops. Existing Paperclip routes assume UI-driven projects, lack fenced claim leases for pools of workers, and lack a minimal `pc` CLI and `paperclipai/sdk` client. **Proposed solution** Build a headless coordination layer directly on top of Paperclip `issues` and `issue_comments` using `issues.scope = 'channel'`: - **Database & Contracts (`packages/db`, `packages/shared`)**: Add `0511_pale_kronos.sql` (`issues.scope`) and `0512_stormy_the_hood.sql` for lazy hierarchical `channels`, `channel_access_members`, immutable `company_schemas`, monotonic `board_events`, `scheduled_board_posts`, `issue_batch_idempotency_keys`, scoped `board_api_keys`, `agent_identity_policy`, `kv_labels`, `schema_blocks`, and fenced claim leases. Export Zod contracts, DAG sorting, KV CAS helpers, and the zero-dependency `paperclip()` SDK (`packages/shared/src/sdk/`), including an in-memory test backend. - **Server APIs & Workers (`server/`)**: Add routes and services for progressive `--as` actor resolution (`open_local_profiles`, `delegated_profiles`, `strict_agent_keys`), `pc agent connect` auth challenges, lazy channels, CAS `kv-labels`, versioned schemas, topological batch creation, `FOR UPDATE SKIP LOCKED` pool claims with fenced TTL renewal/release/complete/fail, one-line `ask`/`confirm`/`approve`/`reject` interactions, SSE cursor streaming (`events/wait`, `events/stream`), and sleep-aware lease expiry and scheduled post workers. - **CLI, Launcher & Docs (`cli/`, `doc/`, `skills/`)**: Expose the `pc` binary alias and `paperclipai/sdk` export, add the zero-prompt `paperclipai up` / `pc up` local launcher, add `pc` commands (`post`, `reply`, `read`, `channels`, `label`, `tasks`, `ask`, `confirm`, `approve`, `reject`, `schemas`, `schedule`, `tail`, `wait`, `agent connect/login`), add documentation (`doc/CHANNELS-AND-QUEUES.md`, `doc/CLI.md`, `doc/HEADLESS-TUTORIALS.md`), and add `skills/paperclip-lite/SKILL.md`. **Alternatives considered** - **Separate message and queue tables outside `issues`**: Rejected because channel posts and queued tasks would lose Paperclip identifiers (`PC-1`), comments, attachments, privacy ACLs, and direct Web UI issue URLs (`//issues/PC-1`). - **Advisory locks or polling loops for task workers**: Rejected because advisory locks drop on reconnect across laptop sleep, and polling wastes tokens and prevents database sleep. Fenced `(claimToken, claimEpoch)` TTL leases with `events/wait` and `waitSec` solve both safely. **Roadmap alignment** Extends core Paperclip agent orchestration and CLI workflows with a headless board, SDK, and queue primitive without altering existing Web UI board behavior. **Additional context** This PR builds on the `issues.scope` surface visibility foundation from #23329 (included as the base commit in this stacked branch so CI and reviewers can test the full integration against `master`). ## What Changed - **Schema & Migrations (`packages/db`)**: Added online-compatible migrations `0511_pale_kronos.sql` and `0512_stormy_the_hood.sql`, schema definitions (`channels.ts`, `company_schemas.ts`, `headless_board.ts`), and column extensions on `issues`, `issue_comments`, `companies`, `board_api_keys`, and `cli_auth_challenges`. - **Shared Contracts & SDK (`packages/shared`)**: Added `packages/shared/src/headless/*` (channels, events, identity, labels, leases, DAG plans, schemas) and `packages/shared/src/sdk/*` (`paperclip()` client, env loader, SSE parser, and in-memory backend). - **Server Routes & Services (`server/`)**: Added `headless-channels-schemas.ts`, `headless-queues-events.ts`, `headless-identity.ts` routes and supporting services (`headless-channels.ts`, `headless-common.ts`, `headless-events-schedules-interactions.ts`, `headless-identity.ts`, `headless-labels-batch.ts`, `headless-schemas.ts`, `headless-task-queue.ts`), plus `issues.scope` visibility isolation and `board-auth.ts` extensions. - **CLI & SDK Export (`cli/`, `scripts/`)**: Exposed `pc` bin alias and `paperclipai/sdk` entrypoint, added `up.ts` zero-prompt launcher and `cli/src/commands/board/*` commands (`post`, `reply`, `read`, `channels`, `label`, `tasks`, `ask`, `confirm`, `approve`, `reject`, `schemas`, `schedule`, `tail`, `wait`, `agent`). - **Docs, Skill & Runner Registry (`doc/`, `skills/`, `tests/runner-e2e/`)**: Added `doc/CHANNELS-AND-QUEUES.md`, `doc/CLI.md`, `doc/HEADLESS-TUTORIALS.md`, plan docs, `skills/paperclip-lite/SKILL.md`, and synchronized `tests/runner-e2e/source-sdk-public-inputs.json`. ## Verification - `pnpm --filter @paperclipai/shared build` — passed. - `pnpm --filter @paperclipai/db check:migrations` — passed (`0511_pale_kronos.sql` and `0512_stormy_the_hood.sql` verified online-compatible, 2 new migrations since `630cf0423024`, none blocked). - `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse HEAD) --check` — passed (`598` inputs, `changed: false`). - `pnpm exec vitest run --config tests/runner-e2e/vitest.config.ts tests/runner-e2e/source-sdk-public-inputs.test.mjs` — 13/13 tests passed. - `node scripts/check-maps.mjs` — passed (`35` areas, `192` capability IDs aligned). - `pnpm exec vitest run packages/shared/src/headless/headless.test.ts packages/shared/src/sdk/sdk.test.ts cli/src/__tests__/headless-board-cli.test.ts` — 3 files, 22/22 tests passed. - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/issue-scope-visibility.test.ts src/__tests__/headless-channels-schemas-batch.test.ts src/__tests__/headless-identity-auth.test.ts src/__tests__/headless-queues-leases-events.test.ts src/__tests__/headless-e2e-sdk-cli.test.ts` — 5 files, 25/25 tests passed. - `pnpm --filter @paperclipai/shared typecheck && pnpm --filter @paperclipai/db typecheck && pnpm --filter @paperclipai/server typecheck && pnpm --filter paperclipai typecheck` — all passed. - `pnpm --filter paperclipai build` — passed. ## Risks - **Two new migrations (`0511`, `0512`)**: Both migrations are marked online-compatible (`NOT VALID` constraints validated afterwards, `CONCURRENTLY` index creation, idempotent statements for non-transactional execution) and checked by `check:migrations`. If #23329 lands separately with `0511` modified or renumbered, this branch will rebase on top cleanly. - **Large surface area (91 files)**: Changes are primarily additive new modules (`headless-*`, `cli/src/commands/board/*`, `packages/shared/src/headless/*`, `packages/shared/src/sdk/*`); existing Web UI board behavior remains isolated via `issues.scope`. - **Full repository Vitest suite**: Only the targeted headless, SDK, CLI, server, and runner-e2e pin suites ran locally after rebasing; full cross-package CI checks will validate the remaining suite. ## Model Used - Google DeepMind Antigravity (Gemini coding agent) with tool use and code execution ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- cli/esbuild.config.mjs | 34 +- cli/package.json | 13 +- cli/src/__tests__/headless-board-cli.test.ts | 1101 +++++++ cli/src/commands/board/agent-auth.ts | 491 ++++ cli/src/commands/board/channels.ts | 582 ++++ cli/src/commands/board/client.ts | 493 ++++ cli/src/commands/board/events.ts | 305 ++ cli/src/commands/board/index.ts | 14 + cli/src/commands/board/interactions.ts | 199 ++ cli/src/commands/board/schemas.ts | 132 + cli/src/commands/board/store.ts | 283 ++ cli/src/commands/board/tasks.ts | 1205 ++++++++ cli/src/commands/client/access.ts | 29 +- cli/src/commands/client/agent.ts | 2 + cli/src/commands/up.ts | 391 +++ cli/src/config/data-dir.ts | 5 +- cli/src/index.ts | 28 +- cli/src/sdk.ts | 1 + doc/CHANNELS-AND-QUEUES.md | 161 ++ doc/CLI.md | 140 + doc/HEADLESS-TUTORIALS.md | 279 ++ ...26-11-30-headless-paperclip-master-plan.md | 429 +++ .../2026-11-30-issue-scope-and-channels.md | 223 ++ ...026-11-30-queues-leases-and-concurrency.md | 250 ++ docs/api/authentication.md | 14 +- docs/api/headless.md | 135 + docs/api/overview.md | 6 + packages/db/src/client.ts | 1 + .../src/migrations/0512_stormy_the_hood.sql | 168 ++ ...{0507_snapshot.json => 0512_snapshot.json} | 1629 ++++++++++- packages/db/src/migrations/meta/_journal.json | 9 +- packages/db/src/schema/agent_api_keys.ts | 1 + packages/db/src/schema/board_api_keys.ts | 8 +- packages/db/src/schema/channels.ts | 106 + packages/db/src/schema/cli_auth_challenges.ts | 5 + packages/db/src/schema/companies.ts | 10 +- packages/db/src/schema/company_schemas.ts | 46 + packages/db/src/schema/headless_board.ts | 150 + packages/db/src/schema/index.ts | 3 + packages/db/src/schema/issue_comments.ts | 7 +- packages/db/src/schema/issues.ts | 44 +- packages/shared/package.json | 10 + packages/shared/src/headless/channels.ts | 114 + packages/shared/src/headless/events.ts | 48 + packages/shared/src/headless/headless.test.ts | 323 +++ packages/shared/src/headless/identity.ts | 46 + packages/shared/src/headless/index.ts | 7 + packages/shared/src/headless/labels.ts | 183 ++ packages/shared/src/headless/leases.ts | 268 ++ packages/shared/src/headless/plans.ts | 305 ++ packages/shared/src/headless/pure.ts | 150 + packages/shared/src/headless/schemas.ts | 603 ++++ packages/shared/src/index.ts | 1 + packages/shared/src/sdk/client.ts | 1006 +++++++ packages/shared/src/sdk/env.ts | 348 +++ packages/shared/src/sdk/index.ts | 23 + packages/shared/src/sdk/lite.ts | 73 + packages/shared/src/sdk/memory-backend.ts | 2529 +++++++++++++++++ packages/shared/src/sdk/sdk.test.ts | 732 +++++ packages/shared/src/sdk/sse.ts | 83 + packages/shared/src/sdk/types.ts | 275 ++ scripts/build-npm.sh | 7 +- scripts/generate-npm-package-json.mjs | 1 + .../company-skills-list-statements.test.ts | 2 +- .../fixtures/issue-detail-response.json | 13 + .../headless-channels-schemas-batch.test.ts | 1152 ++++++++ .../__tests__/headless-e2e-sdk-cli.test.ts | 506 ++++ .../__tests__/headless-identity-auth.test.ts | 1290 +++++++++ .../headless-queues-leases-events.test.ts | 1565 ++++++++++ server/src/__tests__/openapi-routes.test.ts | 3 + server/src/adapters/registry.ts | 32 +- server/src/app.ts | 13 + server/src/middleware/auth.ts | 23 +- server/src/modules/agent-lifecycle/index.ts | 39 + server/src/routes/access.ts | 235 +- server/src/routes/agents.ts | 11 + server/src/routes/authz.ts | 19 + .../src/routes/headless-channels-schemas.ts | 1430 ++++++++++ server/src/routes/headless-identity.ts | 68 + server/src/routes/headless-queues-events.ts | 599 ++++ server/src/routes/openapi.ts | 52 + server/src/services/agent-lifecycle.ts | 7 + server/src/services/authorization.ts | 31 +- server/src/services/board-auth.ts | 241 +- .../services/delivery-work-notifications.ts | 2 + server/src/services/headless-channels.ts | 1363 +++++++++ server/src/services/headless-common.ts | 1208 ++++++++ .../headless-events-schedules-interactions.ts | 2456 ++++++++++++++++ server/src/services/headless-identity.ts | 587 ++++ server/src/services/headless-labels-batch.ts | 663 +++++ server/src/services/headless-schemas.ts | 454 +++ server/src/services/headless-task-queue.ts | 1865 ++++++++++++ server/src/services/issue-comment-writes.ts | 5 +- .../src/services/issue-thread-interactions.ts | 296 +- server/src/services/issue-visibility.ts | 38 +- server/src/services/issues.ts | 27 +- server/src/services/recovery/service.ts | 11 + server/src/types/express.d.ts | 6 +- skills/paperclip-lite/SKILL.md | 94 + .../runner-e2e/source-sdk-public-inputs.json | 22 +- 100 files changed, 32616 insertions(+), 79 deletions(-) create mode 100644 cli/src/__tests__/headless-board-cli.test.ts create mode 100644 cli/src/commands/board/agent-auth.ts create mode 100644 cli/src/commands/board/channels.ts create mode 100644 cli/src/commands/board/client.ts create mode 100644 cli/src/commands/board/events.ts create mode 100644 cli/src/commands/board/index.ts create mode 100644 cli/src/commands/board/interactions.ts create mode 100644 cli/src/commands/board/schemas.ts create mode 100644 cli/src/commands/board/store.ts create mode 100644 cli/src/commands/board/tasks.ts create mode 100644 cli/src/commands/up.ts create mode 100644 cli/src/sdk.ts create mode 100644 doc/CHANNELS-AND-QUEUES.md create mode 100644 doc/HEADLESS-TUTORIALS.md create mode 100644 doc/plans/2026-11-30-headless-paperclip-master-plan.md create mode 100644 doc/plans/2026-11-30-issue-scope-and-channels.md create mode 100644 doc/plans/2026-11-30-queues-leases-and-concurrency.md create mode 100644 docs/api/headless.md create mode 100644 packages/db/src/migrations/0512_stormy_the_hood.sql rename packages/db/src/migrations/meta/{0507_snapshot.json => 0512_snapshot.json} (97%) create mode 100644 packages/db/src/schema/channels.ts create mode 100644 packages/db/src/schema/company_schemas.ts create mode 100644 packages/db/src/schema/headless_board.ts create mode 100644 packages/shared/src/headless/channels.ts create mode 100644 packages/shared/src/headless/events.ts create mode 100644 packages/shared/src/headless/headless.test.ts create mode 100644 packages/shared/src/headless/identity.ts create mode 100644 packages/shared/src/headless/index.ts create mode 100644 packages/shared/src/headless/labels.ts create mode 100644 packages/shared/src/headless/leases.ts create mode 100644 packages/shared/src/headless/plans.ts create mode 100644 packages/shared/src/headless/pure.ts create mode 100644 packages/shared/src/headless/schemas.ts create mode 100644 packages/shared/src/sdk/client.ts create mode 100644 packages/shared/src/sdk/env.ts create mode 100644 packages/shared/src/sdk/index.ts create mode 100644 packages/shared/src/sdk/lite.ts create mode 100644 packages/shared/src/sdk/memory-backend.ts create mode 100644 packages/shared/src/sdk/sdk.test.ts create mode 100644 packages/shared/src/sdk/sse.ts create mode 100644 packages/shared/src/sdk/types.ts create mode 100644 server/src/__tests__/headless-channels-schemas-batch.test.ts create mode 100644 server/src/__tests__/headless-e2e-sdk-cli.test.ts create mode 100644 server/src/__tests__/headless-identity-auth.test.ts create mode 100644 server/src/__tests__/headless-queues-leases-events.test.ts create mode 100644 server/src/routes/headless-channels-schemas.ts create mode 100644 server/src/routes/headless-identity.ts create mode 100644 server/src/routes/headless-queues-events.ts create mode 100644 server/src/services/headless-channels.ts create mode 100644 server/src/services/headless-common.ts create mode 100644 server/src/services/headless-events-schedules-interactions.ts create mode 100644 server/src/services/headless-identity.ts create mode 100644 server/src/services/headless-labels-batch.ts create mode 100644 server/src/services/headless-schemas.ts create mode 100644 server/src/services/headless-task-queue.ts create mode 100644 skills/paperclip-lite/SKILL.md diff --git a/cli/esbuild.config.mjs b/cli/esbuild.config.mjs index fee12f51fbc..b7e55f5d598 100644 --- a/cli/esbuild.config.mjs +++ b/cli/esbuild.config.mjs @@ -5,7 +5,7 @@ * External npm packages remain as regular dependencies. */ -import { readFileSync } from "node:fs"; +import { cpSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; import { createRequire } from "node:module"; import { resolve, dirname } from "node:path"; import { fileURLToPath } from "node:url"; @@ -65,14 +65,42 @@ if (bundledCliNpmDependencies.has("embedded-postgres")) { } } +export function emitSdkTypes() { + const sharedDist = resolve(repoRoot, "packages/shared/dist"); + const cliDist = resolve(__dirname, "dist"); + const sdkTypesDir = resolve(cliDist, "sdk-types"); + rmSync(sdkTypesDir, { recursive: true, force: true }); + mkdirSync(resolve(sdkTypesDir, "headless"), { recursive: true }); + mkdirSync(resolve(sdkTypesDir, "sdk"), { recursive: true }); + + cpSync(resolve(sharedDist, "constants.d.ts"), resolve(sdkTypesDir, "constants.d.ts")); + cpSync(resolve(sharedDist, "headless"), resolve(sdkTypesDir, "headless"), { + recursive: true, + filter: (src) => + statSync(src).isDirectory() || + (src.endsWith(".d.ts") && !src.endsWith(".test.d.ts")), + }); + for (const name of ["client.d.ts", "env.d.ts", "lite.d.ts", "sse.d.ts", "types.d.ts"]) { + cpSync(resolve(sharedDist, "sdk", name), resolve(sdkTypesDir, "sdk", name)); + } + writeFileSync( + resolve(cliDist, "sdk.d.ts"), + 'export * from "./sdk-types/sdk/lite.js";\n', + "utf8", + ); +} + /** @type {import('esbuild').BuildOptions} */ export default { - entryPoints: ["src/index.ts"], + entryPoints: { + index: "src/index.ts", + sdk: "src/sdk.ts", + }, bundle: true, platform: "node", target: "node24", format: "esm", - outfile: "dist/index.js", + outdir: "dist", banner: { js: "#!/usr/bin/env node" }, external: [...externals].sort(), treeShaking: true, diff --git a/cli/package.json b/cli/package.json index b623ca5a898..b23af92fbdb 100644 --- a/cli/package.json +++ b/cli/package.json @@ -4,7 +4,16 @@ "description": "Paperclip CLI — orchestrate AI agent teams to run a business", "type": "module", "bin": { - "paperclipai": "./dist/index.js" + "paperclipai": "./dist/index.js", + "pc": "./dist/index.js" + }, + "exports": { + ".": "./dist/index.js", + "./sdk": { + "types": "./dist/sdk.d.ts", + "import": "./dist/sdk.js", + "default": "./dist/sdk.js" + } }, "keywords": [ "paperclip", @@ -31,7 +40,7 @@ }, "scripts": { "dev": "tsx src/index.ts", - "build": "node --input-type=module -e \"import esbuild from 'esbuild'; import config from './esbuild.config.mjs'; await esbuild.build(config);\" && chmod +x dist/index.js", + "build": "node --input-type=module -e \"import esbuild from 'esbuild'; import config, { emitSdkTypes } from './esbuild.config.mjs'; await esbuild.build(config); emitSdkTypes();\" && chmod +x dist/index.js", "clean": "rm -rf dist", "typecheck": "tsc --noEmit" }, diff --git a/cli/src/__tests__/headless-board-cli.test.ts b/cli/src/__tests__/headless-board-cli.test.ts new file mode 100644 index 00000000000..0d512585dff --- /dev/null +++ b/cli/src/__tests__/headless-board-cli.test.ts @@ -0,0 +1,1101 @@ +import fs from "node:fs"; +import http from "node:http"; +import os from "node:os"; +import path from "node:path"; +import { execFileSync } from "node:child_process"; +import { Command } from "commander"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + createInMemoryPaperclipBackend, + type InMemoryPaperclipBackend, +} from "@paperclipai/shared/sdk"; +import { readContext } from "../client/context.js"; +import { registerAccessCommands } from "../commands/client/access.js"; +import { registerAgentCommands } from "../commands/client/agent.js"; +import { registerPromptCommands } from "../commands/client/prompt.js"; +import { registerBoardCommands } from "../commands/board/index.js"; +import { readRepoLocalBoardConfig, resolveBoardClient } from "../commands/board/client.js"; +import { + deleteClaimRecord, + findClaimRecord, + readProfileRecord, + resolveClaimFilePath, +} from "../commands/board/store.js"; +import { applyDataDirOverride, type DataDirOptionLike } from "../config/data-dir.js"; +import { + bootstrapUpBoard, + checkLocalGitignore, + deriveCompanyIssuePrefix, + formatUpReadyBanner, + prepareUpEnvironment, + registerUpCommand, + upCommand, + type UpOptions, +} from "../commands/up.js"; + +class ExitSignal extends Error { + constructor(readonly code: number) { + super(`process.exit(${code})`); + } +} + +async function startBackendServer(backend: InMemoryPaperclipBackend): Promise<{ + apiBase: string; + close: () => Promise; +}> { + const server = http.createServer(async (req, res) => { + try { + const origin = `http://${req.headers.host ?? "127.0.0.1"}`; + const url = new URL(req.url ?? "/", origin); + const chunks: Buffer[] = []; + for await (const chunk of req) { + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); + } + const rawBody = Buffer.concat(chunks); + const headers = new Headers(); + for (const [k, v] of Object.entries(req.headers)) { + if (Array.isArray(v)) { + for (const item of v) headers.append(k, item); + } else if (typeof v === "string") { + headers.set(k, v); + } + } + + const ac = new AbortController(); + req.once("close", () => ac.abort()); + + const response = await backend.fetch(url.toString(), { + method: req.method, + headers, + body: + req.method !== "GET" && req.method !== "HEAD" && rawBody.length > 0 + ? rawBody.toString("utf8") + : undefined, + signal: ac.signal, + }); + + res.statusCode = response.status; + response.headers.forEach((value, key) => { + res.setHeader(key, value); + }); + + if (!response.body) { + res.end(); + return; + } + + const reader = response.body.getReader(); + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + if (value) { + res.write(Buffer.from(value)); + } + } + } catch { + // Stream closed or aborted + } finally { + res.end(); + } + } catch (err) { + res.statusCode = 500; + res.setHeader("content-type", "application/json"); + res.end( + JSON.stringify({ + error: "server_error", + message: err instanceof Error ? err.message : String(err), + }), + ); + } + }); + + await new Promise((resolve) => { + server.listen(0, "127.0.0.1", resolve); + }); + const addr = server.address() as { port: number }; + return { + apiBase: `http://127.0.0.1:${addr.port}`, + close: () => + new Promise((resolve, reject) => { + server.close((err) => (err ? reject(err) : resolve())); + }), + }; +} + +function buildTestProgram(): Command { + const program = new Command(); + program.enablePositionalOptions(); + program.exitOverride(); + program.configureOutput({ writeOut: () => {}, writeErr: () => {} }); + registerAgentCommands(program); + registerPromptCommands(program); + registerAccessCommands(program); + registerBoardCommands(program); + return program; +} + +describe("headless board CLI (pc)", () => { + const originalEnv = { ...process.env }; + const cleanupDirs: string[] = []; + let backend: InMemoryPaperclipBackend; + let server: { apiBase: string; close: () => Promise }; + let homeDir: string; + let logs: string[]; + let errs: string[]; + + beforeEach(async () => { + process.env = { ...originalEnv }; + delete process.env.PAPERCLIP_API_URL; + delete process.env.PAPERCLIP_API_KEY; + delete process.env.PAPERCLIP_COMPANY_ID; + delete process.env.PAPERCLIP_PROFILE; + delete process.env.PAPERCLIP_CLI_PERSONA; + delete process.env.PAPERCLIP_CLAIM_TOKEN; + delete process.env.PAPERCLIP_CLAIM_EPOCH; + delete process.env.PAPERCLIP_TASK_ID; + delete process.env.PAPERCLIP_ISSUE_UUID; + + homeDir = fs.mkdtempSync(path.join(os.tmpdir(), "paperclip-board-cli-")); + cleanupDirs.push(homeDir); + process.env.PAPERCLIP_HOME = homeDir; + process.env.PAPERCLIP_CONTEXT = path.join(homeDir, "context.json"); + + backend = createInMemoryPaperclipBackend({ companyPrefix: "PAP" }); + server = await startBackendServer(backend); + + logs = []; + errs = []; + vi.spyOn(console, "log").mockImplementation((...args) => { + logs.push(args.map(String).join(" ")); + }); + vi.spyOn(console, "error").mockImplementation((...args) => { + errs.push(args.map(String).join(" ")); + }); + vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new ExitSignal(code ?? 0); + }) as never); + }); + + afterEach(async () => { + vi.restoreAllMocks(); + process.env = { ...originalEnv }; + await server.close(); + while (cleanupDirs.length > 0) { + fs.rmSync(cleanupDirs.pop()!, { recursive: true, force: true }); + } + }); + + async function runCli(args: string[], opts: { includeApiBase?: boolean } = {}): Promise<{ + exitCode: number; + stdout: string[]; + stderr: string[]; + }> { + logs = []; + errs = []; + const program = buildTestProgram(); + let finalArgs = args; + if (opts.includeApiBase !== false) { + const dashIdx = args.indexOf("--"); + finalArgs = + dashIdx === -1 + ? [...args, "--api-base", server.apiBase] + : [...args.slice(0, dashIdx), "--api-base", server.apiBase, ...args.slice(dashIdx)]; + } + try { + await program.parseAsync(finalArgs, { from: "user" }); + return { exitCode: 0, stdout: [...logs], stderr: [...errs] }; + } catch (err) { + if (err instanceof ExitSignal) { + return { exitCode: err.code, stdout: [...logs], stderr: [...errs] }; + } + throw err; + } + } + + it("supports post, passive read without [backlog], reply --after guard, and CAS label --if", async () => { + const postRes = await runCli(["post", "deploys/prod", "Rolled out v1.2.0", "--as", "lead"]); + expect(postRes.exitCode).toBe(0); + expect(postRes.stdout).toEqual(["PAP-1"]); + + const readRes = await runCli(["read", "deploys/prod"]); + expect(readRes.exitCode).toBe(0); + const readText = readRes.stdout.join("\n"); + expect(readText).toContain("PAP-1"); + expect(readText).not.toContain("[backlog]"); + + const r1 = await runCli(["reply", "PAP-1", "Smoke green", "--as", "qa"]); + expect(r1.exitCode).toBe(0); + const commentId1 = r1.stdout[0]!; + expect(commentId1.length).toBeGreaterThan(10); + + const r2 = await runCli([ + "reply", + "PAP-1", + "Following up", + "--after", + commentId1, + "--as", + "qa", + ]); + expect(r2.exitCode).toBe(0); + + // Stale --after returns 409 newer_message + const stale = await runCli([ + "reply", + "PAP-1", + "Stale", + "--after", + commentId1, + "--json", + ]); + expect(stale.exitCode).toBe(1); + expect(JSON.parse(stale.stderr[0]!)).toMatchObject({ + error: "newer_message", + }); + + // CAS labels + const l1 = await runCli(["label", "PAP-1", "stage=new"]); + expect(l1.exitCode).toBe(0); + + const l2 = await runCli([ + "label", + "PAP-1", + "stage=investigating", + "owner=worker-1", + "--if", + "stage=new", + "--if-unset", + "owner", + "--json", + ]); + expect(l2.exitCode).toBe(0); + expect(JSON.parse(l2.stdout.join("\n"))).toMatchObject({ + kvLabels: { stage: "investigating", owner: "worker-1" }, + }); + + const conflict = await runCli([ + "label", + "PAP-1", + "stage=investigating", + "owner=worker-2", + "--if", + "stage=new", + "--json", + ]); + expect(conflict.exitCode).toBe(1); + expect(JSON.parse(conflict.stderr[0]!)).toMatchObject({ + error: "label_conflict", + }); + }); + + it("handles channels routing, board channels, and whoami --as without breaking legacy whoami", async () => { + const chCreate = await runCli(["channels", "create", "build/auth", "--description", "Auth CI"]); + expect(chCreate.exitCode).toBe(0); + + const chList = await runCli(["channels", "--prefix", "build/", "--json"]); + expect(chList.exitCode).toBe(0); + expect(JSON.parse(chList.stdout.join("\n")).map((c: { path: string }) => c.path)).toEqual([ + "build/auth", + ]); + + const boardCh = await runCli(["board", "channels", "--json"]); + expect(boardCh.exitCode).toBe(0); + expect(JSON.parse(boardCh.stdout.join("\n")).map((c: { path: string }) => c.path)).toEqual([ + "build/auth", + ]); + + const who = await runCli(["whoami", "--as", "worker-1", "--company", "PAP", "--json"]); + expect(who.exitCode).toBe(0); + expect(JSON.parse(who.stdout.join("\n"))).toMatchObject({ + companyPrefix: "PAP", + actorProfile: "worker-1", + principalType: "local_trusted", + }); + }); + + it("creates plan.json DAGs, claims --ready, enforces profile claim_not_held, and validates resultSchema", async () => { + const web = backend.seedProject({ slug: "web-app", name: "Web App" }); + const planPath = path.join(homeDir, "plan.json"); + fs.writeFileSync( + planPath, + JSON.stringify({ + projectId: "web-app", + idempotencyKey: "auth-dag-1", + tasks: [ + { + key: "review", + title: "Review auth patch", + needs: ["patch"], + labels: { role: "reviewer" }, + resultSchema: "finding@1", + }, + { + key: "patch", + title: "Patch token check", + labels: { role: "worker" }, + }, + ], + }), + ); + + const createRes = await runCli([ + "tasks", + "create", + "build/auth", + "--file", + planPath, + "--json", + ]); + expect(createRes.exitCode).toBe(0); + const created = JSON.parse(createRes.stdout.join("\n")) as { + tasks: Array<{ key: string; identifier: string; issue: { id: string; projectId: string } }>; + }; + expect(created.tasks.map((t) => t.key)).toEqual(["patch", "review"]); + const patchTask = created.tasks.find((t) => t.key === "patch")!; + const reviewTask = created.tasks.find((t) => t.key === "review")!; + expect(patchTask.issue.projectId).toBe(web.id); + + // Reviewer cannot claim blocked review yet + const blockedClaim = await runCli([ + "tasks", + "claim", + "--ready", + "build/auth", + "--label", + "role=reviewer", + "--json", + ]); + expect(blockedClaim.exitCode).toBe(1); + + // Worker 1 claims patch + const w1Claim = await runCli([ + "tasks", + "claim", + "--ready", + "build/auth", + "--label", + "role=worker", + "--as", + "worker-1", + "--json", + ]); + expect(w1Claim.exitCode).toBe(0); + const claimJson = JSON.parse(w1Claim.stdout.join("\n")); + expect(claimJson.issue.identifier).toBe(patchTask.identifier); + + // Claim stored locally with 0600 permissions + const storedClaim = findClaimRecord(backend.companyId, patchTask.identifier); + expect(storedClaim?.profile).toBe("worker-1"); + const claimFileMode = + fs.statSync(resolveClaimFilePath(backend.companyId, patchTask.issue.id)).mode & 0o777; + expect(claimFileMode).toBe(0o600); + + // Worker 2 cannot settle worker 1's local claim + const wrongProfile = await runCli([ + "tasks", + "complete", + patchTask.identifier, + "Hijack", + "--as", + "worker-2", + "--json", + ]); + expect(wrongProfile.exitCode).toBe(1); + expect(JSON.parse(wrongProfile.stderr[0]!)).toMatchObject({ + error: "claim_not_held", + }); + + // Worker 1 renews and completes + const renewRes = await runCli([ + "tasks", + "renew", + patchTask.identifier, + "--lease", + "2m", + "--as", + "worker-1", + ]); + expect(renewRes.exitCode).toBe(0); + + const completeRes = await runCli([ + "tasks", + "complete", + patchTask.identifier, + "Patched", + "--as", + "worker-1", + ]); + expect(completeRes.exitCode).toBe(0); + expect(findClaimRecord(backend.companyId, patchTask.identifier)).toBeNull(); + + // Now review is unblocked and claimable + const revClaim = await runCli([ + "tasks", + "claim", + "--ready", + "build/auth", + "--label", + "role=reviewer", + "--as", + "reviewer-1", + "--json", + ]); + expect(revClaim.exitCode).toBe(0); + expect(JSON.parse(revClaim.stdout.join("\n")).issue.identifier).toBe(reviewTask.identifier); + + // Completing review without resultSchema data fails with 422 + const badComplete = await runCli([ + "tasks", + "complete", + reviewTask.identifier, + "No data", + "--as", + "reviewer-1", + "--json", + ]); + expect(badComplete.exitCode).toBe(1); + expect(JSON.parse(badComplete.stderr[0]!)).toMatchObject({ + error: "missing_or_invalid_result_schema", + }); + + // Supplying valid --data completes review + const okComplete = await runCli([ + "tasks", + "complete", + reviewTask.identifier, + "Looks safe", + "--data", + '{"severity":"info","title":"Clean"}', + "--as", + "reviewer-1", + ]); + expect(okComplete.exitCode).toBe(0); + }); + + it("runs tasks via pc tasks run -- with env injection, exit settlement, and claim_lost termination", async () => { + // 1. Happy path with PAPERCLIP_* env verification (including PAPERCLIP_API_KEY) + backend.seedBoardToken({ token: "brd_run_secret", userId: "user-run" }); + const t1 = await runCli(["tasks", "create", "build/run", "Verify env injection", "--json"]); + expect(t1.exitCode).toBe(0); + const id1 = (JSON.parse(t1.stdout.join("\n")) as { identifier: string }).identifier; + + const envCheckScript = [ + "const req = ['PAPERCLIP_TASK_ID','PAPERCLIP_ISSUE_UUID','PAPERCLIP_CLAIM_TOKEN','PAPERCLIP_CLAIM_EPOCH','PAPERCLIP_API_URL','PAPERCLIP_COMPANY_ID','PAPERCLIP_PROFILE','PAPERCLIP_API_KEY'];", + "for (const k of req) { if (!process.env[k]) { console.error('missing ' + k); process.exit(2); } }", + `if (process.env.PAPERCLIP_TASK_ID !== ${JSON.stringify(id1)}) process.exit(3);`, + "if (process.env.PAPERCLIP_PROFILE !== 'runner-1') process.exit(4);", + "if (process.env.PAPERCLIP_API_KEY !== 'brd_run_secret') process.exit(5);", + ].join(" "); + + const runOk = await runCli([ + "tasks", + "run", + "--ready", + "build/run", + "--as", + "runner-1", + "--api-key", + "brd_run_secret", + "--result", + "Env verified", + "--", + process.execPath, + "-e", + envCheckScript, + ]); + expect(runOk.exitCode).toBe(0); + const issue1After = backend.getState().issues.find((i) => i.identifier === id1)!; + expect(issue1After.status).toBe("done"); + expect(findClaimRecord(backend.companyId, id1)).toBeNull(); + + // 2. Non-zero exit marks task blocked (or todo with --requeue-on-error) + const t2 = await runCli(["tasks", "create", "build/run", "Failing command", "--json"]); + const id2 = (JSON.parse(t2.stdout.join("\n")) as { identifier: string }).identifier; + const runFail = await runCli([ + "tasks", + "run", + id2, + "--as", + "runner-2", + "--requeue-on-error", + "--", + process.execPath, + "-e", + "process.exit(7)", + ]); + expect(runFail.exitCode).toBe(7); + expect(backend.getState().issues.find((i) => i.identifier === id2)!.status).toBe("todo"); + + // 3. Lease renewal 409 claim_lost terminates child and exits 1 (including external cancel) + const t3 = await runCli(["tasks", "create", "build/run", "Lost claim test", "--json"]); + const id3 = (JSON.parse(t3.stdout.join("\n")) as { identifier: string }).identifier; + + const timer = setTimeout(() => { + // Advance backend clock past the 1s lease so the next renew hits 409 claim_lost + backend.advanceTime(5_000); + }, 150); + + try { + const runLost = await runCli([ + "tasks", + "run", + id3, + "--lease", + "1s", + "--as", + "runner-3", + "--", + process.execPath, + "-e", + "setTimeout(() => {}, 15000)", + ]); + expect(runLost.exitCode).toBe(1); + } finally { + clearTimeout(timer); + deleteClaimRecord(backend.companyId, id3); + } + }); + + it("terminates pc tasks run child process on external cancel", async () => { + const t4 = await runCli(["tasks", "create", "build/run", "External cancel claim_lost test", "--json"]); + const id4 = (JSON.parse(t4.stdout.join("\n")) as { identifier: string }).identifier; + const cancelTimer = setTimeout(() => { + void backend.fetch(`http://127.0.0.1/api/issues/${encodeURIComponent(id4)}`, { + method: "PATCH", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ status: "cancelled" }), + }); + }, 150); + try { + const runCancelled = await runCli([ + "tasks", + "run", + id4, + "--lease", + "1s", + "--as", + "runner-4", + "--", + process.execPath, + "-e", + "setTimeout(() => {}, 15000)", + ]); + expect(runCancelled.exitCode).toBe(1); + } finally { + clearTimeout(cancelTimer); + deleteClaimRecord(backend.companyId, id4); + } + }, 10_000); + + it("supports ask/approve requeue, schemas, schedules, and wait cursor replay/timeout", async () => { + const t = await runCli(["tasks", "create", "db/migrations", "Drop old col", "--json"]); + const task = JSON.parse(t.stdout.join("\n")) as { identifier: string; cursor: string }; + + await runCli(["tasks", "claim", task.identifier, "--as", "worker-a"]); + const askRes = await runCli([ + "ask", + task.identifier, + "Which strategy?", + "--choice", + "blue,green", + "--human", + "--as", + "worker-a", + "--json", + ]); + expect(askRes.exitCode).toBe(0); + expect(JSON.parse(askRes.stdout.join("\n"))).toMatchObject({ + status: "pending", + continuationPolicy: "requeue_on_resolve", + }); + // Claim was released on ask + expect(findClaimRecord(backend.companyId, task.identifier)).toBeNull(); + + // Approve requeues to todo + const appRes = await runCli(["approve", task.identifier, "--note", "Use green", "--json"]); + expect(appRes.exitCode).toBe(0); + expect(backend.getState().issues.find((i) => i.identifier === task.identifier)!.status).toBe( + "todo", + ); + + // Schemas + const schemaPath = path.join(homeDir, "audit.schema.json"); + fs.writeFileSync( + schemaPath, + JSON.stringify({ type: "object", required: ["passed"], properties: { passed: { type: "boolean" } } }), + ); + const sCreate = await runCli(["schemas", "create", "audit-check@1", "--file", schemaPath]); + expect(sCreate.exitCode).toBe(0); + + const sPost = await runCli([ + "post", + "qa/audit", + "Audit complete", + "--schema", + "audit-check@1", + '{"passed":true}', + "--json", + ]); + expect(sPost.exitCode).toBe(0); + expect(JSON.parse(sPost.stdout.join("\n")).blocks[0]).toEqual({ + schema: "audit-check", + version: 1, + data: { passed: true }, + }); + + // Schedules + const sched = await runCli(["schedule", "qa/audit", "Recheck", "--in", "5m", "--post", "--json"]); + expect(sched.exitCode).toBe(0); + const schedId = (JSON.parse(sched.stdout.join("\n")) as { id: string }).id; + const schedList = await runCli(["schedules", "list", "--json"]); + expect(JSON.parse(schedList.stdout.join("\n"))).toHaveLength(1); + const schedCancel = await runCli(["schedules", "cancel", schedId, "--json"]); + expect(JSON.parse(schedCancel.stdout.join("\n"))).toEqual({ cancelled: true }); + + // Wait cursor replay + const waitReplay = await runCli([ + "wait", + task.identifier, + "--event", + "interaction.resolved", + "--after", + task.cursor, + "--timeout", + "1s", + "--json", + ]); + expect(waitReplay.exitCode).toBe(0); + expect(JSON.parse(waitReplay.stdout.join("\n")).type).toBe("interaction.resolved"); + + // Wait timeout exits 1 with { error: "timeout" } + const waitTimeout = await runCli([ + "wait", + task.identifier, + "--event", + "task.completed", + "--after", + "evt_99999", + "--timeout", + "50ms", + "--json", + ]); + expect(waitTimeout.exitCode).toBe(1); + expect(JSON.parse(waitTimeout.stderr[0]!)).toMatchObject({ error: "timeout" }); + }); + + it("writes 0600 agent profiles on agent connect and uses them for --as under strict_agent_keys", async () => { + // Seed backend with a board token and an agent-connect handler / fallback + backend.setPolicy("strict_agent_keys"); + backend.seedBoardToken({ token: "brd_admin", userId: "user-dotta" }); + const seeded = backend.seedAgent({ + name: "security-scanner", + role: "security", + apiKey: "pcp_scanner_key_123", + }); + + // Write profile using store or simulate agent connect via existing profile store + const { writeProfileRecord } = await import("../commands/board/store.js"); + const profilePath = writeProfileRecord("security-scanner", { + agentId: seeded.id, + agentName: seeded.name, + companyId: backend.companyId, + apiBase: server.apiBase, + apiKey: seeded.apiKey, + role: "security", + }); + expect(fs.statSync(profilePath).mode & 0o777).toBe(0o600); + expect(readProfileRecord("security-scanner")?.apiKey).toBe("pcp_scanner_key_123"); + + const who = await runCli(["whoami", "--as", "security-scanner", "--json"]); + expect(who.exitCode).toBe(0); + expect(JSON.parse(who.stdout.join("\n"))).toMatchObject({ + principalType: "agent", + agentId: seeded.id, + agentName: "security-scanner", + }); + }); + + it("boots local board via upCommand without LLM keys and writes context", async () => { + expect(deriveCompanyIssuePrefix("Acme Corp")).toBe("ACM"); + expect(deriveCompanyIssuePrefix("AI")).toBe("AIP"); + + const repoDir = fs.realpathSync( + fs.mkdtempSync(path.join(os.tmpdir(), "paperclip-up-local-")), + ); + cleanupDirs.push(repoDir); + execFileSync("git", ["init"], { cwd: repoDir, stdio: "ignore" }); + fs.writeFileSync(path.join(repoDir, ".gitignore"), "node_modules/\n"); + expect(checkLocalGitignore(repoDir).ignored).toBe(false); + + const prepared = await prepareUpEnvironment({ local: true }, repoDir); + expect(prepared.dataDir).toBe(path.join(repoDir, ".paperclip", "board")); + expect(prepared.gitignoreMissing).toBe(true); + + const createdCompanies: Array<{ name: string }> = []; + const ensuredChannels: string[] = []; + + await upCommand( + { local: true, companyName: "My Board" }, + { + run: async (opts) => { + await opts.afterStart?.({ + apiUrl: "http://127.0.0.1:3199/api", + databaseUrl: "postgres://embedded", + host: "127.0.0.1", + listenPort: 3199, + }); + }, + createApi: () => ({ + get: async () => [] as unknown as T, + post: async (_path: string, body?: unknown) => { + const payload = body as { name: string }; + createdCompanies.push(payload); + return { + id: "11111111-1111-4111-8111-111111111111", + name: payload.name, + issuePrefix: "MYB", + status: "active", + } as unknown as T; + }, + }), + ensureGeneralChannel: async (_apiBase, companyId) => { + ensuredChannels.push(`${companyId}:general`); + return null; + }, + updateContext: ({ apiBase, companyId, contextPath }) => { + const target = contextPath ?? path.join(repoDir, ".paperclip", "context.json"); + fs.mkdirSync(path.dirname(target), { recursive: true }); + fs.writeFileSync( + target, + JSON.stringify({ + version: 2, + currentProfile: "default", + profiles: { default: { apiBase, companyId } }, + }), + ); + return target; + }, + }, + repoDir, + ); + + expect(createdCompanies).toEqual([{ name: "My Board" }]); + expect(ensuredChannels).toEqual(["11111111-1111-4111-8111-111111111111:general"]); + const ctx = readContext(path.join(repoDir, ".paperclip", "context.json")); + expect(ctx.profiles.default?.apiBase).toBe("http://127.0.0.1:3199"); + expect(ctx.profiles.default?.companyId).toBe("11111111-1111-4111-8111-111111111111"); + + const output = logs.join("\n"); + expect(output).toContain( + "Paperclip ready at http://127.0.0.1:3199 (Company: My Board [MYB], mode: local_trusted)", + ); + + const banner = formatUpReadyBanner({ + url: "http://127.0.0.1:3100", + companyName: "Workspace", + issuePrefix: "WOR", + deploymentMode: "local_trusted", + dataDir: "/tmp/board", + contextUpdated: true, + contextPath: "/tmp/context.json", + companyId: "cid", + }); + expect(banner).toHaveLength(4); + + // Reusing existing company skips company creation + const reused = await bootstrapUpBoard({ + api: { + get: async () => + [{ id: "c1", name: "Existing", issuePrefix: "EXI", status: "active" }] as unknown as T, + post: async () => { + throw new Error("should not create company"); + }, + }, + apiBase: "http://127.0.0.1:3100", + companyName: "Ignored", + ensureGeneralChannel: async () => null, + }); + expect(reused.reused).toBe(true); + expect(reused.issuePrefix).toBe("EXI"); + }); + + it("handles Commander --no-context boolean option in preAction and upCommand via program.parseAsync", async () => { + const repoDir = fs.mkdtempSync(path.join(os.tmpdir(), "paperclip-up-parse-")); + execFileSync("git", ["init", "-q"], { cwd: repoDir }); + + const prevCwd = process.cwd(); + const prevHome = process.env.PAPERCLIP_HOME; + const prevConfig = process.env.PAPERCLIP_CONFIG; + const prevContext = process.env.PAPERCLIP_CONTEXT; + const prevInstance = process.env.PAPERCLIP_INSTANCE_ID; + const prevPort = process.env.PORT; + + const logs: string[] = []; + vi.spyOn(console, "log").mockImplementation((...args: unknown[]) => { + logs.push(args.map(String).join(" ")); + }); + + try { + process.chdir(repoDir); + const runWithArgs = async (argv: string[]) => { + delete process.env.PAPERCLIP_HOME; + delete process.env.PAPERCLIP_CONFIG; + delete process.env.PAPERCLIP_CONTEXT; + delete process.env.PAPERCLIP_INSTANCE_ID; + delete process.env.PORT; + + const updateContextCalls: Array<{ contextPath?: string }> = []; + const testProgram = new Command(); + testProgram.hook("preAction", async (_thisCommand, actionCommand) => { + const options = actionCommand.optsWithGlobals() as DataDirOptionLike & UpOptions; + const prepared = await prepareUpEnvironment(options, repoDir); + const dataDirOptions: DataDirOptionLike = { + ...options, + dataDir: prepared.dataDir, + context: typeof options.context === "string" ? options.context : undefined, + }; + applyDataDirOverride(dataDirOptions, { + hasConfigOption: true, + hasContextOption: true, + }); + }); + registerUpCommand(testProgram, { + run: async (opts) => { + await opts.afterStart?.({ + apiUrl: "http://127.0.0.1:3198/api", + databaseUrl: "postgres://embedded", + host: "127.0.0.1", + listenPort: 3198, + }); + }, + createApi: () => ({ + get: async () => + [{ id: "c1", name: "Local", issuePrefix: "LOC", status: "active" }] as unknown as T, + post: async () => ({} as T), + }), + ensureGeneralChannel: async () => null, + updateContext: (input) => { + updateContextCalls.push({ contextPath: input.contextPath }); + return input.contextPath ?? path.join(repoDir, ".paperclip", "context.json"); + }, + }); + await testProgram.parseAsync(argv); + return { + updateContextCalls, + paperclipContext: process.env.PAPERCLIP_CONTEXT, + }; + }; + + // Default (options.context === true from --no-context default): does not crash applyDataDirOverride and keeps .paperclip/context.json + const realRepoDir = fs.realpathSync(repoDir); + const defaultRes = await runWithArgs(["node", "pc", "up", "--local"]); + expect(path.dirname(defaultRes.paperclipContext!)).toBe( + path.join(realRepoDir, ".paperclip"), + ); + expect(defaultRes.updateContextCalls).toHaveLength(1); + + // Explicit --no-context (options.context === false): skips context update and does not crash preAction + logs.length = 0; + const noCtxRes = await runWithArgs(["node", "pc", "up", "--local", "--no-context"]); + expect(noCtxRes.updateContextCalls).toHaveLength(0); + expect(logs.join("\n")).toContain("Context: skipped (--no-context)"); + + // Repo-local .paperclip/context.json takes precedence over global PAPERCLIP_CONTEXT unless --context is passed + const globalCtxPath = path.join(repoDir, "global-context.json"); + fs.writeFileSync( + globalCtxPath, + JSON.stringify({ + version: 2, + currentProfile: "default", + profiles: { default: { apiBase: "http://127.0.0.1:4999", companyId: "global-co" } }, + }), + ); + const localCtxPath = path.join(repoDir, ".paperclip", "context.json"); + fs.mkdirSync(path.dirname(localCtxPath), { recursive: true }); + fs.writeFileSync( + localCtxPath, + JSON.stringify({ + version: 2, + currentProfile: "default", + profiles: { default: { apiBase: "http://127.0.0.1:3198", companyId: "local-co" } }, + }), + ); + process.env.PAPERCLIP_CONTEXT = globalCtxPath; + const repoCfg = readRepoLocalBoardConfig(repoDir); + expect(repoCfg).toEqual({ + apiBase: "http://127.0.0.1:3198", + companyId: "local-co", + source: "local_context", + }); + + const discovered = resolveBoardClient({}); + expect(discovered.apiBase).toBe("http://127.0.0.1:3198"); + expect(discovered.company).toBe("local-co"); + + const explicitCtx = resolveBoardClient({ context: globalCtxPath }); + expect(explicitCtx.apiBase).toBe("http://127.0.0.1:4999"); + expect(explicitCtx.company).toBe("global-co"); + } finally { + process.chdir(prevCwd); + if (prevHome === undefined) delete process.env.PAPERCLIP_HOME; + else process.env.PAPERCLIP_HOME = prevHome; + if (prevConfig === undefined) delete process.env.PAPERCLIP_CONFIG; + else process.env.PAPERCLIP_CONFIG = prevConfig; + if (prevContext === undefined) delete process.env.PAPERCLIP_CONTEXT; + else process.env.PAPERCLIP_CONTEXT = prevContext; + if (prevInstance === undefined) delete process.env.PAPERCLIP_INSTANCE_ID; + else process.env.PAPERCLIP_INSTANCE_ID = prevInstance; + if (prevPort === undefined) delete process.env.PORT; + else process.env.PORT = prevPort; + fs.rmSync(repoDir, { recursive: true, force: true }); + } + }); + + it("prefers --as profile key over PAPERCLIP_API_KEY, refuses ambient keys on untrusted .paperclip.json, and sends explicit requeue=false on pc tasks fail", async () => { + const repoDir = fs.mkdtempSync(path.join(os.tmpdir(), "paperclip-cli-sec-")); + const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), "paperclip-home-sec-")); + execFileSync("git", ["init", "-q"], { cwd: repoDir }); + + const backend = createInMemoryPaperclipBackend({ + agentIdentityPolicy: "delegated_profiles", + }); + backend.seedAgent({ name: "runner-bot", role: "engineer", apiKey: "pcp_runner_key" }); + backend.seedBoardToken({ token: "brd_ambient_secret", userId: "user-ambient" }); + const srv = await startBackendServer(backend); + + const prevCwd = process.cwd(); + const prevHome = process.env.PAPERCLIP_HOME; + const prevApiKey = process.env.PAPERCLIP_API_KEY; + const prevContext = process.env.PAPERCLIP_CONTEXT; + + try { + process.env.PAPERCLIP_HOME = homeDir; + process.env.PAPERCLIP_API_KEY = "brd_ambient_secret"; + const profileDir = path.join(homeDir, "profiles"); + fs.mkdirSync(profileDir, { recursive: true }); + fs.writeFileSync( + path.join(profileDir, "runner-bot.json"), + JSON.stringify({ agentApiKey: "pcp_runner_key" }), + ); + + // 1. With --as runner-bot, stored profile agent key takes precedence over PAPERCLIP_API_KEY + const asBot = resolveBoardClient({ + apiBase: srv.apiBase, + company: backend.companyId, + as: "runner-bot", + }); + expect(asBot.apiKey).toBe("pcp_runner_key"); + const who = await asBot.client.whoami(); + expect(who.principalType).toBe("agent"); + expect(who.agentName).toBe("runner-bot"); + + // 2. Untrusted repo-local .paperclip.json pointing to an unconfigured origin refuses sending ambient PAPERCLIP_API_KEY + delete process.env.PAPERCLIP_HOME; + process.chdir(repoDir); + const localCtx = path.join(repoDir, "context.json"); + fs.writeFileSync( + localCtx, + JSON.stringify({ + version: 2, + currentProfile: "default", + profiles: { + default: { + apiBase: "http://127.0.0.1:49999", + companyId: "trusted-co", + }, + }, + }), + ); + process.env.PAPERCLIP_CONTEXT = localCtx; + fs.writeFileSync( + path.join(repoDir, ".paperclip.json"), + JSON.stringify({ + apiBase: srv.apiBase, + companyId: backend.companyId, + }), + ); + expect(() => resolveBoardClient({})).toThrow(/untrusted \.paperclip\.json/i); + + // Repo-local .paperclip/context.json pointing to an unconfigured origin ALSO refuses ambient PAPERCLIP_API_KEY and originless profile keys + fs.rmSync(path.join(repoDir, ".paperclip.json"), { force: true }); + fs.mkdirSync(path.join(repoDir, ".paperclip"), { recursive: true }); + fs.writeFileSync( + path.join(repoDir, ".paperclip", "context.json"), + JSON.stringify({ + version: 2, + currentProfile: "default", + profiles: { + default: { + apiBase: srv.apiBase, + companyId: backend.companyId, + apiKeyEnvVarName: "PAPERCLIP_API_KEY", + }, + }, + }), + ); + expect(() => resolveBoardClient({})).toThrow(/untrusted \.paperclip\/context\.json/i); + fs.rmSync(path.join(repoDir, ".paperclip"), { recursive: true, force: true }); + + // Explicit --api-key overrides the guard + const explicitKeyClient = resolveBoardClient({ apiKey: "brd_ambient_secret" }); + expect(explicitKeyClient.apiKey).toBe("brd_ambient_secret"); + process.chdir(prevCwd); + process.env.PAPERCLIP_HOME = homeDir; + + // 3. pc tasks fail without --requeue sends requeue: false explicitly + delete process.env.PAPERCLIP_CONTEXT; + const task = await asBot.client.tasks.create("eng", { title: "Fail test" }); + const claim = await asBot.client.tasks.claim(task.identifier); + expect(claim).not.toBeNull(); + + const prevClaimToken = process.env.PAPERCLIP_CLAIM_TOKEN; + process.env.PAPERCLIP_CLAIM_TOKEN = claim!.claimToken; + try { + const prog = new Command(); + prog.enablePositionalOptions(); + registerBoardCommands(prog); + await prog.parseAsync([ + "node", + "pc", + "tasks", + "fail", + task.identifier, + "boom", + "--as", + "runner-bot", + "--api-base", + srv.apiBase, + "--company", + backend.companyId, + "--quiet", + ]); + } catch (err) { + if (err instanceof ExitSignal) { + throw new Error(`pc tasks fail exited ${err.code}: ${errs.join("\n")}`); + } + throw err; + } finally { + if (prevClaimToken === undefined) delete process.env.PAPERCLIP_CLAIM_TOKEN; + else process.env.PAPERCLIP_CLAIM_TOKEN = prevClaimToken; + } + + const readAfter = await asBot.client.read(task.identifier); + expect(readAfter.kind).toBe("thread"); + if (readAfter.kind === "thread") { + expect(readAfter.issue.status).toBe("blocked"); + } + } finally { + process.chdir(prevCwd); + if (prevHome === undefined) delete process.env.PAPERCLIP_HOME; + else process.env.PAPERCLIP_HOME = prevHome; + if (prevApiKey === undefined) delete process.env.PAPERCLIP_API_KEY; + else process.env.PAPERCLIP_API_KEY = prevApiKey; + if (prevContext === undefined) delete process.env.PAPERCLIP_CONTEXT; + else process.env.PAPERCLIP_CONTEXT = prevContext; + await srv.close(); + fs.rmSync(repoDir, { recursive: true, force: true }); + fs.rmSync(homeDir, { recursive: true, force: true }); + } + }); +}); diff --git a/cli/src/commands/board/agent-auth.ts b/cli/src/commands/board/agent-auth.ts new file mode 100644 index 00000000000..096ca1ee569 --- /dev/null +++ b/cli/src/commands/board/agent-auth.ts @@ -0,0 +1,491 @@ +import pc from "picocolors"; +import type { Command } from "commander"; +import { AGENT_ROLES, type Agent, type AgentRole } from "@paperclipai/shared"; +import { parseDurationMs, PaperclipError } from "@paperclipai/shared/sdk"; +import { loginBoardCli, openUrl } from "../../client/board-auth.js"; +import { + addBoardClientOptions, + handleBoardError, + resolveBoardClient, + type BoardCommonOptions, + type ResolvedBoardClient, +} from "./client.js"; +import { writeProfileRecord } from "./store.js"; + +interface AgentConnectOptions extends BoardCommonOptions { + role?: string; + ttl?: string; + saveProfile?: string; + revealKey?: boolean; +} + +interface AgentLoginOptions extends BoardCommonOptions { + name: string; + role?: string; + ttl?: string; + saveProfile?: string; + browser?: boolean; +} + +interface AgentConnectApiResponse { + agent?: Agent; + agentId?: string; + agentName?: string; + companyId?: string; + token?: string; + apiKey?: string; + key?: { + id: string; + name: string; + token: string; + createdAt?: string; + expiresAt?: string | null; + }; +} + +function shellEscape(value: string): string { + return value.replace(/'/g, "'\"'\"'"); +} + +function redactApiKeyToken(token: string): string { + const prefixMatch = /^([a-z]+_)/i.exec(token.trim()); + const prefix = prefixMatch ? prefixMatch[1]! : ""; + return `${prefix}••••••••`; +} + +function buildHeadlessAgentExports( + input: { + apiBase: string; + companyId: string; + agentId: string; + apiKey: string; + profile: string; + }, + opts: { revealKey?: boolean } = {}, +): string { + const lines = [ + `export PAPERCLIP_API_URL='${shellEscape(input.apiBase)}'`, + `export PAPERCLIP_COMPANY_ID='${shellEscape(input.companyId)}'`, + `export PAPERCLIP_AGENT_ID='${shellEscape(input.agentId)}'`, + ]; + if (opts.revealKey) { + lines.push(`export PAPERCLIP_API_KEY='${shellEscape(input.apiKey)}'`); + } else { + lines.push(`# PAPERCLIP_API_KEY='${redactApiKeyToken(input.apiKey)}' (redacted; stored in local profile)`); + } + lines.push(`export PAPERCLIP_PROFILE='${shellEscape(input.profile)}'`); + return lines.join("\n"); +} + +function normalizeAgentRole(rawRole?: string): AgentRole { + const candidate = rawRole?.trim().toLowerCase() ?? ""; + if ((AGENT_ROLES as readonly string[]).includes(candidate)) { + return candidate as AgentRole; + } + return "general"; +} + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +async function connectHeadlessAgentWithClient( + resolved: ResolvedBoardClient, + input: { + name: string; + role?: string; + ttl?: string; + saveProfile?: string; + }, +): Promise<{ + profile: string; + profilePath: string; + agentId: string; + agentName: string; + companyId: string; + apiBase: string; + apiKey: string; + keyId?: string; + expiresAt?: string | null; +}> { + const companyId = await resolved.resolveCompanyId(); + const profileName = (input.saveProfile?.trim() || input.name.trim()); + const ttlSec = input.ttl ? Math.max(1, Math.round(parseDurationMs(input.ttl) / 1000)) : undefined; + + let agentId: string | undefined; + let agentName = input.name.trim(); + let apiKey: string | undefined; + let keyId: string | undefined; + let expiresAt: string | null | undefined; + + try { + const connected = await resolved.requestJson( + `/api/companies/${encodeURIComponent(companyId)}/agents/connect`, + { + method: "POST", + body: JSON.stringify({ + name: agentName, + ...(input.role ? { role: input.role } : {}), + ...(ttlSec !== undefined ? { ttlSec } : {}), + }), + }, + ); + agentId = connected.agent?.id ?? connected.agentId; + agentName = connected.agent?.name ?? connected.agentName ?? agentName; + apiKey = connected.key?.token ?? connected.apiKey ?? connected.token; + keyId = connected.key?.id; + expiresAt = connected.key?.expiresAt; + } catch (err) { + if (!(err instanceof PaperclipError) || err.status !== 404) { + throw err; + } + } + + if (!agentId || !apiKey) { + const existingAgents = await resolved.requestJson( + `/api/companies/${encodeURIComponent(companyId)}/agents`, + { method: "GET" }, + ); + const lower = agentName.toLowerCase(); + let target = (existingAgents ?? []).find( + (a) => a.name.toLowerCase() === lower || a.urlKey?.toLowerCase() === lower, + ); + + if (!target) { + target = await resolved.requestJson( + `/api/companies/${encodeURIComponent(companyId)}/agents`, + { + method: "POST", + body: JSON.stringify({ + name: agentName, + role: normalizeAgentRole(input.role), + adapterType: "headless", + }), + }, + ); + } + + const keyName = `cli-${profileName}-${new Date().toISOString().replaceAll(":", "-")}`; + const createdKey = await resolved.requestJson<{ + id: string; + name: string; + token: string; + createdAt: string; + expiresAt?: string | null; + }>(`/api/agents/${encodeURIComponent(target.id)}/keys`, { + method: "POST", + body: JSON.stringify({ + name: keyName, + ...(ttlSec !== undefined ? { ttlSec } : {}), + }), + }); + + agentId = target.id; + agentName = target.name; + apiKey = createdKey.token; + keyId = createdKey.id; + expiresAt = createdKey.expiresAt ?? null; + } + + const profilePath = writeProfileRecord(profileName, { + agentId, + agentName, + companyId, + apiBase: resolved.apiBase, + apiKey, + ...(input.role ? { role: input.role } : {}), + }); + + return { + profile: profileName, + profilePath, + agentId, + agentName, + companyId, + apiBase: resolved.apiBase, + apiKey, + keyId, + expiresAt, + }; +} + +export async function handleBoardWhoami(opts: BoardCommonOptions): Promise { + const resolved = resolveBoardClient(opts); + const info = await resolved.client.whoami(); + if (resolved.json) { + console.log(JSON.stringify(info, null, 2)); + return; + } + + console.log(`${pc.bold("API:")} ${info.apiBase}`); + console.log(`${pc.bold("Company:")} ${info.companyName} [${info.companyPrefix}] (${info.companyId})`); + const principalDetail = info.agentId + ? `agent @${info.agentName ?? info.agentId}` + : info.actorProfile + ? `${info.principalType} (profile=${info.actorProfile}${info.userId ? `, user=${info.userId}` : ""})` + : `${info.principalType}${info.userId ? ` (user=${info.userId})` : ""}`; + console.log(`${pc.bold("Principal:")} ${principalDetail}`); + console.log(`${pc.bold("Policy:")} ${info.agentIdentityPolicy}`); + if (info.scopes) { + console.log(`${pc.bold("Scopes:")} ${JSON.stringify(info.scopes)}`); + } +} + +function buildSafeAgentLoginJson(connected: { + profile: string; + profilePath: string; + agentId: string; + agentName: string; + companyId: string; + apiBase: string; + keyId?: string | null; + expiresAt?: string | null; +}) { + return { + ok: true, + profile: connected.profile, + profilePath: connected.profilePath, + agentId: connected.agentId, + agentName: connected.agentName, + companyId: connected.companyId, + apiBase: connected.apiBase, + ...(connected.keyId !== undefined ? { keyId: connected.keyId } : {}), + ...(connected.expiresAt !== undefined ? { expiresAt: connected.expiresAt } : {}), + }; +} + +export function registerBoardAgentAuthCommands(agentCmd: Command): void { + addBoardClientOptions( + agentCmd + .command("connect") + .description("Create or reuse a headless agent, mint an API key, and store a local profile") + .argument("", "Agent name / profile name") + .option("--role ", "Agent role (e.g. worker, security, engineer, general)", "general") + .option("--ttl ", "Key TTL duration (e.g. 7d, 24h)") + .option("--save-profile ", "Local profile filename under ~/.paperclip/profiles/ (defaults to )") + .option("--reveal-key", "Print the unredacted PAPERCLIP_API_KEY to stdout") + .action(async (name: string, opts: AgentConnectOptions) => { + try { + const resolved = resolveBoardClient(opts); + const result = await connectHeadlessAgentWithClient(resolved, { + name, + role: opts.role, + ttl: opts.ttl, + saveProfile: opts.saveProfile, + }); + const exportsText = buildHeadlessAgentExports(result, { revealKey: opts.revealKey }); + const displayedToken = opts.revealKey + ? result.apiKey + : redactApiKeyToken(result.apiKey); + if (resolved.json) { + console.log( + JSON.stringify( + { + ok: true, + profile: result.profile, + profilePath: result.profilePath, + agentId: result.agentId, + agentName: result.agentName, + companyId: result.companyId, + apiBase: result.apiBase, + key: { + id: result.keyId ?? null, + token: displayedToken, + redacted: !opts.revealKey, + expiresAt: result.expiresAt ?? null, + }, + exports: exportsText, + }, + null, + 2, + ), + ); + return; + } + + console.log(`# Saved agent profile '${result.profile}' to ${result.profilePath}`); + console.log(exportsText); + } catch (err) { + handleBoardError(err, opts); + } + }), + { includeCompany: true }, + ); + + addBoardClientOptions( + agentCmd + .command("login") + .description("Provision a headless agent API key via browser approval") + .requiredOption("--name ", "Agent name to create or connect") + .option("--role ", "Agent role", "general") + .option("--ttl ", "Key TTL duration (e.g. 7d)") + .option("--save-profile ", "Local profile filename (defaults to --name)") + .option("--no-browser", "Do not attempt to open a browser automatically") + .action(async (opts: AgentLoginOptions) => { + try { + const resolved = resolveBoardClient(opts); + const profileName = opts.saveProfile?.trim() || opts.name.trim(); + let requestedCompanyId: string | null = null; + if (opts.company || opts.companyId) { + try { + requestedCompanyId = await resolved.resolveCompanyId(); + } catch { + requestedCompanyId = (opts.company ?? opts.companyId)?.trim() ?? null; + } + } + + let directAgentChallengeSupported = true; + let challengeResponse: { + id: string; + token: string; + boardApiToken?: string; + approvalPath: string; + approvalUrl: string | null; + pollPath: string; + expiresAt: string; + suggestedPollIntervalMs: number; + } | null = null; + + try { + challengeResponse = await resolved.requestJson("/api/cli-auth/challenges", { + method: "POST", + body: JSON.stringify({ + command: `paperclipai agent login --name ${opts.name}`, + clientName: "paperclipai cli", + requestedAccess: "board", + requestedCompanyId, + challengeKind: "agent_key", + agentName: opts.name, + ...(opts.role ? { agentRole: opts.role } : {}), + }), + }); + } catch (err) { + if (err instanceof PaperclipError && err.status === 400) { + directAgentChallengeSupported = false; + } else { + throw err; + } + } + + if (!directAgentChallengeSupported || !challengeResponse) { + const login = await loginBoardCli({ + apiBase: resolved.apiBase, + requestedAccess: "board", + requestedCompanyId, + command: `paperclipai agent login --name ${opts.name}`, + openBrowser: opts.browser, + }); + const authedResolved = resolveBoardClient({ + ...opts, + apiBase: resolved.apiBase, + apiKey: login.token, + }); + const connected = await connectHeadlessAgentWithClient(authedResolved, { + name: opts.name, + role: opts.role, + ttl: opts.ttl, + saveProfile: profileName, + }); + if (resolved.json) { + console.log(JSON.stringify(buildSafeAgentLoginJson(connected), null, 2)); + return; + } + console.log( + pc.green(`Connected agent '${connected.agentName}' and saved profile '${connected.profile}' to ${connected.profilePath}`), + ); + return; + } + + const approvalUrl = + challengeResponse.approvalUrl ?? `${resolved.apiBase}${challengeResponse.approvalPath}`; + console.error(pc.bold("Agent authorization required")); + console.error(`Open this URL in your browser to approve agent '${opts.name}':\n${approvalUrl}`); + if (opts.browser !== false) { + await openUrl(approvalUrl); + } + + const expiresAtMs = Date.parse(challengeResponse.expiresAt); + const pollMs = Math.max(500, challengeResponse.suggestedPollIntervalMs || 1000); + while (Date.now() < expiresAtMs) { + const status = await resolved.requestJson<{ + status: "pending" | "approved" | "cancelled" | "expired"; + agentApiToken?: string; + agentId?: string; + companyId?: string; + }>( + `/api${challengeResponse.pollPath}?token=${encodeURIComponent(challengeResponse.token)}`, + { method: "GET" }, + ); + + if (status.status === "approved") { + const resolvedAgentToken = status.agentApiToken ?? challengeResponse.boardApiToken; + if (resolvedAgentToken && status.agentId && status.companyId) { + const profilePath = writeProfileRecord(profileName, { + agentId: status.agentId, + agentName: opts.name.trim(), + companyId: status.companyId, + apiBase: resolved.apiBase, + apiKey: resolvedAgentToken, + ...(opts.role ? { role: opts.role } : {}), + }); + const out = { + ok: true, + profile: profileName, + profilePath, + agentId: status.agentId, + agentName: opts.name.trim(), + companyId: status.companyId, + apiBase: resolved.apiBase, + }; + if (resolved.json) { + console.log(JSON.stringify(out, null, 2)); + } else { + console.log( + pc.green(`Approved agent '${opts.name}' and saved profile '${profileName}' to ${profilePath}`), + ); + } + return; + } + + if (!challengeResponse.boardApiToken) { + throw new Error("Approved challenge did not yield an agent or board token."); + } + const authedResolved = resolveBoardClient({ + ...opts, + apiBase: resolved.apiBase, + apiKey: challengeResponse.boardApiToken, + }); + const connected = await connectHeadlessAgentWithClient(authedResolved, { + name: opts.name, + role: opts.role, + ttl: opts.ttl, + saveProfile: profileName, + }); + if (resolved.json) { + console.log(JSON.stringify(buildSafeAgentLoginJson(connected), null, 2)); + } else { + console.log( + pc.green(`Approved agent '${connected.agentName}' and saved profile '${connected.profile}' to ${connected.profilePath}`), + ); + } + return; + } + + if (status.status === "cancelled") { + throw new Error("Agent login challenge was cancelled."); + } + if (status.status === "expired") { + throw new Error("Agent login challenge expired before approval."); + } + + await sleep(pollMs); + } + + throw new Error("Agent login challenge expired before approval."); + } catch (err) { + handleBoardError(err, opts); + } + }), + { includeCompany: true }, + ); +} diff --git a/cli/src/commands/board/channels.ts b/cli/src/commands/board/channels.ts new file mode 100644 index 00000000000..a3b87bd64b4 --- /dev/null +++ b/cli/src/commands/board/channels.ts @@ -0,0 +1,582 @@ +import pc from "picocolors"; +import type { Command } from "commander"; +import type { ChannelPage, ChannelView, ThreadDetailView } from "@paperclipai/shared/sdk"; +import { channelsCommand } from "../channels.js"; +import { + addBoardClientOptions, + collectOption, + handleBoardError, + isPcBinary, + isScriptOutput, + parseJsonArg, + parseKeyValuePairs, + parseLabelsList, + readTextInput, + resolveBoardClient, + splitCsvValues, + type BoardCommonOptions, +} from "./client.js"; + +interface ChannelsListOptions extends BoardCommonOptions { + prefix?: string; + boardChannels?: boolean; +} + +interface ChannelCreateOptions extends BoardCommonOptions { + private?: boolean; + project?: string; + description?: string; +} + +interface PostOptions extends BoardCommonOptions { + title?: string; + file?: string; + attach?: string[]; + label?: string[]; + schema?: string; + data?: string; + board?: boolean; + idempotencyKey?: string; +} + +interface ReplyOptions extends BoardCommonOptions { + file?: string; + attach?: string[]; + label?: string[]; + schema?: string; + data?: string; + after?: string; + internal?: boolean; + idempotencyKey?: string; +} + +interface ReadOptions extends BoardCommonOptions { + label?: string[]; + status?: string[]; + after?: string; + limit?: number; +} + +interface LabelOptions extends BoardCommonOptions { + set?: string[]; + unset?: string[]; + if?: string[]; + ifUnset?: string[]; +} + +export function shouldRouteToBoardChannels(opts: ChannelsListOptions, prefixArg?: string): boolean { + if (isPcBinary()) return true; + if (opts.boardChannels) return true; + if (prefixArg !== undefined) return true; + if (opts.prefix !== undefined) return true; + if (opts.company !== undefined) return true; + if (opts.companyId !== undefined) return true; + if (opts.apiBase !== undefined) return true; + if (opts.as !== undefined) return true; + return false; +} + +function tryParseJsonObject(raw: string): Record | null { + const trimmed = raw.trim(); + if (!trimmed.startsWith("{")) return null; + try { + const parsed = JSON.parse(trimmed) as unknown; + if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) { + return parsed as Record; + } + return null; + } catch { + return null; + } +} + +function resolveTextAndSchema(input: { + textParts: string[]; + file?: string; + schemaRef?: string; + dataJson?: string; +}): { + text: string | undefined; + schema: { ref: string; data: Record } | undefined; +} { + const fileText = input.file !== undefined ? readTextInput(undefined, input.file) : undefined; + + if (!input.schemaRef) { + const inline = input.textParts.length > 0 ? input.textParts.join(" ") : undefined; + return { + text: fileText ?? inline, + schema: undefined, + }; + } + + let data: Record | null = null; + let prose: string | undefined = fileText; + + if (input.dataJson !== undefined) { + const parsed = parseJsonArg(input.dataJson, "--data"); + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { + throw new Error("--data must be a JSON object"); + } + data = parsed as Record; + if (prose === undefined && input.textParts.length > 0) { + prose = input.textParts.join(" "); + } + } else if (input.textParts.length > 0) { + const last = input.textParts[input.textParts.length - 1]!; + const parsedLast = tryParseJsonObject(last); + if (parsedLast) { + data = parsedLast; + const before = input.textParts.slice(0, -1).join(" ").trim(); + if (prose === undefined && before) { + prose = before; + } + } + } + + if (!data && fileText !== undefined) { + const parsedFile = tryParseJsonObject(fileText); + if (parsedFile) { + data = parsedFile; + prose = input.textParts.length > 0 ? input.textParts.join(" ") : undefined; + } + } + + if (!data) { + throw new Error( + `--schema ${input.schemaRef} requires a JSON object payload via --data '', positional JSON argument, or --file `, + ); + } + + return { + text: prose, + schema: { ref: input.schemaRef, data }, + }; +} + +function formatChannelList(channels: ChannelView[]): void { + if (channels.length === 0) { + console.log(pc.dim("(no channels)")); + return; + } + + const groups = new Map(); + for (const ch of channels) { + const slashIdx = ch.path.indexOf("/"); + const group = slashIdx === -1 ? "" : `${ch.path.slice(0, slashIdx)}/`; + const list = groups.get(group) ?? []; + list.push(ch); + groups.set(group, list); + } + + for (const [group, items] of groups.entries()) { + if (group) { + console.log(pc.bold(group)); + } + for (const ch of items) { + const vis = ch.visibility === "private" ? pc.yellow(" [private]") : ""; + const counts = pc.dim(`(${ch.threadCount} threads, ${ch.readyTaskCount} ready)`); + const desc = ch.description ? pc.dim(` — ${ch.description}`) : ""; + console.log(` #${ch.path}${vis} ${counts}${desc}`); + } + } +} + +function formatLabelsInline( + kvLabels: Record | undefined, + tagLabels: string[] | undefined, +): string { + const parts: string[] = []; + for (const tag of tagLabels ?? []) { + parts.push(`#${tag}`); + } + for (const [k, v] of Object.entries(kvLabels ?? {})) { + parts.push(`${k}=${v}`); + } + return parts.length > 0 ? pc.dim(` [${parts.join(" ")}]`) : ""; +} + +function formatReadPage(page: ChannelPage, opts: { quiet?: boolean }): void { + console.log(pc.bold(`#${page.channel}`) + pc.dim(` (${page.items.length} items)`)); + if (page.items.length === 0) { + console.log(pc.dim(" (empty)")); + } else { + for (const item of page.items) { + // Omit [backlog] on passive channel posts so discussions read naturally + const statusBadge = item.isPassivePost ? "" : ` [${item.status}]`; + const actor = item.actorProfile + ? `@${item.actorProfile}` + : item.assigneeAgentId + ? `agent:${item.assigneeAgentId.slice(0, 8)}` + : "board"; + const replies = item.replyCount > 0 ? `, ${item.replyCount} replies` : ""; + const labels = formatLabelsInline(item.kvLabels, item.tagLabels); + console.log( + ` ${pc.cyan(item.identifier)}${statusBadge} ${item.title} ${pc.dim(`(#${item.channel ?? "board"}, ${actor}${replies})`)}${labels}`, + ); + } + } + if (process.stdout.isTTY && !opts.quiet) { + console.log(pc.dim(`cursor: ${page.cursor} (use --after ${page.cursor} for newer updates)`)); + } +} + +function formatThreadDetail(detail: ThreadDetailView, opts: { quiet?: boolean }): void { + const { issue } = detail; + const statusBadge = issue.isPassivePost ? "" : ` [${issue.status}]`; + const chBadge = issue.channel ? ` #${issue.channel}` : ""; + console.log(`${pc.cyan(pc.bold(issue.identifier))}${statusBadge}${pc.dim(chBadge)} ${pc.bold(issue.title)}`); + const labels = formatLabelsInline(issue.kvLabels, issue.tagLabels); + if (labels) { + console.log(` labels:${labels}`); + } + if (issue.resultSchemaRef) { + console.log(pc.dim(` resultSchema: ${issue.resultSchemaRef}`)); + } + if (issue.description) { + console.log(""); + console.log(issue.description); + } + const blocks = issue.blocks ?? []; + if (blocks.length > 0) { + for (const block of blocks) { + console.log(pc.dim(` [${block.schema}@${block.version}] `) + JSON.stringify(block.data)); + } + } + const comments = detail.comments ?? []; + if (comments.length > 0) { + console.log(""); + console.log(pc.bold(`Replies (${comments.length}):`)); + for (const comment of comments) { + const who = comment.actorProfile ?? comment.authorType; + const internal = comment.internal ? pc.yellow(" [internal]") : ""; + console.log(` ${pc.dim(comment.id)} ${pc.cyan(who)}${internal}: ${comment.body}`); + for (const block of comment.blocks ?? []) { + console.log(pc.dim(` [${block.schema}@${block.version}] `) + JSON.stringify(block.data)); + } + } + } + const interactions = detail.interactions ?? []; + if (interactions.length > 0) { + console.log(""); + console.log(pc.bold(`Interactions (${interactions.length}):`)); + for (const ix of interactions) { + const outcome = ix.answer ?? ix.note; + const suffix = outcome ? pc.green(` -> ${outcome}`) : ""; + console.log(` ${pc.dim(ix.id)} [${ix.status}] ${ix.kind}: ${ix.prompt}${suffix}`); + } + } + if (process.stdout.isTTY && !opts.quiet) { + console.log(pc.dim(`cursor: ${detail.cursor} (use --after ${detail.cursor} for newer updates)`)); + } +} + +async function executeChannelsList( + prefixArg: string | undefined, + cmdOpts: ChannelsListOptions, + forceBoard: boolean, +): Promise { + try { + if (!forceBoard && !shouldRouteToBoardChannels(cmdOpts, prefixArg)) { + await channelsCommand({ json: cmdOpts.json }); + return; + } + const resolved = resolveBoardClient(cmdOpts); + const effectivePrefix = cmdOpts.prefix ?? prefixArg; + const list = await resolved.client.channels.list(effectivePrefix); + if (resolved.json) { + console.log(JSON.stringify(list, null, 2)); + return; + } + formatChannelList(list); + } catch (err) { + handleBoardError(err, cmdOpts); + } +} + +function configureChannelsSubtree(cmd: Command, opts: { forceBoard: boolean }): void { + addBoardClientOptions( + cmd + .description( + opts.forceBoard + ? "List board channels" + : "Show release channels (paperclipai) or board channels (pc / --board-channels / --prefix)", + ) + .argument("[prefix]", "Optional channel path prefix (e.g. build/)") + .option("--prefix ", "Filter board channels by path prefix (e.g. build/)") + .option("--board-channels", "Force listing board channels instead of release channels") + .action(async (prefixArg: string | undefined, cmdOpts: ChannelsListOptions) => { + await executeChannelsList(prefixArg, cmdOpts, opts.forceBoard); + }), + ); + + addBoardClientOptions( + cmd + .command("list") + .description("List board channels") + .argument("[prefix]", "Optional channel path prefix (e.g. build/)") + .option("--prefix ", "Filter board channels by path prefix (e.g. build/)") + .action(async (prefixArg: string | undefined, listOpts: ChannelsListOptions) => { + await executeChannelsList(prefixArg, listOpts, true); + }), + ); + + addBoardClientOptions( + cmd + .command("create") + .description("Create a board channel") + .argument("", "Channel path (e.g. build/auth)") + .option("--private", "Create a private channel") + .option("--project ", "Default project ID or slug for this channel") + .option("--description ", "Channel description") + .action(async (channelPath: string, createOpts: ChannelCreateOptions) => { + try { + const resolved = resolveBoardClient(createOpts); + const created = await resolved.client.channels.create(channelPath, { + ...(createOpts.private ? { visibility: "private" as const } : {}), + ...(createOpts.project ? { defaultProjectId: createOpts.project } : {}), + ...(createOpts.description !== undefined ? { description: createOpts.description } : {}), + }); + if (resolved.json) { + console.log(JSON.stringify(created, null, 2)); + return; + } + if (isScriptOutput(resolved)) { + console.log(created.path); + return; + } + console.log(pc.green(`Channel #${created.path} (${created.visibility}) ready.`)); + } catch (err) { + handleBoardError(err, createOpts); + } + }), + ); +} + +export function registerBoardChannelCommands(program: Command): void { + const existingChannels = program.commands.find((c) => c.name() === "channels"); + if (existingChannels) { + throw new Error("Unexpected duplicate 'channels' command before board channel registration"); + } + const channelsCmd = program.command("channels"); + configureChannelsSubtree(channelsCmd, { forceBoard: false }); + + const board = program.commands.find((c) => c.name() === "board") ?? program.command("board").description("Board operator operations"); + const boardChannelsCmd = board.command("channels"); + configureChannelsSubtree(boardChannelsCmd, { forceBoard: true }); + + addBoardClientOptions( + program + .command("post") + .description("Post a passive note or structured message to a channel") + .argument("", "Channel path (e.g. deploys/prod)") + .argument("[text...]", "Post text (or JSON block when --schema is used)") + .option("--title ", "Explicit title") + .option("--file ", "Read message body (or schema JSON) from file or '-' for stdin") + .option("--attach ", "Attach file(s) to the created post", collectOption, []) + .option("--label ", "Set label(s) (repeatable)", collectOption, []) + .option("--schema ", "Attach a validated schema block (@)") + .option("--data ", "JSON object data for --schema") + .option("--board", "Also surface this post on the main Tasks board (scope=board)") + .option("--idempotency-key ", "Idempotency key for safe retries") + .action(async (channel: string, textParts: string[], opts: PostOptions) => { + try { + const resolved = resolveBoardClient(opts); + const { text, schema } = resolveTextAndSchema({ + textParts, + file: opts.file, + schemaRef: opts.schema, + dataJson: opts.data, + }); + if ((!text || !text.trim()) && !schema && !opts.title?.trim()) { + throw new Error("Post requires message text, --title, --file, or --schema payload."); + } + const { kvLabels, tagLabels } = parseLabelsList(opts.label); + const created = await resolved.client.post(channel, { + ...(opts.title !== undefined ? { title: opts.title } : {}), + ...(text !== undefined ? { text } : {}), + ...(Object.keys(kvLabels).length > 0 ? { labels: kvLabels } : {}), + ...(tagLabels.length > 0 ? { tagLabels } : {}), + ...(schema ? { schema } : {}), + ...(opts.board ? { board: true } : {}), + ...(opts.idempotencyKey ? { idempotencyKey: opts.idempotencyKey } : {}), + }); + + if (opts.attach && opts.attach.length > 0) { + await resolved.uploadIssueAttachments(created.companyId, created.id, opts.attach); + } + + if (resolved.json) { + console.log(JSON.stringify(created, null, 2)); + return; + } + if (isScriptOutput(resolved)) { + console.log(created.identifier); + return; + } + console.log( + `${pc.cyan(created.identifier)} #${created.channel ?? channel} ${created.title} ${pc.dim(`(${created.cursor})`)}`, + ); + } catch (err) { + handleBoardError(err, opts); + } + }), + ); + + addBoardClientOptions( + program + .command("reply") + .description("Reply to an existing thread or task") + .argument("", "Issue identifier (e.g. PAP-142) or UUID") + .argument("[text...]", "Reply text (or JSON block when --schema is used)") + .option("--file ", "Read reply body (or schema JSON) from file or '-' for stdin") + .option("--attach ", "Attach file(s) to the thread", collectOption, []) + .option("--label ", "Set comment kv-label(s) (repeatable)", collectOption, []) + .option("--schema ", "Attach a validated schema block (@)") + .option("--data ", "JSON object data for --schema") + .option("--after ", "Optimistic guard: fail with 409 newer_message if newer comments exist") + .option("--internal", "Mark reply as internal") + .option("--idempotency-key ", "Idempotency key for safe retries") + .action(async (id: string, textParts: string[], opts: ReplyOptions) => { + try { + const resolved = resolveBoardClient(opts); + const { text, schema } = resolveTextAndSchema({ + textParts, + file: opts.file, + schemaRef: opts.schema, + dataJson: opts.data, + }); + if ((!text || !text.trim()) && !schema) { + throw new Error("Reply requires message text, --file, or --schema payload."); + } + const kvLabels = parseKeyValuePairs(opts.label, "--label"); + const comment = await resolved.client.reply(id, { + ...(text !== undefined ? { body: text } : {}), + ...(Object.keys(kvLabels).length > 0 ? { labels: kvLabels } : {}), + ...(schema ? { schema } : {}), + ...(opts.after ? { after: opts.after } : {}), + ...(opts.internal ? { internal: true } : {}), + ...(opts.idempotencyKey ? { idempotencyKey: opts.idempotencyKey } : {}), + }); + + if (opts.attach && opts.attach.length > 0) { + const companyId = await resolved.resolveCompanyId(); + await resolved.uploadIssueAttachments(companyId, comment.issueId, opts.attach); + } + + if (resolved.json) { + console.log(JSON.stringify(comment, null, 2)); + return; + } + if (isScriptOutput(resolved)) { + console.log(comment.id); + return; + } + console.log( + `${pc.cyan(comment.id)} on ${comment.identifier} ${pc.dim(`(${comment.cursor})`)}`, + ); + } catch (err) { + handleBoardError(err, opts); + } + }), + ); + + addBoardClientOptions( + program + .command("read") + .description("Read a channel feed (e.g. build/) or full thread/task (e.g. PAP-142)") + .argument("[target]", "Channel path or issue identifier/UUID", "general") + .option("--label ", "Filter by label expression (repeatable)", collectOption, []) + .option("--status ", "Filter by issue status (repeatable or comma-separated)", collectOption, []) + .option("--after ", "Return updates after cursor (evt_...)") + .option("-n, --limit ", "Maximum number of items", (val) => Number.parseInt(val, 10)) + .action(async (target: string, opts: ReadOptions) => { + try { + const resolved = resolveBoardClient(opts); + const statuses = splitCsvValues(opts.status) as Array< + "backlog" | "todo" | "in_progress" | "in_review" | "blocked" | "done" | "cancelled" + >; + const result = await resolved.client.read(target, { + ...(opts.label && opts.label.length > 0 ? { label: opts.label } : {}), + ...(statuses.length > 0 ? { status: statuses } : {}), + ...(opts.after ? { after: opts.after } : {}), + ...(opts.limit !== undefined && Number.isFinite(opts.limit) ? { limit: opts.limit } : {}), + }); + + if (resolved.json) { + console.log(JSON.stringify(result, null, 2)); + return; + } + if (result.kind === "channel") { + formatReadPage(result, resolved); + } else { + formatThreadDetail(result, resolved); + } + } catch (err) { + handleBoardError(err, opts); + } + }), + ); + + addBoardClientOptions( + program + .command("label") + .description("Atomically set/unset key=value labels with optional compare-and-swap (--if)") + .argument("", "Issue identifier (e.g. PAP-50) or UUID") + .argument("[kv...]", "Key=value pairs to set") + .option("--set ", "Key=value pair to set (repeatable)", collectOption, []) + .option("--unset ", "Label key(s) to remove (repeatable)", collectOption, []) + .option("--if ", "CAS precondition: key=value, or key=null / key= when unset (repeatable)", collectOption, []) + .option("--if-unset ", "CAS precondition: key must currently be unset (repeatable)", collectOption, []) + .action(async (id: string, kvArgs: string[], opts: LabelOptions) => { + try { + const resolved = resolveBoardClient(opts); + const setMap = parseKeyValuePairs([...(opts.set ?? []), ...kvArgs], "label"); + const ifMap: Record = {}; + for (const rawIf of opts.if ?? []) { + const eqIdx = rawIf.indexOf("="); + if (eqIdx === -1) { + throw new Error(`Invalid --if "${rawIf}": expected = or =null`); + } + const key = rawIf.slice(0, eqIdx).trim(); + const val = rawIf.slice(eqIdx + 1).trim(); + if (!key) { + throw new Error(`Invalid --if "${rawIf}": key must be non-empty`); + } + ifMap[key] = val === "" || val === "null" ? null : val; + } + for (const key of opts.ifUnset ?? []) { + const trimmed = key.trim(); + if (trimmed) { + ifMap[trimmed] = null; + } + } + const unsetList = (opts.unset ?? []).map((k) => k.trim()).filter(Boolean); + + if ( + Object.keys(setMap).length === 0 && + unsetList.length === 0 && + Object.keys(ifMap).length === 0 + ) { + throw new Error("Specify at least one , --set , --unset , --if , or --if-unset ."); + } + + const result = await resolved.client.label(id, { + ...(Object.keys(setMap).length > 0 ? { set: setMap } : {}), + ...(unsetList.length > 0 ? { unset: unsetList } : {}), + ...(Object.keys(ifMap).length > 0 ? { if: ifMap } : {}), + }); + + if (resolved.json) { + console.log(JSON.stringify(result, null, 2)); + return; + } + const labelSummary = Object.entries(result.kvLabels) + .map(([k, v]) => `${k}=${v}`) + .join(" "); + console.log(`${pc.cyan(id)} ${labelSummary || pc.dim("(no labels)")} ${pc.dim(`(${result.cursor})`)}`); + } catch (err) { + handleBoardError(err, opts); + } + }), + ); +} diff --git a/cli/src/commands/board/client.ts b/cli/src/commands/board/client.ts new file mode 100644 index 00000000000..ad49c5c7492 --- /dev/null +++ b/cli/src/commands/board/client.ts @@ -0,0 +1,493 @@ +import fs from "node:fs"; +import path from "node:path"; +import pc from "picocolors"; +import type { Command } from "commander"; +import { + paperclip, + PaperclipError, + type CompanyResolutionView, + type PaperclipHandle, +} from "@paperclipai/shared/sdk"; +import { getStoredBoardCredential } from "../../client/board-auth.js"; +import { readContext, resolveProfile } from "../../client/context.js"; +import { ApiRequestError } from "../../client/http.js"; +import { inferApiBaseFromConfig, inferContentTypeFromPath, normalizeApiBase } from "../client/common.js"; +import { detectGitWorkspaceInfo } from "../git-workspace.js"; +import { readProfileRecord } from "./store.js"; + +export interface BoardCommonOptions { + apiBase?: string; + apiKey?: string; + company?: string; + companyId?: string; + as?: string; + config?: string; + dataDir?: string; + context?: string; + quiet?: boolean; + json?: boolean; +} + +export interface RepoLocalBoardConfig { + source?: "local_context" | "paperclip_json"; + apiBase?: string; + companyId?: string; + company?: string; +} + +export interface ResolvedBoardClient { + client: PaperclipHandle; + apiBase: string; + apiKey: string | undefined; + company: string | undefined; + profile: string | null; + quiet: boolean; + json: boolean; + resolveCompanyId: () => Promise; + requestJson: (reqPath: string, init?: RequestInit) => Promise; + uploadIssueAttachments: (companyId: string, issueId: string, files: string[]) => Promise; +} + +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 function isPcBinary(argv: string[] = process.argv): boolean { + if (process.env.PAPERCLIP_CLI_PERSONA === "pc") { + return true; + } + const binPath = argv[1] ?? ""; + if (!binPath) return false; + const binName = path.basename(binPath).replace(/\.(?:js|mjs|cjs|ts)$/i, ""); + return binName === "pc"; +} + +export function addBoardClientOptions( + command: Command, + opts: { includeCompany?: boolean; includeJson?: boolean } = {}, +): Command { + command + .option("--api-base ", "Base URL for the Paperclip API") + .option("--api-key ", "Bearer token for board or agent calls") + .option("--company ", "Company ID or issue prefix (e.g. PAP)") + .option("--as ", "Act as a named profile or registered headless agent") + .option("-c, --config ", "Path to Paperclip config file") + .option("-d, --data-dir ", "Paperclip data directory root") + .option("--context ", "Path to CLI context file") + .option("-q, --quiet", "Print only minimal identifiers for scripting"); + + if (opts.includeCompany !== false) { + command.option("-C, --company-id ", "Company ID (overrides context default)"); + } + if (opts.includeJson !== false) { + command.option("--json", "Output raw JSON"); + } + + return command; +} + +export function readRepoLocalBoardConfig(cwd = process.cwd()): RepoLocalBoardConfig | null { + const git = detectGitWorkspaceInfo(cwd); + const roots = [ + ...(git ? [git.root] : []), + path.resolve(cwd), + ]; + const uniqueRoots = [...new Set(roots.map((r) => path.resolve(r)))]; + + for (const root of uniqueRoots) { + const envHome = process.env.PAPERCLIP_HOME?.trim(); + if (envHome && path.resolve(envHome) !== path.join(root, ".paperclip", "board")) { + continue; + } + + const localContextPath = path.join(root, ".paperclip", "context.json"); + if (fs.existsSync(localContextPath)) { + try { + const profile = resolveProfile(readContext(localContextPath)).profile; + if (profile.apiBase || profile.companyId) { + return { + source: "local_context", + apiBase: profile.apiBase, + companyId: profile.companyId, + }; + } + } catch { + // Ignore malformed optional repo context file + } + } + + const candidate = path.join(root, ".paperclip.json"); + if (!fs.existsSync(candidate)) continue; + try { + const parsed = JSON.parse(fs.readFileSync(candidate, "utf8")) as unknown; + if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) { + const rec = parsed as Record; + return { + source: "paperclip_json", + apiBase: typeof rec.apiBase === "string" ? rec.apiBase : undefined, + companyId: typeof rec.companyId === "string" ? rec.companyId : undefined, + company: typeof rec.company === "string" ? rec.company : undefined, + }; + } + } catch { + // Ignore malformed optional repo file + } + } + return null; +} + +export function readTextInput(inlineText?: string, filePath?: string): string | undefined { + if (filePath !== undefined) { + if (filePath === "-") { + return fs.readFileSync(0, "utf8"); + } + return fs.readFileSync(path.resolve(filePath), "utf8"); + } + return inlineText; +} + +export function parseJsonArg(raw: string, label = "JSON"): unknown { + try { + return JSON.parse(raw) as unknown; + } catch (err) { + throw new Error(`Invalid ${label}: ${err instanceof Error ? err.message : String(err)}`); + } +} + +export function collectOption(value: string, previous: string[] = []): string[] { + return [...previous, value]; +} + +export function parseLabelsList(rawLabels: string[] | undefined): { + kvLabels: Record; + tagLabels: string[]; +} { + const kvLabels: Record = {}; + const tagLabels: string[] = []; + for (const item of rawLabels ?? []) { + const trimmed = item.trim(); + if (!trimmed) continue; + const eqIdx = trimmed.indexOf("="); + if (eqIdx === -1) { + tagLabels.push(trimmed); + continue; + } + const key = trimmed.slice(0, eqIdx).trim(); + const val = trimmed.slice(eqIdx + 1).trim(); + if (!key || !val) { + throw new Error(`Invalid label "${item}": expected =`); + } + kvLabels[key] = val; + } + return { kvLabels, tagLabels }; +} + +export function parseKeyValuePairs(items: string[] | undefined, flagName = "label"): Record { + const result: Record = {}; + for (const item of items ?? []) { + const eqIdx = item.indexOf("="); + if (eqIdx === -1) { + throw new Error(`Invalid ${flagName} "${item}": expected =`); + } + const key = item.slice(0, eqIdx).trim(); + const val = item.slice(eqIdx + 1).trim(); + if (!key || !val) { + throw new Error(`Invalid ${flagName} "${item}": expected non-empty =`); + } + result[key] = val; + } + return result; +} + +export function splitCsvValues(values: string[] | undefined): string[] { + const out: string[] = []; + for (const entry of values ?? []) { + for (const part of entry.split(",")) { + const trimmed = part.trim(); + if (trimmed) out.push(trimmed); + } + } + return out; +} + +async function parseFetchError(res: Response): Promise { + const text = await res.text().catch(() => ""); + let parsed: Record | null = null; + if (text) { + try { + const raw = JSON.parse(text) as unknown; + if (typeof raw === "object" && raw !== null && !Array.isArray(raw)) { + parsed = raw as Record; + } + } catch { + // plain text + } + } + const nestedDetails = + parsed?.details && typeof parsed.details === "object" && !Array.isArray(parsed.details) + ? (parsed.details as Record) + : null; + const code = + (typeof parsed?.code === "string" && parsed.code) || + (typeof nestedDetails?.code === "string" && nestedDetails.code) || + (typeof parsed?.error === "string" && parsed.error) || + `http_${res.status}`; + const message = + (typeof parsed?.message === "string" && parsed.message) || + (typeof parsed?.error === "string" && parsed.error) || + text || + `Request failed with status ${res.status}`; + const rawNext = Array.isArray(parsed?.next) + ? parsed.next + : Array.isArray(nestedDetails?.next) + ? nestedDetails.next + : undefined; + const next = rawNext?.filter((item): item is string => typeof item === "string"); + return new PaperclipError({ + status: res.status, + code, + message, + next, + details: parsed ?? undefined, + }); +} + +export function resolveBoardClient(opts: BoardCommonOptions): ResolvedBoardClient { + const profile = + opts.as !== undefined + ? opts.as.trim() || null + : process.env.PAPERCLIP_PROFILE?.trim() || null; + + const rawStoredProfile = profile ? readProfileRecord(profile) : null; + let contextProfile: { apiBase?: string; companyId?: string; apiKeyEnvVarName?: string } = {}; + try { + const context = readContext(opts.context); + contextProfile = resolveProfile(context).profile; + } catch { + // Allow operating even if context file is absent or unreadable + } + const repoLocal = opts.context || opts.dataDir ? null : readRepoLocalBoardConfig(); + + const explicitApiBase = opts.apiBase?.trim(); + const envApiBase = process.env.PAPERCLIP_API_URL?.trim(); + const explicitOrRepoApiBase = + explicitApiBase || + envApiBase || + repoLocal?.apiBase?.trim() || + undefined; + + const storedProfile = + rawStoredProfile && + (!explicitOrRepoApiBase || + !rawStoredProfile.apiBase?.trim() || + normalizeApiBase(rawStoredProfile.apiBase.trim()) === normalizeApiBase(explicitOrRepoApiBase)) + ? rawStoredProfile + : null; + + const profileApiBase = storedProfile?.apiBase?.trim(); + const repoEndpointApiBase = + !explicitApiBase && + !envApiBase && + !profileApiBase && + (repoLocal?.source === "paperclip_json" || repoLocal?.source === "local_context") + ? repoLocal.apiBase?.trim() + : undefined; + + const rawApiBase = + explicitOrRepoApiBase || + profileApiBase || + contextProfile.apiBase?.trim() || + inferApiBaseFromConfig(opts.config); + const apiBase = normalizeApiBase(rawApiBase); + + const sameOrigin = (a?: string, b?: string): boolean => { + if (!a || !b) return false; + try { + return new URL(normalizeApiBase(a)).origin === new URL(normalizeApiBase(b)).origin; + } catch { + return false; + } + }; + + const untrustedRepoEndpoint = + Boolean(repoEndpointApiBase) && + !sameOrigin(apiBase, contextProfile.apiBase); + + const explicitAsRequested = opts.as !== undefined && Boolean(opts.as.trim()); + const explicitFlagKey = opts.apiKey?.trim() || undefined; + const envApiKey = process.env.PAPERCLIP_API_KEY?.trim() || undefined; + const profileEnvKey = contextProfile.apiKeyEnvVarName + ? process.env[contextProfile.apiKeyEnvVarName]?.trim() || undefined + : undefined; + const hasOriginlessProfileKey = Boolean( + storedProfile?.apiKey && !storedProfile.apiBase, + ); + const trustedProfileKey = + storedProfile?.apiKey && + ((storedProfile.apiBase && sameOrigin(storedProfile.apiBase, apiBase)) || + (!storedProfile.apiBase && !untrustedRepoEndpoint)) + ? storedProfile.apiKey + : undefined; + const storedBoardKey = getStoredBoardCredential(apiBase)?.token; + + if ( + untrustedRepoEndpoint && + !explicitFlagKey && + (envApiKey || profileEnvKey || hasOriginlessProfileKey) + ) { + throw new Error( + `Refusing to send ambient credentials to untrusted ${repoLocal?.source === "local_context" ? ".paperclip/context.json" : ".paperclip.json"} apiBase '${apiBase}'. Pass --api-base or --api-key explicitly if you trust this endpoint.`, + ); + } + + const ambientKey = untrustedRepoEndpoint ? undefined : (envApiKey ?? profileEnvKey); + const apiKey = + explicitFlagKey ?? + (explicitAsRequested + ? (trustedProfileKey ?? storedBoardKey ?? ambientKey) + : (ambientKey ?? trustedProfileKey ?? storedBoardKey)); + + const repoLocalMatchesApiBase = + !repoLocal?.apiBase?.trim() || normalizeApiBase(repoLocal.apiBase.trim()) === apiBase; + const contextMatchesApiBase = + !contextProfile.apiBase?.trim() || normalizeApiBase(contextProfile.apiBase.trim()) === apiBase; + + const company = + opts.company?.trim() || + opts.companyId?.trim() || + process.env.PAPERCLIP_COMPANY_ID?.trim() || + storedProfile?.companyId?.trim() || + (repoLocalMatchesApiBase ? repoLocal?.companyId?.trim() || repoLocal?.company?.trim() : undefined) || + (contextMatchesApiBase ? contextProfile.companyId?.trim() : undefined) || + undefined; + + const buildHeaders = (initHeaders?: HeadersInit): Headers => { + const headers = new Headers(initHeaders); + if (apiKey && !headers.has("authorization")) { + headers.set("authorization", `Bearer ${apiKey}`); + } + if (profile && !storedProfile?.apiKey && !headers.has("x-paperclip-actor-profile")) { + headers.set("x-paperclip-actor-profile", profile); + } + return headers; + }; + + const requestJson = async (reqPath: string, init: RequestInit = {}): Promise => { + const url = `${apiBase}${reqPath.startsWith("/") ? reqPath : `/${reqPath}`}`; + const headers = buildHeaders(init.headers); + if (init.body !== undefined && typeof init.body === "string" && !headers.has("content-type")) { + headers.set("content-type", "application/json"); + } + if (!headers.has("accept")) { + headers.set("accept", "application/json"); + } + const res = await fetch(url, { ...init, headers }); + if (!res.ok) { + throw await parseFetchError(res); + } + if (res.status === 204) { + return null as T; + } + return (await res.json()) as T; + }; + + let cachedCompanyId: string | null = null; + const resolveCompanyId = async (): Promise => { + if (cachedCompanyId) return cachedCompanyId; + if (company && UUID_RE.test(company)) { + cachedCompanyId = company.toLowerCase(); + return cachedCompanyId; + } + const qs = company ? `?company=${encodeURIComponent(company)}` : ""; + const resolved = await requestJson(`/api/companies/resolve-default${qs}`, { + method: "GET", + }); + cachedCompanyId = resolved.id; + return resolved.id; + }; + + const uploadIssueAttachments = async ( + resolvedCompanyId: string, + issueId: string, + files: string[], + ): Promise => { + const uploaded: unknown[] = []; + for (const filePath of files) { + const resolvedPath = path.resolve(filePath); + const bytes = fs.readFileSync(resolvedPath); + const form = new FormData(); + const mimeType = inferContentTypeFromPath(resolvedPath) ?? "application/octet-stream"; + form.set("file", new Blob([bytes], { type: mimeType }), path.basename(resolvedPath)); + const url = `${apiBase}/api/companies/${encodeURIComponent(resolvedCompanyId)}/issues/${encodeURIComponent(issueId)}/attachments`; + const headers = buildHeaders(); + const res = await fetch(url, { + method: "POST", + headers, + body: form, + }); + if (!res.ok) { + throw await parseFetchError(res); + } + uploaded.push(await res.json()); + } + return uploaded; + }; + + // Pass a non-existent homeDir only when storedProfile wasn't used, or pass explicit apiKey/profile: + // Note: when storedProfile?.apiKey was found in store.ts, we already placed it in apiKey above! + const client = paperclip({ + apiBase, + apiKey, + company, + profile: storedProfile?.apiKey ? null : profile, + }); + + return { + client, + apiBase, + apiKey, + company, + profile, + quiet: Boolean(opts.quiet), + json: Boolean(opts.json), + resolveCompanyId, + requestJson, + uploadIssueAttachments, + }; +} + +export function isScriptOutput(opts: { quiet?: boolean; json?: boolean }): boolean { + return !opts.json && (Boolean(opts.quiet) || !process.stdout.isTTY); +} + +export function handleBoardError(error: unknown, opts: { json?: boolean } = {}): never { + let code = "cli_error"; + let message = error instanceof Error ? error.message : String(error); + let next: string[] | undefined; + + if (error instanceof PaperclipError) { + code = error.code; + message = error.message; + next = error.next; + } else if (error instanceof ApiRequestError) { + code = `http_${error.status}`; + message = error.message; + } + + if (opts.json) { + console.error( + JSON.stringify({ + error: code, + message, + ...(next && next.length > 0 ? { next } : {}), + }), + ); + process.exit(1); + } + + console.error(pc.red(`Error (${code}): ${message}`)); + if (next && next.length > 0) { + for (const suggestion of next) { + console.error(pc.dim(` next: ${suggestion}`)); + } + } + process.exit(1); +} diff --git a/cli/src/commands/board/events.ts b/cli/src/commands/board/events.ts new file mode 100644 index 00000000000..c8e3dcc630e --- /dev/null +++ b/cli/src/commands/board/events.ts @@ -0,0 +1,305 @@ +import pc from "picocolors"; +import type { Command } from "commander"; +import type { BoardEventType, BoardEventView } from "@paperclipai/shared/sdk"; +import { + addBoardClientOptions, + collectOption, + handleBoardError, + isScriptOutput, + resolveBoardClient, + splitCsvValues, + type BoardCommonOptions, +} from "./client.js"; + +const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const ISSUE_ID_RE = /^[A-Z][A-Z0-9]*-\d+$/i; + +interface ScheduleOptions extends BoardCommonOptions { + in?: string; + at?: string; + every?: string; + until?: string; + post?: boolean; + target?: string; +} + +interface SchedulesListOptions extends BoardCommonOptions { + target?: string; +} + +interface TailOptions extends BoardCommonOptions { + event?: string[]; + label?: string[]; + mentions?: string | boolean; + after?: string; +} + +interface WaitOptions extends TailOptions { + timeout?: string; +} + +function isIssueRef(target: string): boolean { + const trimmed = target.trim(); + return UUID_RE.test(trimmed) || ISSUE_ID_RE.test(trimmed); +} + +function formatEventLine(evt: BoardEventView): string { + const where = evt.identifier ?? (evt.channel ? `#${evt.channel}` : evt.companyId.slice(0, 8)); + const actor = evt.actor.profile ?? evt.actor.name ?? evt.actor.type; + return `${pc.dim(`[${evt.cursor}]`)} ${pc.cyan(evt.type)} ${where} ${pc.dim(`by ${actor}`)}`; +} + +async function runSchedulesList(opts: SchedulesListOptions): Promise { + const resolved = resolveBoardClient(opts); + const list = await resolved.client.schedules.list( + opts.target ? { target: opts.target } : undefined, + ); + if (resolved.json) { + console.log(JSON.stringify(list, null, 2)); + return; + } + if (list.length === 0) { + console.log(pc.dim("(no schedules)")); + return; + } + for (const item of list) { + console.log( + ` ${pc.cyan(item.id)} [${item.status}] ${item.target} next=${item.nextRunAt} ${item.message}`, + ); + } +} + +async function runScheduleCancel(id: string, opts: BoardCommonOptions): Promise { + const resolved = resolveBoardClient(opts); + const res = await resolved.client.schedules.cancel(id); + if (resolved.json) { + console.log(JSON.stringify(res, null, 2)); + return; + } + console.log(`${pc.yellow("Cancelled")} schedule ${id}`); +} + +export function registerBoardEventCommands(program: Command): void { + addBoardClientOptions( + program + .command("schedule") + .description("Schedule a delayed/recurring board post or task monitor wakeup (or 'list' / 'cancel ')") + .argument("[args...]", " , or 'list' / 'cancel '") + .option("--in ", "Relative delay (e.g. 5m, 2h)") + .option("--at ", "Absolute ISO-8601 timestamp") + .option("--every ", "Recurring interval (e.g. 1d, 30m)") + .option("--until ", "End ISO-8601 timestamp for recurring schedules") + .option("--post", "Post as a message rather than only a monitor wakeup") + .option("--target ", "Filter target when listing schedules") + .action(async (args: string[], opts: ScheduleOptions) => { + try { + const hasScheduleTiming = Boolean(opts.in || opts.at || opts.every); + if (args.length === 0 || (args[0] === "list" && !hasScheduleTiming)) { + await runSchedulesList({ + ...opts, + target: opts.target ?? args[1], + }); + return; + } + if (args[0] === "cancel" && !hasScheduleTiming) { + const scheduleId = args[1]?.trim(); + if (!scheduleId) { + throw new Error("Usage: pc schedule cancel "); + } + await runScheduleCancel(scheduleId, opts); + return; + } + + const target = args[0]?.trim(); + const message = args.slice(1).join(" ").trim(); + if (!target || !message) { + throw new Error( + "Usage: pc schedule --in |--at |--every (or 'pc schedule list' / 'pc schedule cancel ')", + ); + } + + const resolved = resolveBoardClient(opts); + const created = await resolved.client.schedule(target, { + message, + ...(opts.in !== undefined ? { in: opts.in } : {}), + ...(opts.at !== undefined ? { at: opts.at } : {}), + ...(opts.every !== undefined ? { every: opts.every } : {}), + ...(opts.until !== undefined ? { until: opts.until } : {}), + ...(opts.post ? { post: true } : {}), + }); + if (resolved.json) { + console.log(JSON.stringify(created, null, 2)); + return; + } + if (isScriptOutput(resolved)) { + console.log(created.id); + return; + } + const cursorSuffix = created.cursor ? `, cursor=${created.cursor}` : ""; + console.log( + `${pc.green("Scheduled")} ${pc.cyan(created.id)} on ${created.target} (nextRunAt=${created.nextRunAt}${cursorSuffix})`, + ); + } catch (err) { + handleBoardError(err, opts); + } + }), + ); + + const schedules = addBoardClientOptions( + program + .command("schedules") + .description("List and cancel board schedules") + .option("--target ", "Filter by target channel or issue") + .action(async (opts: SchedulesListOptions) => { + try { + await runSchedulesList(opts); + } catch (err) { + handleBoardError(err, opts); + } + }), + ); + + addBoardClientOptions( + schedules + .command("list") + .description("List scheduled posts and monitors") + .option("--target ", "Filter by target channel or issue") + .action(async (opts: SchedulesListOptions) => { + try { + await runSchedulesList(opts); + } catch (err) { + handleBoardError(err, opts); + } + }), + ); + + addBoardClientOptions( + schedules + .command("cancel") + .description("Cancel a scheduled post or monitor") + .argument("", "Schedule ID") + .action(async (id: string, opts: BoardCommonOptions) => { + try { + await runScheduleCancel(id, opts); + } catch (err) { + handleBoardError(err, opts); + } + }), + ); + + addBoardClientOptions( + program + .command("tail") + .description("Stream live board events over SSE until interrupted") + .argument("[target]", "Optional channel path or issue identifier/UUID") + .option("--event ", "Filter by event type(s)", collectOption, []) + .option("--label ", "Filter by label expression (repeatable)", collectOption, []) + .option("--mentions [handle]", "Filter for mentions of handle (or active profile)") + .option("--after ", "Replay events after cursor (evt_0 for all history; defaults to live from now)") + .action(async (target: string | undefined, opts: TailOptions) => { + const ac = new AbortController(); + const onSig = () => ac.abort(); + process.once("SIGINT", onSig); + process.once("SIGTERM", onSig); + try { + const resolved = resolveBoardClient(opts); + const eventTypes = splitCsvValues(opts.event) as BoardEventType[]; + const mentionsHandle = + typeof opts.mentions === "string" + ? opts.mentions + : opts.mentions === true + ? resolved.profile ?? "@me" + : undefined; + + const filters = { + ...(target + ? isIssueRef(target) + ? { issueId: target } + : { channel: target } + : {}), + ...(eventTypes.length > 0 ? { event: eventTypes } : {}), + ...(opts.label && opts.label.length > 0 ? { label: opts.label } : {}), + ...(mentionsHandle ? { mentions: mentionsHandle } : {}), + ...(opts.after ? { after: opts.after } : {}), + }; + + for await (const evt of resolved.client.events(filters, { signal: ac.signal })) { + if (resolved.json) { + console.log(JSON.stringify(evt)); + } else { + console.log(formatEventLine(evt)); + } + } + } catch (err) { + if (!ac.signal.aborted) { + handleBoardError(err, opts); + } + } finally { + process.removeListener("SIGINT", onSig); + process.removeListener("SIGTERM", onSig); + } + }), + ); + + addBoardClientOptions( + program + .command("wait") + .description("Block until a matching board event arrives (with cursor replay)") + .argument("[target]", "Optional channel path or issue identifier/UUID") + .option("--event ", "Filter by event type(s)", collectOption, []) + .option("--label ", "Filter by label expression (repeatable)", collectOption, []) + .option("--mentions [handle]", "Filter for mentions of handle (or active profile)") + .option("--after ", "Replay events after cursor (evt_0 for all history; defaults to live from now)") + .option("--timeout ", "Maximum wait duration (e.g. 30m, 10s)", "30m") + .action(async (target: string | undefined, opts: WaitOptions) => { + let timedOut = false; + try { + const resolved = resolveBoardClient(opts); + const eventTypes = splitCsvValues(opts.event) as BoardEventType[]; + const mentionsHandle = + typeof opts.mentions === "string" + ? opts.mentions + : opts.mentions === true + ? resolved.profile ?? "@me" + : undefined; + + const evt = await resolved.client.wait( + target, + { + ...(eventTypes.length > 0 ? { event: eventTypes } : {}), + ...(opts.label && opts.label.length > 0 ? { label: opts.label } : {}), + ...(mentionsHandle ? { mentions: mentionsHandle } : {}), + ...(opts.after ? { after: opts.after } : {}), + ...(opts.timeout ? { timeout: opts.timeout } : {}), + }, + ); + + if (!evt) { + if (resolved.json) { + console.error( + JSON.stringify({ + error: "timeout", + reason: "timeout", + message: "Timed out waiting for matching board event", + }), + ); + } else { + console.error(pc.yellow("Timed out waiting for matching board event.")); + } + timedOut = true; + } else if (resolved.json) { + console.log(JSON.stringify(evt, null, 2)); + } else if (isScriptOutput(resolved)) { + console.log(evt.cursor); + } else { + console.log(formatEventLine(evt)); + } + } catch (err) { + handleBoardError(err, opts); + } + if (timedOut) { + process.exit(1); + } + }), + ); +} diff --git a/cli/src/commands/board/index.ts b/cli/src/commands/board/index.ts new file mode 100644 index 00000000000..9ac1dd49232 --- /dev/null +++ b/cli/src/commands/board/index.ts @@ -0,0 +1,14 @@ +import type { Command } from "commander"; +import { registerBoardChannelCommands } from "./channels.js"; +import { registerBoardEventCommands } from "./events.js"; +import { registerBoardInteractionCommands } from "./interactions.js"; +import { registerBoardSchemaCommands } from "./schemas.js"; +import { registerBoardTaskCommands } from "./tasks.js"; + +export function registerBoardCommands(program: Command): void { + registerBoardChannelCommands(program); + registerBoardTaskCommands(program); + registerBoardInteractionCommands(program); + registerBoardSchemaCommands(program); + registerBoardEventCommands(program); +} diff --git a/cli/src/commands/board/interactions.ts b/cli/src/commands/board/interactions.ts new file mode 100644 index 00000000000..8f380d52166 --- /dev/null +++ b/cli/src/commands/board/interactions.ts @@ -0,0 +1,199 @@ +import pc from "picocolors"; +import type { Command } from "commander"; +import { + addBoardClientOptions, + collectOption, + handleBoardError, + isScriptOutput, + resolveBoardClient, + splitCsvValues, + type BoardCommonOptions, +} from "./client.js"; +import { deleteClaimRecord, resolveClaimCredentials } from "./store.js"; + +interface AskOptions extends BoardCommonOptions { + choice?: string[]; + choices?: string[]; + human?: boolean; + humanOnly?: boolean; + agent?: string; +} + +interface ConfirmOptions extends BoardCommonOptions { + human?: boolean; + humanOnly?: boolean; + wakeOnAccept?: boolean; +} + +interface ApproveOptions extends BoardCommonOptions { + answer?: string; + note?: string; + interactionId?: string; +} + +interface RejectOptions extends BoardCommonOptions { + reason?: string; + note?: string; + interactionId?: string; +} + +export function registerBoardInteractionCommands(program: Command): void { + addBoardClientOptions( + program + .command("ask") + .description("Ask a question on a thread/task (moves to blocked and releases pool lease)") + .argument("", "Issue identifier (e.g. PAP-14) or UUID") + .argument("", "Question prompt") + .option("--choices ", "Comma-separated answer choices (repeatable)", collectOption, []) + .option("--choice ", "Alias for --choices", collectOption, []) + .option("--human-only", "Require human resolution (resolverPolicy=human_only)") + .option("--human", "Alias for --human-only") + .option("--agent ", "Target agent ID or handle") + .action(async (id: string, question: string, opts: AskOptions) => { + try { + const resolved = resolveBoardClient(opts); + const companyId = await resolved.resolveCompanyId(); + const claim = resolveClaimCredentials({ + companyId, + issueRef: id, + activeProfile: resolved.profile, + requireClaim: false, + }); + const mergedChoices = splitCsvValues([...(opts.choices ?? []), ...(opts.choice ?? [])]); + const humanOnly = Boolean(opts.humanOnly || opts.human); + const interaction = await resolved.client.ask(id, question, { + ...(mergedChoices.length > 0 ? { choices: mergedChoices } : {}), + ...(humanOnly ? { humanOnly: true } : {}), + ...(opts.agent ? { agent: opts.agent } : {}), + ...(claim ? { claimToken: claim.claimToken } : {}), + }); + if (claim?.source === "store") { + deleteClaimRecord(companyId, id); + } + + if (resolved.json) { + console.log(JSON.stringify(interaction, null, 2)); + return; + } + if (isScriptOutput(resolved)) { + console.log(interaction.id); + return; + } + console.log( + `${pc.cyan(interaction.identifier)} asked (${interaction.id}) ${pc.dim(`status=${interaction.status}`)}`, + ); + } catch (err) { + handleBoardError(err, opts); + } + }), + ); + + addBoardClientOptions( + program + .command("confirm") + .description("Request confirmation on a thread/task (moves to blocked and releases pool lease)") + .argument("", "Issue identifier (e.g. PAP-14) or UUID") + .argument("", "Confirmation prompt") + .option("--human-only", "Require human resolution (resolverPolicy=human_only)") + .option("--human", "Alias for --human-only") + .option("--wake-on-accept", "Wake assignee when accepted") + .action(async (id: string, prompt: string, opts: ConfirmOptions) => { + try { + const resolved = resolveBoardClient(opts); + const companyId = await resolved.resolveCompanyId(); + const claim = resolveClaimCredentials({ + companyId, + issueRef: id, + activeProfile: resolved.profile, + requireClaim: false, + }); + const humanOnly = Boolean(opts.humanOnly || opts.human); + const interaction = await resolved.client.confirm(id, prompt, { + ...(humanOnly ? { humanOnly: true } : {}), + ...(opts.wakeOnAccept ? { wakeOnAccept: true } : {}), + ...(claim ? { claimToken: claim.claimToken } : {}), + }); + if (claim?.source === "store") { + deleteClaimRecord(companyId, id); + } + + if (resolved.json) { + console.log(JSON.stringify(interaction, null, 2)); + return; + } + if (isScriptOutput(resolved)) { + console.log(interaction.id); + return; + } + console.log( + `${pc.cyan(interaction.identifier)} confirmation (${interaction.id}) ${pc.dim(`status=${interaction.status}`)}`, + ); + } catch (err) { + handleBoardError(err, opts); + } + }), + ); + + addBoardClientOptions( + program + .command("approve") + .description("Approve or answer a pending confirmation or question on an issue") + .argument("", "Issue identifier (e.g. PAP-14) or UUID") + .argument("[answer...]", "Optional answer or approval note") + .option("--answer ", "Answer text for a pending question") + .option("--note ", "Optional approval note") + .option("--interaction-id ", "Specific interaction ID to resolve") + .action(async (id: string, answerParts: string[], opts: ApproveOptions) => { + try { + const resolved = resolveBoardClient(opts); + const positional = answerParts.length > 0 ? answerParts.join(" ") : undefined; + const answer = opts.answer ?? positional; + const interaction = await resolved.client.approve(id, { + ...(answer !== undefined ? { answer } : {}), + ...(opts.note !== undefined ? { note: opts.note } : {}), + ...(opts.interactionId ? { interactionId: opts.interactionId } : {}), + }); + if (resolved.json) { + console.log(JSON.stringify(interaction, null, 2)); + return; + } + console.log( + `${pc.green("Approved")} ${pc.cyan(interaction.identifier)} (${interaction.id})`, + ); + } catch (err) { + handleBoardError(err, opts); + } + }), + ); + + addBoardClientOptions( + program + .command("reject") + .description("Reject a pending confirmation or question on an issue") + .argument("", "Issue identifier (e.g. PAP-14) or UUID") + .argument("[reason...]", "Optional rejection reason") + .option("--reason ", "Rejection reason") + .option("--note ", "Alias for --reason") + .option("--interaction-id ", "Specific interaction ID to resolve") + .action(async (id: string, reasonParts: string[], opts: RejectOptions) => { + try { + const resolved = resolveBoardClient(opts); + const positional = reasonParts.length > 0 ? reasonParts.join(" ") : undefined; + const reason = opts.reason ?? opts.note ?? positional; + const interaction = await resolved.client.reject(id, { + ...(reason !== undefined ? { reason } : {}), + ...(opts.interactionId ? { interactionId: opts.interactionId } : {}), + }); + if (resolved.json) { + console.log(JSON.stringify(interaction, null, 2)); + return; + } + console.log( + `${pc.yellow("Rejected")} ${pc.cyan(interaction.identifier)} (${interaction.id})`, + ); + } catch (err) { + handleBoardError(err, opts); + } + }), + ); +} diff --git a/cli/src/commands/board/schemas.ts b/cli/src/commands/board/schemas.ts new file mode 100644 index 00000000000..929bdbd7a34 --- /dev/null +++ b/cli/src/commands/board/schemas.ts @@ -0,0 +1,132 @@ +import pc from "picocolors"; +import type { Command } from "commander"; +import { + addBoardClientOptions, + handleBoardError, + isScriptOutput, + parseJsonArg, + readTextInput, + resolveBoardClient, + type BoardCommonOptions, +} from "./client.js"; + +interface SchemaCreateOptions extends BoardCommonOptions { + file?: string; + data?: string; + schema?: string; + version?: string; + description?: string; +} + +async function runSchemasList(opts: BoardCommonOptions): Promise { + try { + const resolved = resolveBoardClient(opts); + const items = await resolved.client.schemas.list(); + if (resolved.json) { + console.log(JSON.stringify(items, null, 2)); + return; + } + if (items.length === 0) { + console.log(pc.dim("(no schemas)")); + return; + } + for (const item of items) { + const origin = item.builtIn ? pc.dim(" [built-in]") : ""; + const desc = item.description ? pc.dim(` — ${item.description}`) : ""; + console.log(` ${pc.cyan(item.ref)}${origin}${desc}`); + } + } catch (err) { + handleBoardError(err, opts); + } +} + +export function registerBoardSchemaCommands(program: Command): void { + const schemas = addBoardClientOptions( + program + .command("schemas") + .description("List, inspect, and register versioned JSON schemas") + .action(async (opts: BoardCommonOptions) => { + await runSchemasList(opts); + }), + ); + + addBoardClientOptions( + schemas + .command("list") + .description("List available schemas for the company") + .action(async (opts: BoardCommonOptions) => { + await runSchemasList(opts); + }), + ); + + addBoardClientOptions( + schemas + .command("inspect") + .alias("get") + .description("Inspect a schema definition by @") + .argument("", "Schema reference (e.g. finding@1)") + .action(async (ref: string, opts: BoardCommonOptions) => { + try { + const resolved = resolveBoardClient(opts); + const schema = await resolved.client.schemas.get(ref); + if (resolved.json) { + console.log(JSON.stringify(schema, null, 2)); + return; + } + console.log(pc.cyan(pc.bold(schema.ref)) + (schema.builtIn ? pc.dim(" [built-in]") : "")); + if (schema.description) console.log(pc.dim(schema.description)); + console.log(JSON.stringify(schema.jsonSchema, null, 2)); + } catch (err) { + handleBoardError(err, opts); + } + }), + ); + + addBoardClientOptions( + schemas + .command("create") + .description("Register an immutable schema version (@)") + .argument("", "Schema reference (@ or with --version)") + .option("--version ", "Schema version number when omitted from ") + .option("--file ", "Path to JSON schema file or '-' for stdin") + .option("--data ", "Inline JSON schema object") + .option("--schema ", "Alias for --data ''") + .option("--description ", "Schema description") + .action(async (rawRef: string, opts: SchemaCreateOptions) => { + try { + const resolved = resolveBoardClient(opts); + const trimmedRef = rawRef.trim(); + const effectiveRef = trimmedRef.includes("@") + ? trimmedRef + : opts.version + ? `${trimmedRef}@${opts.version.trim()}` + : trimmedRef; + const rawJson = opts.data ?? opts.schema ?? readTextInput(undefined, opts.file); + if (!rawJson) { + throw new Error("Provide a JSON schema via --schema '', --data '', or --file ."); + } + const parsed = parseJsonArg(rawJson, "JSON schema"); + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { + throw new Error("Schema definition must be a JSON object."); + } + const result = await resolved.client.schemas.create({ + ref: effectiveRef, + jsonSchema: parsed as Record, + ...(opts.description !== undefined ? { description: opts.description } : {}), + }); + if (resolved.json) { + console.log(JSON.stringify(result, null, 2)); + return; + } + if (isScriptOutput(resolved)) { + console.log(result.schema.ref); + return; + } + const verb = result.created ? "Registered" : "Already registered (identical)"; + console.log(`${pc.green(verb)} ${pc.cyan(result.schema.ref)}`); + } catch (err) { + handleBoardError(err, opts); + } + }), + ); +} diff --git a/cli/src/commands/board/store.ts b/cli/src/commands/board/store.ts new file mode 100644 index 00000000000..9eed257829c --- /dev/null +++ b/cli/src/commands/board/store.ts @@ -0,0 +1,283 @@ +import fs from "node:fs"; +import path from "node:path"; +import { PaperclipError } from "@paperclipai/shared/sdk"; +import { resolvePaperclipHomeDir } from "../../config/home.js"; +import { detectGitWorkspaceInfo } from "../git-workspace.js"; + +function resolveEffectiveStoreHome(homeDir?: string): string { + if (homeDir) return homeDir; + if (process.env.PAPERCLIP_HOME?.trim()) { + return resolvePaperclipHomeDir(); + } + const git = detectGitWorkspaceInfo(process.cwd()); + const roots = Array.from(new Set([...(git ? [git.root] : []), path.resolve(process.cwd())])); + for (const root of roots) { + const localPaperclipDir = path.join(root, ".paperclip"); + if (fs.existsSync(path.join(localPaperclipDir, "context.json"))) { + return localPaperclipDir; + } + } + return resolvePaperclipHomeDir(); +} + +export interface StoredAgentProfileRecord { + agentId: string; + agentName: string; + companyId: string; + apiBase: string; + apiKey: string; + role?: string; + createdAt?: string; + updatedAt?: string; +} + +export interface StoredClaimRecord { + companyId: string; + issueId: string; + identifier: string; + claimToken: string; + claimEpoch: number; + leaseExpiresAt: string; + profile: string | null; + updatedAt: string; +} + +export interface ResolvedClaimCredentials { + claimToken: string; + claimEpoch?: number; + issueId?: string; + identifier?: string; + source: "env" | "store"; +} + +function sanitizeSegment(raw: string, label: string): string { + const trimmed = raw.trim(); + const safe = trimmed.replace(/[^a-zA-Z0-9._-]/g, ""); + if (!safe || safe === "." || safe === ".." || safe !== trimmed) { + throw new Error(`Invalid ${label} "${raw}" for local credential storage.`); + } + return safe; +} + +function sanitizeFilename(raw: string): string { + const safe = raw.trim().replace(/[^a-zA-Z0-9._-]/g, "_"); + if (!safe || safe === "." || safe === "..") { + throw new Error(`Invalid identifier "${raw}" for local storage.`); + } + return safe; +} + +function writeSecureJson(filePath: string, data: unknown): void { + fs.mkdirSync(path.dirname(filePath), { recursive: true }); + fs.writeFileSync(filePath, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 }); + try { + fs.chmodSync(filePath, 0o600); + } catch { + // Best-effort on non-POSIX filesystems + } +} + +function readJsonOrNull(filePath: string): T | null { + if (!fs.existsSync(filePath)) return null; + try { + const raw = fs.readFileSync(filePath, "utf8"); + const parsed = JSON.parse(raw) as unknown; + return typeof parsed === "object" && parsed !== null ? (parsed as T) : null; + } catch { + return null; + } +} + +export function resolveProfileStorePath(profileName: string, homeDir?: string): string { + const baseHome = resolveEffectiveStoreHome(homeDir); + const safeName = sanitizeSegment(profileName, "profile name"); + return path.join(baseHome, "profiles", `${safeName}.json`); +} + +export function readProfileRecord( + profileName: string, + homeDir?: string, +): StoredAgentProfileRecord | null { + try { + const filePath = resolveProfileStorePath(profileName, homeDir); + const parsed = readJsonOrNull>(filePath); + if (!parsed) return null; + const apiKey = + (typeof parsed.apiKey === "string" && parsed.apiKey) || + ((parsed as Record).agent_api_key as string | undefined) || + ((parsed as Record).agentApiKey as string | undefined); + if (!apiKey) return null; + return { + agentId: typeof parsed.agentId === "string" ? parsed.agentId : "", + agentName: typeof parsed.agentName === "string" ? parsed.agentName : profileName, + companyId: typeof parsed.companyId === "string" ? parsed.companyId : "", + apiBase: typeof parsed.apiBase === "string" ? parsed.apiBase : "", + apiKey, + ...(typeof parsed.role === "string" ? { role: parsed.role } : {}), + ...(typeof parsed.createdAt === "string" ? { createdAt: parsed.createdAt } : {}), + ...(typeof parsed.updatedAt === "string" ? { updatedAt: parsed.updatedAt } : {}), + }; + } catch { + return null; + } +} + +export function writeProfileRecord( + profileName: string, + record: StoredAgentProfileRecord, + homeDir?: string, +): string { + const filePath = resolveProfileStorePath(profileName, homeDir); + const now = new Date().toISOString(); + writeSecureJson(filePath, { + ...record, + createdAt: record.createdAt ?? now, + updatedAt: now, + }); + return filePath; +} + +export function resolveClaimsCompanyDir(companyId: string, homeDir?: string): string { + const baseHome = resolveEffectiveStoreHome(homeDir); + return path.join(baseHome, "claims", sanitizeFilename(companyId)); +} + +export function resolveClaimFilePath( + companyId: string, + issueId: string, + homeDir?: string, +): string { + return path.join(resolveClaimsCompanyDir(companyId, homeDir), `${sanitizeFilename(issueId)}.json`); +} + +export function saveClaimRecord(record: StoredClaimRecord, homeDir?: string): string { + const filePath = resolveClaimFilePath(record.companyId, record.issueId, homeDir); + writeSecureJson(filePath, record); + return filePath; +} + +export function findClaimRecord( + companyId: string, + issueRef: string, + homeDir?: string, +): StoredClaimRecord | null { + const trimmed = issueRef.trim(); + if (!trimmed) return null; + + const directPath = resolveClaimFilePath(companyId, trimmed, homeDir); + const direct = readJsonOrNull(directPath); + if (direct && typeof direct.claimToken === "string") { + return direct; + } + + const dir = resolveClaimsCompanyDir(companyId, homeDir); + if (!fs.existsSync(dir)) return null; + + const upper = trimmed.toUpperCase(); + for (const entry of fs.readdirSync(dir)) { + if (!entry.endsWith(".json")) continue; + const candidate = readJsonOrNull(path.join(dir, entry)); + if (!candidate || typeof candidate.claimToken !== "string") continue; + if ( + candidate.issueId === trimmed || + candidate.identifier?.toUpperCase() === upper + ) { + return candidate; + } + } + return null; +} + +export function deleteClaimRecord( + companyId: string, + issueRef: string, + homeDir?: string, +): boolean { + const existing = findClaimRecord(companyId, issueRef, homeDir); + if (!existing) return false; + const filePath = resolveClaimFilePath(companyId, existing.issueId, homeDir); + try { + fs.unlinkSync(filePath); + return true; + } catch { + return false; + } +} + +export function resolveClaimCredentials(input: { + companyId: string; + issueRef: string; + activeProfile: string | null; + requireClaim: boolean; + homeDir?: string; +}): ResolvedClaimCredentials | null { + const envToken = process.env.PAPERCLIP_CLAIM_TOKEN?.trim(); + const envTaskId = process.env.PAPERCLIP_TASK_ID?.trim(); + const envIssueUuid = process.env.PAPERCLIP_ISSUE_UUID?.trim(); + const envProfile = process.env.PAPERCLIP_PROFILE?.trim() || null; + + if (envToken) { + const refUpper = input.issueRef.trim().toUpperCase(); + const matchesEnvTarget = + (!envTaskId && !envIssueUuid) || + envTaskId?.toUpperCase() === refUpper || + envIssueUuid?.toLowerCase() === input.issueRef.trim().toLowerCase(); + + if (matchesEnvTarget) { + if (envProfile !== null && (input.activeProfile ?? null) !== envProfile) { + throw new PaperclipError({ + status: 409, + code: "claim_not_held", + message: `Task "${input.issueRef}" claim in environment belongs to profile "${envProfile}", not "${input.activeProfile ?? "default"}"`, + next: [`Retry with --as ${envProfile}`], + }); + } + const rawEpoch = process.env.PAPERCLIP_CLAIM_EPOCH?.trim(); + const parsedEpoch = + rawEpoch !== undefined && /^\d+$/.test(rawEpoch) + ? Number.parseInt(rawEpoch, 10) + : undefined; + return { + claimToken: envToken, + ...(parsedEpoch !== undefined ? { claimEpoch: parsedEpoch } : {}), + ...(envIssueUuid ? { issueId: envIssueUuid } : {}), + ...(envTaskId ? { identifier: envTaskId } : {}), + source: "env", + }; + } + } + + const stored = findClaimRecord(input.companyId, input.issueRef, input.homeDir); + if (stored) { + const heldProfile = stored.profile ?? null; + const callerProfile = input.activeProfile ?? null; + if (heldProfile !== callerProfile) { + throw new PaperclipError({ + status: 409, + code: "claim_not_held", + message: `Task "${input.issueRef}" is claimed locally by profile "${heldProfile ?? "(none)"}", not "${callerProfile ?? "(none)"}"`, + next: heldProfile + ? [`pc tasks complete ${input.issueRef} --as ${heldProfile}`] + : [`pc tasks claim ${input.issueRef}${callerProfile ? ` --as ${callerProfile}` : ""}`], + }); + } + return { + claimToken: stored.claimToken, + claimEpoch: stored.claimEpoch, + issueId: stored.issueId, + identifier: stored.identifier, + source: "store", + }; + } + + if (input.requireClaim) { + throw new PaperclipError({ + status: 409, + code: "claim_not_held", + message: `No active local claim held for task "${input.issueRef}"`, + next: [`pc tasks claim ${input.issueRef}${input.activeProfile ? ` --as ${input.activeProfile}` : ""}`], + }); + } + + return null; +} diff --git a/cli/src/commands/board/tasks.ts b/cli/src/commands/board/tasks.ts new file mode 100644 index 00000000000..d32146a0f67 --- /dev/null +++ b/cli/src/commands/board/tasks.ts @@ -0,0 +1,1205 @@ +import { spawn, type ChildProcess } from "node:child_process"; +import pc from "picocolors"; +import type { Command } from "commander"; +import { ISSUE_PRIORITIES, type IssuePriority, type IssueStatus } from "@paperclipai/shared"; +import { + CHANNEL_PATH_REGEX, + parseDurationMs, + PaperclipError, + type BatchCreateIssuesResult, + type HeadlessIssueView, + type PlanTaskInput, + type TaskClaimView, + type ThreadDetailView, +} from "@paperclipai/shared/sdk"; +import { + addBoardClientOptions, + collectOption, + handleBoardError, + isScriptOutput, + parseJsonArg, + parseLabelsList, + readTextInput, + resolveBoardClient, + splitCsvValues, + type BoardCommonOptions, + type ResolvedBoardClient, +} from "./client.js"; +import { + deleteClaimRecord, + findClaimRecord, + resolveClaimCredentials, + saveClaimRecord, +} from "./store.js"; + +const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const ISSUE_ID_RE = /^[A-Z][A-Z0-9]*-\d+$/i; + +interface TasksListOptions extends BoardCommonOptions { + state?: string[]; + status?: string[]; + label?: string[]; + assignee?: string; + project?: string; + ready?: boolean; + channel?: string; + limit?: number; +} + +interface TasksCreateOptions extends BoardCommonOptions { + title?: string; + project?: string; + file?: string; + needs?: string[]; + for?: string; + priority?: string; + label?: string[]; + board?: boolean; + resultSchema?: string; + claim?: boolean; + idempotencyKey?: string; +} + +interface TasksClaimOptions extends BoardCommonOptions { + ready?: string | boolean; + channel?: string; + label?: string[]; + project?: string; + lease?: string; + wait?: string; + includeUntrusted?: boolean; +} + +interface TasksRunOptions extends TasksClaimOptions { + result?: string; + requeueOnError?: boolean; +} + +interface TasksRenewOptions extends BoardCommonOptions { + lease?: string; +} + +interface TasksReleaseOptions extends BoardCommonOptions { + comment?: string; + message?: string; +} + +interface TasksCompleteOptions extends BoardCommonOptions { + message?: string; + comment?: string; + data?: string; + pr?: string; + attach?: string[]; + resultSchema?: string; +} + +interface TasksFailOptions extends BoardCommonOptions { + reason?: string; + message?: string; + requeue?: boolean; +} + +interface TasksBlockOptions extends BoardCommonOptions { + reason?: string; + message?: string; +} + +function isIssueRef(value: string): boolean { + const trimmed = value.trim(); + return UUID_RE.test(trimmed) || ISSUE_ID_RE.test(trimmed); +} + +function isValidChannelRef(value: string): boolean { + const trimmed = value.trim().replace(/^#/, "").toLowerCase(); + return CHANNEL_PATH_REGEX.test(trimmed); +} + +function validatePriority(raw?: string): IssuePriority | undefined { + if (!raw) return undefined; + if (!ISSUE_PRIORITIES.includes(raw as IssuePriority)) { + throw new Error(`Invalid priority "${raw}": expected one of ${ISSUE_PRIORITIES.join(", ")}`); + } + return raw as IssuePriority; +} + +function parsePlanJsonPayload(rawText: string): { + isPlan: true; + channel?: string; + projectId?: string | null; + board?: boolean; + idempotencyKey?: string; + tasks: PlanTaskInput[]; +} | { isPlan: false } { + const trimmed = rawText.trim(); + if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) { + return { isPlan: false }; + } + let parsed: unknown; + try { + parsed = JSON.parse(trimmed); + } catch { + return { isPlan: false }; + } + if (Array.isArray(parsed)) { + return { isPlan: true, tasks: parsed as PlanTaskInput[] }; + } + if (typeof parsed === "object" && parsed !== null && Array.isArray((parsed as Record).tasks)) { + const obj = parsed as Record; + return { + isPlan: true, + channel: typeof obj.channel === "string" ? obj.channel : undefined, + projectId: + obj.projectId === null || typeof obj.projectId === "string" + ? (obj.projectId as string | null) + : undefined, + board: typeof obj.board === "boolean" ? obj.board : undefined, + idempotencyKey: typeof obj.idempotencyKey === "string" ? obj.idempotencyKey : undefined, + tasks: obj.tasks as PlanTaskInput[], + }; + } + return { isPlan: false }; +} + +function formatTaskListLine(task: HeadlessIssueView): string { + const ch = task.channel ? `#${task.channel}` : "board"; + const pri = task.priority !== "medium" ? ` (${task.priority})` : ""; + const owner = task.claimHolderProfile + ? `claimed:${task.claimHolderProfile}` + : task.assigneeAgentId + ? `agent:${task.assigneeAgentId.slice(0, 8)}` + : "ready-pool"; + const labelParts = Object.entries(task.kvLabels).map(([k, v]) => `${k}=${v}`); + const labelStr = labelParts.length > 0 ? pc.dim(` [${labelParts.join(" ")}]`) : ""; + return ` ${pc.cyan(task.identifier)} [${task.status}]${pri} ${task.title} ${pc.dim(`(${ch}, ${owner})`)}${labelStr}`; +} + +function getRootRawArgs(cmd: Command): string[] { + let curr: Command | null = cmd; + while (curr?.parent) { + curr = curr.parent; + } + const raw = (curr as (Command & { rawArgs?: string[] }) | null)?.rawArgs; + return Array.isArray(raw) && raw.length > 0 ? raw : process.argv; +} + +export function extractRunArgs( + positionalArgs: string[], + rawArgs: string[], + hasReadyFlag: boolean, +): { id: string | undefined; cmd: string[] } { + const dashDashIdx = rawArgs.indexOf("--"); + if (dashDashIdx !== -1) { + const afterDash = rawArgs.slice(dashDashIdx + 1); + const beforeCount = positionalArgs.length - afterDash.length; + const id = beforeCount > 0 ? positionalArgs[0] : undefined; + return { id, cmd: afterDash }; + } + + if (positionalArgs.length === 0) { + return { id: undefined, cmd: [] }; + } + if (hasReadyFlag) { + return { id: undefined, cmd: positionalArgs }; + } + const [first, ...rest] = positionalArgs; + if (first && isIssueRef(first) && rest.length > 0) { + return { id: first, cmd: rest }; + } + return { id: undefined, cmd: positionalArgs }; +} + +async function performClaim( + resolved: ResolvedBoardClient, + id: string | undefined, + opts: TasksClaimOptions, +) { + const readyChannel = + opts.channel?.trim() || + (typeof opts.ready === "string" ? opts.ready : undefined); + const isPoolClaim = Boolean(opts.ready || opts.channel); + if (!id && !isPoolClaim) { + throw new Error("Specify a task , pass --ready [channel], or pass --channel ."); + } + if (id && isPoolClaim) { + throw new Error("Pass either a specific task or --ready/--channel, not both."); + } + + const claim = await resolved.client.tasks.claim( + id ?? { + ready: true, + ...(readyChannel ? { channel: readyChannel } : {}), + ...(opts.project ? { projectId: opts.project } : {}), + ...(opts.label && opts.label.length > 0 ? { label: opts.label } : {}), + ...(opts.lease ? { lease: opts.lease } : {}), + ...(opts.wait ? { wait: opts.wait } : {}), + ...(opts.includeUntrusted ? { includeUntrusted: true } : {}), + }, + id + ? { + ...(opts.lease ? { lease: opts.lease } : {}), + ...(opts.wait ? { wait: opts.wait } : {}), + } + : undefined, + ); + + if (claim) { + saveClaimRecord({ + companyId: claim.task.companyId, + issueId: claim.task.id, + identifier: claim.task.identifier, + claimToken: claim.claimToken, + claimEpoch: claim.claimEpoch, + leaseExpiresAt: claim.leaseExpiresAt, + profile: resolved.profile, + updatedAt: new Date().toISOString(), + }); + } + return claim; +} + +export interface TasksRunDependencies { + spawnProcess?: typeof spawn; + killGraceMs?: number; +} + +export async function executeTasksRun( + resolved: ResolvedBoardClient, + id: string | undefined, + cmd: string[], + opts: TasksRunOptions, + deps: TasksRunDependencies = {}, +): Promise { + if (cmd.length === 0) { + throw new Error("No command specified. Usage: pc tasks run [id] -- "); + } + + const claimed = await performClaim(resolved, id, opts); + if (!claimed) { + if (resolved.json) { + console.error( + JSON.stringify({ + error: "timeout", + reason: "timeout", + message: "No ready task available before timeout", + }), + ); + } else { + console.error(pc.yellow("No ready task available.")); + } + return 1; + } + + const spawnImpl = deps.spawnProcess ?? spawn; + const killGraceMs = deps.killGraceMs ?? 5_000; + + let currentToken = claimed.claimToken; + let currentEpoch = claimed.claimEpoch; + const grantedLeaseMs = Number.isFinite(Date.parse(claimed.leaseExpiresAt)) + ? Date.parse(claimed.leaseExpiresAt) - Date.now() + : Number.NaN; + const requestedLeaseMs = opts.lease + ? Math.max(100, parseDurationMs(opts.lease)) + : Number.NaN; + const leaseMs = + Number.isFinite(grantedLeaseMs) && grantedLeaseMs > 0 + ? grantedLeaseMs + : Number.isFinite(requestedLeaseMs) + ? requestedLeaseMs + : 300_000; + const renewIntervalMs = Math.max(50, Math.floor(leaseMs / 3)); + + const childEnv: NodeJS.ProcessEnv = { + ...process.env, + PAPERCLIP_TASK_ID: claimed.task.identifier, + PAPERCLIP_ISSUE_UUID: claimed.task.id, + PAPERCLIP_CLAIM_TOKEN: claimed.claimToken, + PAPERCLIP_CLAIM_EPOCH: String(claimed.claimEpoch), + PAPERCLIP_API_URL: resolved.apiBase, + PAPERCLIP_COMPANY_ID: claimed.task.companyId, + ...(resolved.apiKey ? { PAPERCLIP_API_KEY: resolved.apiKey } : {}), + PAPERCLIP_PROFILE: resolved.profile ?? "", + }; + + const child: ChildProcess = spawnImpl(cmd[0]!, cmd.slice(1), { + stdio: "inherit", + shell: false, + env: childEnv, + }); + + let lostClaim = false; + let settledByChild = false; + let receivedSignal: NodeJS.Signals | null = null; + let killEscalationTimer: NodeJS.Timeout | null = null; + let renewInFlight = false; + + const terminateChild = (sig: NodeJS.Signals) => { + try { + child.kill(sig); + } catch { + // Child already exited + } + if (!killEscalationTimer) { + killEscalationTimer = setTimeout(() => { + try { + child.kill("SIGKILL"); + } catch { + // Child already exited + } + }, killGraceMs); + killEscalationTimer.unref?.(); + } + }; + + const renewTimer = setInterval(async () => { + if (renewInFlight || lostClaim || settledByChild || receivedSignal) return; + renewInFlight = true; + try { + const renewed = await resolved.requestJson( + `/api/issues/${encodeURIComponent(claimed.task.id)}/claim/renew`, + { + method: "POST", + headers: { "x-paperclip-claim-token": currentToken }, + body: JSON.stringify({ + claimToken: currentToken, + claimEpoch: currentEpoch, + leaseSec: Math.max(1, Math.round(leaseMs / 1000)), + }), + }, + ); + currentToken = renewed.claimToken; + currentEpoch = renewed.claimEpoch; + saveClaimRecord({ + companyId: claimed.task.companyId, + issueId: claimed.task.id, + identifier: claimed.task.identifier, + claimToken: renewed.claimToken, + claimEpoch: renewed.claimEpoch, + leaseExpiresAt: renewed.leaseExpiresAt, + profile: resolved.profile, + updatedAt: new Date().toISOString(), + }); + } catch (err) { + if (err instanceof PaperclipError && err.status === 409 && err.code === "claim_lost") { + // Distinguish self-settlement by child from genuine lease loss/takeover + let childAlreadySettled = false; + try { + const detail = await resolved.requestJson( + `/api/issues/${encodeURIComponent(claimed.task.id)}?view=thread`, + { method: "GET" }, + ); + const issue = "issue" in detail ? detail.issue : detail; + const interactions = "interactions" in detail ? detail.interactions : []; + const hasPendingInteraction = interactions.some( + (item) => item.status === "pending", + ); + if ( + (issue.status === "done" && issue.claimEpoch === currentEpoch) || + ((issue.status === "blocked" || issue.status === "in_review") && + hasPendingInteraction) + ) { + childAlreadySettled = true; + } + } catch { + // If check fails, treat conservatively as claim_lost + } + + if (childAlreadySettled) { + settledByChild = true; + clearInterval(renewTimer); + } else { + lostClaim = true; + clearInterval(renewTimer); + console.error(pc.red(`Claim lost on ${claimed.task.identifier}; terminating child process.`)); + terminateChild("SIGTERM"); + } + } + } finally { + renewInFlight = false; + } + }, renewIntervalMs); + renewTimer.unref?.(); + + const onSigInt = () => { + receivedSignal = "SIGINT"; + terminateChild("SIGINT"); + }; + const onSigTerm = () => { + receivedSignal = "SIGTERM"; + terminateChild("SIGTERM"); + }; + process.on("SIGINT", onSigInt); + process.on("SIGTERM", onSigTerm); + + const exitResult = await new Promise<{ code: number | null; signal: NodeJS.Signals | null; error?: Error }>( + (resolve) => { + child.once("error", (err) => resolve({ code: 1, signal: null, error: err })); + child.once("close", (code, signal) => resolve({ code, signal })); + }, + ); + + clearInterval(renewTimer); + if (killEscalationTimer) clearTimeout(killEscalationTimer); + process.removeListener("SIGINT", onSigInt); + process.removeListener("SIGTERM", onSigTerm); + + if (exitResult.error) { + try { + await resolved.requestJson(`/api/issues/${encodeURIComponent(claimed.task.id)}/claim/release`, { + method: "POST", + headers: { "x-paperclip-claim-token": currentToken }, + body: JSON.stringify({ + claimToken: currentToken, + claimEpoch: currentEpoch, + comment: `Failed to spawn command: ${exitResult.error.message}`, + }), + }); + } catch { + // ignore release failure + } + deleteClaimRecord(claimed.task.companyId, claimed.task.id); + throw exitResult.error; + } + + if (lostClaim) { + deleteClaimRecord(claimed.task.companyId, claimed.task.id); + return 1; + } + + if (receivedSignal) { + try { + await resolved.requestJson(`/api/issues/${encodeURIComponent(claimed.task.id)}/claim/release`, { + method: "POST", + headers: { "x-paperclip-claim-token": currentToken }, + body: JSON.stringify({ + claimToken: currentToken, + claimEpoch: currentEpoch, + comment: `Released on ${receivedSignal}`, + }), + }); + } catch { + // May already have been settled + } + deleteClaimRecord(claimed.task.companyId, claimed.task.id); + return receivedSignal === "SIGINT" ? 130 : 143; + } + + // Check whether the child settled the task itself (complete/ask/confirm/block/release) + let alreadySettled = settledByChild || !findClaimRecord(claimed.task.companyId, claimed.task.id); + if (!alreadySettled) { + try { + const detail = await resolved.requestJson( + `/api/issues/${encodeURIComponent(claimed.task.id)}?view=thread`, + { method: "GET" }, + ); + const issue = "issue" in detail ? detail.issue : detail; + if (issue.status !== "in_progress" || issue.claimEpoch !== currentEpoch) { + alreadySettled = true; + } + } catch { + // Proceed to settle + } + } + + const childCode = exitResult.code ?? (exitResult.signal ? 1 : 0); + + if (alreadySettled) { + deleteClaimRecord(claimed.task.companyId, claimed.task.id); + return childCode; + } + + if (childCode === 0) { + await resolved.requestJson( + `/api/issues/${encodeURIComponent(claimed.task.id)}/claim/complete`, + { + method: "POST", + headers: { "x-paperclip-claim-token": currentToken }, + body: JSON.stringify({ + claimToken: currentToken, + claimEpoch: currentEpoch, + ...(opts.result !== undefined ? { message: opts.result } : {}), + }), + }, + ); + deleteClaimRecord(claimed.task.companyId, claimed.task.id); + return 0; + } + + try { + await resolved.requestJson( + `/api/issues/${encodeURIComponent(claimed.task.id)}/claim/fail`, + { + method: "POST", + headers: { "x-paperclip-claim-token": currentToken }, + body: JSON.stringify({ + claimToken: currentToken, + claimEpoch: currentEpoch, + reason: `Command exited with code ${childCode}`, + requeue: Boolean(opts.requeueOnError), + }), + }, + ); + } finally { + deleteClaimRecord(claimed.task.companyId, claimed.task.id); + } + return childCode; +} + +async function runTasksListAction( + channelArg: string | undefined, + opts: TasksListOptions, +): Promise { + try { + const resolved = resolveBoardClient(opts); + const states = splitCsvValues([...(opts.state ?? []), ...(opts.status ?? [])]) as IssueStatus[]; + const effectiveChannel = opts.channel ?? channelArg; + const res = await resolved.client.tasks.list({ + ...(effectiveChannel ? { channel: effectiveChannel } : {}), + ...(states.length > 0 ? { status: states } : {}), + ...(opts.label && opts.label.length > 0 ? { label: opts.label } : {}), + ...(opts.assignee ? { assignee: opts.assignee } : {}), + ...(opts.project ? { project: opts.project } : {}), + ...(opts.ready ? { ready: true } : {}), + ...(opts.limit !== undefined && Number.isFinite(opts.limit) ? { limit: opts.limit } : {}), + }); + + const items = + states.length === 0 && !opts.ready + ? res.items.filter((t) => t.status !== "done" && t.status !== "cancelled" && !t.isPassivePost) + : res.items; + + if (resolved.json) { + console.log(JSON.stringify({ items, cursor: res.cursor }, null, 2)); + return; + } + if (items.length === 0) { + console.log(pc.dim("(no matching tasks)")); + } else { + for (const task of items) { + console.log(formatTaskListLine(task)); + } + } + if (process.stdout.isTTY && !resolved.quiet) { + console.log(pc.dim(`cursor: ${res.cursor}`)); + } + } catch (err) { + handleBoardError(err, opts); + } +} + +function attachTasksListOptions(cmd: Command): Command { + return addBoardClientOptions( + cmd + .argument("[channel]", "Optional channel path (e.g. build/ or build/auth)") + .option("--channel ", "Filter by channel path") + .option("--state ", "Filter by task status (repeatable or comma-separated)", collectOption, []) + .option("--status ", "Alias for --state", collectOption, []) + .option("--label ", "Filter by label expression (repeatable)", collectOption, []) + .option("--assignee ", "Filter by assignee agent") + .option("--project ", "Filter by project ID or slug") + .option("--ready", "Only show ready unassigned unblocked pool tasks") + .option("-n, --limit ", "Maximum number of tasks", (val) => Number.parseInt(val, 10)) + .action(runTasksListAction), + ); +} + +export function registerBoardTaskCommands(program: Command): void { + const tasksCmd = program + .command("tasks") + .description("List, create, claim, run, and settle pooled tasks"); + + attachTasksListOptions(tasksCmd); + attachTasksListOptions( + tasksCmd.command("list").description("List pooled and channel tasks"), + ); + + addBoardClientOptions( + tasksCmd + .command("create") + .description("Create a queued task, promote a backlog post, or submit a plan.json DAG") + .argument("[channelOrId]", "Channel path or existing post ID (PAP-89)") + .argument("[text...]", "Task text or title") + .option("--title ", "Explicit task title") + .option("--project ", "Project ID or slug") + .option("--file ", "Read plan.json DAG or task body from file (or '-' for stdin)") + .option("--needs ", "Blocker issue ID/identifier or key (repeatable or comma-separated)", collectOption, []) + .option("--for ", "Target agent or role") + .option("--priority ", "Priority (critical, high, medium, low)") + .option("--label ", "Set label(s) (repeatable)", collectOption, []) + .option("--board", "Surface task on the main Tasks board (scope=board)") + .option("--result-schema ", "Require structured result matching @ on completion") + .option("--claim", "Immediately claim the created task") + .option("--idempotency-key ", "Idempotency key for safe retries") + .action(async (channelOrId: string | undefined, textParts: string[], opts: TasksCreateOptions) => { + try { + const resolved = resolveBoardClient(opts); + const priority = validatePriority(opts.priority); + const { kvLabels, tagLabels } = parseLabelsList(opts.label); + const needs = splitCsvValues(opts.needs); + const fileContent = opts.file !== undefined ? readTextInput(undefined, opts.file) : undefined; + + if (fileContent !== undefined) { + const maybePlan = parsePlanJsonPayload(fileContent); + if (maybePlan.isPlan) { + const targetChannel = + channelOrId && isValidChannelRef(channelOrId) + ? channelOrId.replace(/^#/, "") + : maybePlan.channel; + const effectiveProject = opts.project ?? maybePlan.projectId; + const effectiveBoard = opts.board ?? maybePlan.board ?? (!targetChannel && effectiveProject ? true : undefined); + const effectiveIdemp = opts.idempotencyKey ?? maybePlan.idempotencyKey; + + const companyId = await resolved.resolveCompanyId(); + const batchResult = await resolved.requestJson( + `/api/companies/${encodeURIComponent(companyId)}/issues/batch`, + { + method: "POST", + body: JSON.stringify({ + ...(targetChannel ? { channel: targetChannel } : {}), + ...(effectiveProject !== undefined ? { projectId: effectiveProject } : {}), + ...(effectiveBoard !== undefined ? { board: effectiveBoard } : {}), + ...(effectiveIdemp ? { idempotencyKey: effectiveIdemp } : {}), + tasks: maybePlan.tasks, + }), + }, + ); + + if (opts.claim && batchResult.tasks.length === 1) { + await performClaim(resolved, batchResult.tasks[0]!.identifier, {}); + } + + if (resolved.json) { + console.log(JSON.stringify(batchResult, null, 2)); + return; + } + if (isScriptOutput(resolved)) { + for (const t of batchResult.tasks) { + console.log(t.identifier); + } + return; + } + console.log( + pc.green(`Created ${batchResult.tasks.length} task(s)${batchResult.idempotentReplay ? " (idempotent replay)" : ""}:`), + ); + for (const t of batchResult.tasks) { + console.log(` ${pc.cyan(t.identifier)} ${t.issue.title}${t.key ? pc.dim(` [${t.key}]`) : ""}`); + } + return; + } + } + + // Promote an existing backlog post? + if (channelOrId && isIssueRef(channelOrId)) { + const promoted = await resolved.client.tasks.create(channelOrId, { + ...(priority ? { priority } : {}), + ...(Object.keys(kvLabels).length > 0 ? { labels: kvLabels } : {}), + ...(opts.project !== undefined ? { projectId: opts.project } : {}), + ...(opts.board ? { board: true } : {}), + ...(opts.for ? { for: opts.for } : {}), + ...(opts.resultSchema ? { resultSchema: opts.resultSchema } : {}), + }); + if (opts.claim) { + await performClaim(resolved, promoted.identifier, {}); + } + if (resolved.json) { + console.log(JSON.stringify(promoted, null, 2)); + return; + } + if (isScriptOutput(resolved)) { + console.log(promoted.identifier); + return; + } + console.log(`${pc.cyan(promoted.identifier)} queued ${promoted.title}`); + return; + } + + // Single task create + let channel: string | undefined; + let inlineParts = [...textParts]; + let boardMode = Boolean(opts.board); + + if (!channelOrId) { + if (opts.project || opts.board) { + boardMode = true; + } else { + channel = "general"; + } + } else if (isValidChannelRef(channelOrId) && (inlineParts.length > 0 || fileContent !== undefined || opts.title)) { + channel = channelOrId.replace(/^#/, ""); + } else if ((opts.project || opts.board) && !isValidChannelRef(channelOrId)) { + inlineParts = [channelOrId, ...inlineParts]; + boardMode = true; + } else if (isValidChannelRef(channelOrId)) { + channel = channelOrId.replace(/^#/, ""); + } else { + inlineParts = [channelOrId, ...inlineParts]; + channel = opts.project || opts.board ? undefined : "general"; + if (!channel) boardMode = true; + } + + const bodyText = fileContent ?? (inlineParts.length > 0 ? inlineParts.join(" ") : undefined); + if (!bodyText?.trim() && !opts.title?.trim()) { + throw new Error("Task requires text, --title, or --file."); + } + + let created: HeadlessIssueView; + if (needs.length > 0 || !channel) { + const companyId = await resolved.resolveCompanyId(); + const taskPayload: PlanTaskInput = { + ...(opts.title ? { title: opts.title } : {}), + ...(bodyText ? { text: bodyText } : {}), + ...(priority ? { priority } : {}), + ...(Object.keys(kvLabels).length > 0 ? { labels: kvLabels } : {}), + ...(tagLabels.length > 0 ? { tagLabels } : {}), + ...(needs.length > 0 ? { needs } : {}), + ...(opts.for ? { for: opts.for } : {}), + ...(opts.resultSchema ? { resultSchema: opts.resultSchema } : {}), + ...(boardMode ? { board: true } : {}), + }; + const batch = await resolved.requestJson( + `/api/companies/${encodeURIComponent(companyId)}/issues/batch`, + { + method: "POST", + body: JSON.stringify({ + ...(channel ? { channel } : {}), + ...(opts.project ? { projectId: opts.project } : {}), + ...(boardMode ? { board: true } : {}), + ...(opts.idempotencyKey ? { idempotencyKey: opts.idempotencyKey } : {}), + tasks: [taskPayload], + }), + }, + ); + created = batch.tasks[0]!.issue; + } else { + created = await resolved.client.tasks.create(channel, { + ...(opts.title ? { title: opts.title } : {}), + ...(bodyText ? { text: bodyText } : {}), + ...(opts.project ? { projectId: opts.project } : {}), + ...(boardMode ? { board: true } : {}), + ...(priority ? { priority } : {}), + ...(Object.keys(kvLabels).length > 0 ? { labels: kvLabels } : {}), + ...(tagLabels.length > 0 ? { tagLabels } : {}), + ...(opts.for ? { for: opts.for } : {}), + ...(opts.resultSchema ? { resultSchema: opts.resultSchema } : {}), + ...(opts.idempotencyKey ? { idempotencyKey: opts.idempotencyKey } : {}), + }); + } + + if (opts.claim) { + await performClaim(resolved, created.identifier, {}); + } + + if (resolved.json) { + console.log(JSON.stringify(created, null, 2)); + return; + } + if (isScriptOutput(resolved)) { + console.log(created.identifier); + return; + } + console.log( + `${pc.cyan(created.identifier)} #${created.channel ?? "board"} ${created.title} ${pc.dim(`(${created.cursor})`)}`, + ); + } catch (err) { + handleBoardError(err, opts); + } + }), + ); + + addBoardClientOptions( + tasksCmd + .command("claim") + .description("Claim a specific task or pop the oldest ready task from a queue") + .argument("[id]", "Specific issue identifier/UUID to claim") + .option("--ready [channel]", "Pop oldest ready task (optionally scoped to channel or prefix/)") + .option("--channel ", "Channel or prefix/ queue to claim from (implies --ready)") + .option("--label ", "Filter by label expression (repeatable)", collectOption, []) + .option("--project ", "Filter by project ID or slug") + .option("--lease ", "Lease duration (e.g. 5m, 60s)") + .option("--wait ", "Wait up to duration if queue is empty (e.g. 10m, 5s)") + .option("--include-untrusted", "Include tasks marked untrusted on wildcard --ready claims") + .action(async (id: string | undefined, opts: TasksClaimOptions) => { + let shouldExit1 = false; + try { + const resolved = resolveBoardClient(opts); + const claimed = await performClaim(resolved, id, opts); + if (!claimed) { + if (resolved.json) { + console.error( + JSON.stringify({ + error: opts.wait ? "timeout" : "no_ready_task", + reason: opts.wait ? "timeout" : "empty", + message: opts.wait ? "Timed out waiting for a ready task" : "No ready task available", + }), + ); + } else { + console.error(pc.yellow(opts.wait ? "Timed out waiting for a ready task." : "No ready task available.")); + } + shouldExit1 = true; + } else if (resolved.json) { + console.log( + JSON.stringify( + { + issue: claimed.task, + claimToken: claimed.claimToken, + claimEpoch: claimed.claimEpoch, + leaseExpiresAt: claimed.leaseExpiresAt, + cursor: claimed.cursor, + }, + null, + 2, + ), + ); + } else if (isScriptOutput(resolved)) { + console.log(claimed.task.identifier); + } else { + console.log( + `${pc.green("Claimed")} ${pc.cyan(claimed.task.identifier)} (epoch=${claimed.claimEpoch}, expires=${claimed.leaseExpiresAt})`, + ); + } + } catch (err) { + handleBoardError(err, opts); + } + if (shouldExit1) { + process.exit(1); + } + }), + ); + + const runSubcmd = addBoardClientOptions( + tasksCmd + .command("run") + .description("Claim a task, run a command with injected env & auto-renewed lease, and settle on exit") + .argument("[args...]", "Optional task ID followed by -- ") + .option("--ready [channel]", "Pop oldest ready task (optionally scoped to channel or prefix/)") + .option("--channel ", "Channel or prefix/ queue to claim from (implies --ready)") + .option("--label ", "Filter by label expression (repeatable)", collectOption, []) + .option("--project ", "Filter by project ID or slug") + .option("--lease ", "Lease duration (e.g. 5m, 60s)") + .option("--wait ", "Wait up to duration if queue is empty (e.g. 10m, 5s)") + .option("--result ", "Completion message when command exits 0 without settling itself") + .option("--requeue-on-error", "Requeue task back to todo when command exits non-zero") + .option("--include-untrusted", "Include tasks marked untrusted on wildcard --ready claims"), + ); + runSubcmd.action(async (args: string[], opts: TasksRunOptions, cmdObj: Command) => { + let exitCode = 0; + try { + const resolved = resolveBoardClient(opts); + const rawArgs = getRootRawArgs(cmdObj); + const { id, cmd } = extractRunArgs(args, rawArgs, opts.ready !== undefined || Boolean(opts.channel)); + exitCode = await executeTasksRun(resolved, id, cmd, opts); + } catch (err) { + handleBoardError(err, opts); + } + if (exitCode !== 0) { + process.exit(exitCode); + } + }); + + addBoardClientOptions( + tasksCmd + .command("renew") + .description("Extend the active lease on a claimed task") + .argument("", "Issue identifier or UUID") + .option("--lease ", "New lease duration (e.g. 5m)") + .action(async (id: string, opts: TasksRenewOptions) => { + try { + const resolved = resolveBoardClient(opts); + const companyId = await resolved.resolveCompanyId(); + const claim = resolveClaimCredentials({ + companyId, + issueRef: id, + activeProfile: resolved.profile, + requireClaim: true, + })!; + const leaseSec = opts.lease + ? Math.max(1, Math.round(parseDurationMs(opts.lease) / 1000)) + : undefined; + const renewed = await resolved.requestJson( + `/api/issues/${encodeURIComponent(id)}/claim/renew`, + { + method: "POST", + headers: { "x-paperclip-claim-token": claim.claimToken }, + body: JSON.stringify({ + claimToken: claim.claimToken, + ...(claim.claimEpoch !== undefined ? { claimEpoch: claim.claimEpoch } : {}), + ...(leaseSec !== undefined ? { leaseSec } : {}), + }), + }, + ); + saveClaimRecord({ + companyId: renewed.issue.companyId, + issueId: renewed.issue.id, + identifier: renewed.issue.identifier, + claimToken: renewed.claimToken, + claimEpoch: renewed.claimEpoch, + leaseExpiresAt: renewed.leaseExpiresAt, + profile: resolved.profile, + updatedAt: new Date().toISOString(), + }); + if (resolved.json) { + console.log(JSON.stringify(renewed, null, 2)); + return; + } + console.log( + `${pc.green("Renewed")} ${pc.cyan(renewed.issue.identifier)} (epoch=${renewed.claimEpoch}, expires=${renewed.leaseExpiresAt})`, + ); + } catch (err) { + handleBoardError(err, opts); + } + }), + ); + + addBoardClientOptions( + tasksCmd + .command("release") + .description("Release a claimed task back to the ready queue (todo)") + .argument("", "Issue identifier or UUID") + .argument("[comment...]", "Optional release note") + .option("--comment ", "Optional release note") + .option("-m, --message ", "Alias for --comment") + .action(async (id: string, commentParts: string[], opts: TasksReleaseOptions) => { + try { + const resolved = resolveBoardClient(opts); + const companyId = await resolved.resolveCompanyId(); + const claim = resolveClaimCredentials({ + companyId, + issueRef: id, + activeProfile: resolved.profile, + requireClaim: true, + })!; + const positional = commentParts.length > 0 ? commentParts.join(" ") : undefined; + const comment = opts.comment ?? opts.message ?? positional; + const result = await resolved.requestJson<{ released: boolean; cursor: string }>( + `/api/issues/${encodeURIComponent(id)}/claim/release`, + { + method: "POST", + headers: { "x-paperclip-claim-token": claim.claimToken }, + body: JSON.stringify({ + claimToken: claim.claimToken, + ...(claim.claimEpoch !== undefined ? { claimEpoch: claim.claimEpoch } : {}), + ...(comment !== undefined ? { comment } : {}), + }), + }, + ); + deleteClaimRecord(companyId, id); + if (resolved.json) { + console.log(JSON.stringify(result, null, 2)); + return; + } + console.log(`${pc.yellow("Released")} ${pc.cyan(id)} back to todo (${result.cursor})`); + } catch (err) { + handleBoardError(err, opts); + } + }), + ); + + addBoardClientOptions( + tasksCmd + .command("complete") + .description("Complete a claimed task (status=done), validating any required resultSchema") + .argument("", "Issue identifier or UUID") + .argument("[result...]", "Completion summary message") + .option("-m, --message ", "Completion summary message") + .option("--comment ", "Alias for --message") + .option("--data ", "Structured JSON result payload") + .option("--pr ", "Pull request URL to attach") + .option("--attach ", "Attach file(s) to the task", collectOption, []) + .option("--result-schema ", "Schema ref (@) for --data") + .action(async (id: string, resultParts: string[], opts: TasksCompleteOptions) => { + try { + const resolved = resolveBoardClient(opts); + const companyId = await resolved.resolveCompanyId(); + const claim = resolveClaimCredentials({ + companyId, + issueRef: id, + activeProfile: resolved.profile, + requireClaim: true, + })!; + const positional = resultParts.length > 0 ? resultParts.join(" ") : undefined; + const message = opts.message ?? opts.comment ?? positional; + let dataObj: Record | undefined; + if (opts.data !== undefined) { + const parsed = parseJsonArg(opts.data, "--data"); + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { + throw new Error("--data must be a JSON object"); + } + dataObj = parsed as Record; + } + + if (opts.attach && opts.attach.length > 0) { + const targetIssueId = claim.issueId ?? id; + await resolved.uploadIssueAttachments(companyId, targetIssueId, opts.attach); + } + + const updated = await resolved.requestJson( + `/api/issues/${encodeURIComponent(id)}/claim/complete`, + { + method: "POST", + headers: { "x-paperclip-claim-token": claim.claimToken }, + body: JSON.stringify({ + claimToken: claim.claimToken, + ...(claim.claimEpoch !== undefined ? { claimEpoch: claim.claimEpoch } : {}), + ...(message !== undefined ? { message } : {}), + ...(dataObj !== undefined ? { data: dataObj } : {}), + ...(opts.pr !== undefined ? { prUrl: opts.pr } : {}), + ...(opts.resultSchema !== undefined ? { resultSchema: opts.resultSchema } : {}), + }), + }, + ); + deleteClaimRecord(companyId, id); + + if (resolved.json) { + console.log(JSON.stringify(updated, null, 2)); + return; + } + if (isScriptOutput(resolved)) { + console.log(updated.identifier); + return; + } + console.log(`${pc.green("Completed")} ${pc.cyan(updated.identifier)} (${updated.cursor})`); + } catch (err) { + handleBoardError(err, opts); + } + }), + ); + + addBoardClientOptions( + tasksCmd + .command("fail") + .description("Fail a claimed task (blocks by default, or returns to todo with --requeue)") + .argument("", "Issue identifier or UUID") + .argument("[reason...]", "Failure reason") + .option("--reason ", "Failure reason") + .option("-m, --message ", "Alias for --reason") + .option("--requeue", "Return task to todo for another worker attempt") + .action(async (id: string, reasonParts: string[], opts: TasksFailOptions) => { + try { + const resolved = resolveBoardClient(opts); + const companyId = await resolved.resolveCompanyId(); + const claim = resolveClaimCredentials({ + companyId, + issueRef: id, + activeProfile: resolved.profile, + requireClaim: true, + })!; + const positional = reasonParts.length > 0 ? reasonParts.join(" ") : undefined; + const reason = (opts.reason ?? opts.message ?? positional)?.trim(); + if (!reason) { + throw new Error("Specify a failure reason via positional or --reason ."); + } + const updated = await resolved.requestJson( + `/api/issues/${encodeURIComponent(id)}/claim/fail`, + { + method: "POST", + headers: { "x-paperclip-claim-token": claim.claimToken }, + body: JSON.stringify({ + claimToken: claim.claimToken, + ...(claim.claimEpoch !== undefined ? { claimEpoch: claim.claimEpoch } : {}), + reason, + requeue: Boolean(opts.requeue), + }), + }, + ); + deleteClaimRecord(companyId, id); + + if (resolved.json) { + console.log(JSON.stringify(updated, null, 2)); + return; + } + console.log( + `${pc.yellow(opts.requeue ? "Requeued" : "Blocked")} ${pc.cyan(updated.identifier)} (status=${updated.status})`, + ); + } catch (err) { + handleBoardError(err, opts); + } + }), + ); + + addBoardClientOptions( + tasksCmd + .command("block") + .description("Mark a task as blocked with a reason (releasing any active pool lease)") + .argument("", "Issue identifier or UUID") + .argument("[reason...]", "Blocking reason") + .option("--reason ", "Blocking reason") + .option("-m, --message ", "Alias for --reason") + .action(async (id: string, reasonParts: string[], opts: TasksBlockOptions) => { + try { + const resolved = resolveBoardClient(opts); + const positional = reasonParts.length > 0 ? reasonParts.join(" ") : undefined; + const reason = (opts.reason ?? opts.message ?? positional)?.trim(); + if (!reason) { + throw new Error("Specify a blocking reason via positional or --reason ."); + } + const companyId = await resolved.resolveCompanyId(); + const claim = resolveClaimCredentials({ + companyId, + issueRef: id, + activeProfile: resolved.profile, + requireClaim: false, + }); + + let updated: HeadlessIssueView; + if (claim) { + updated = await resolved.requestJson( + `/api/issues/${encodeURIComponent(id)}/claim/fail`, + { + method: "POST", + headers: { "x-paperclip-claim-token": claim.claimToken }, + body: JSON.stringify({ + claimToken: claim.claimToken, + ...(claim.claimEpoch !== undefined ? { claimEpoch: claim.claimEpoch } : {}), + reason, + requeue: false, + }), + }, + ); + deleteClaimRecord(companyId, id); + } else { + updated = await resolved.requestJson( + `/api/issues/${encodeURIComponent(id)}`, + { + method: "PATCH", + body: JSON.stringify({ status: "blocked" }), + }, + ); + await resolved.client.reply(id, reason); + } + + if (resolved.json) { + console.log(JSON.stringify(updated, null, 2)); + return; + } + console.log(`${pc.yellow("Blocked")} ${pc.cyan(updated.identifier)} (${updated.cursor})`); + } catch (err) { + handleBoardError(err, opts); + } + }), + ); + + addBoardClientOptions( + tasksCmd + .command("unblock") + .description("Unblock a task back to todo (ready)") + .argument("", "Issue identifier or UUID") + .action(async (id: string, opts: BoardCommonOptions) => { + try { + const resolved = resolveBoardClient(opts); + const updated = await resolved.requestJson( + `/api/issues/${encodeURIComponent(id)}`, + { + method: "PATCH", + body: JSON.stringify({ status: "todo" }), + }, + ); + if (resolved.json) { + console.log(JSON.stringify(updated, null, 2)); + return; + } + console.log(`${pc.green("Unblocked")} ${pc.cyan(updated.identifier)} (status=${updated.status})`); + } catch (err) { + handleBoardError(err, opts); + } + }), + ); +} diff --git a/cli/src/commands/client/access.ts b/cli/src/commands/client/access.ts index 55e0ef05e14..8998fc56448 100644 --- a/cli/src/commands/client/access.ts +++ b/cli/src/commands/client/access.ts @@ -1,4 +1,6 @@ import { Command } from "commander"; +import { handleBoardError, isPcBinary } from "../board/client.js"; +import { handleBoardWhoami } from "../board/agent-auth.js"; import { addCommonClientOptions, apiPath, @@ -364,16 +366,41 @@ export function registerAccessCommands(program: Command): void { ); } +interface WhoamiOptions extends BaseClientOptions { + as?: string; + company?: string; + companyId?: string; +} + +function shouldUseBoardWhoami(opts: WhoamiOptions): boolean { + if (opts.as !== undefined) return true; + if (opts.company !== undefined) return true; + if (opts.companyId !== undefined) return true; + if (Boolean(process.env.PAPERCLIP_PROFILE?.trim())) return true; + if (isPcBinary()) return true; + return false; +} + function addWhoamiCommand(parent: Command): void { addCommonClientOptions( parent .command("whoami") .description("Show current CLI auth identity") - .action(async (opts: BaseClientOptions) => { + .option("--as ", "Resolve identity for a profile or registered agent") + .option("--company ", "Company ID or issue prefix (e.g. PAP)") + .option("-C, --company-id ", "Company ID") + .action(async (opts: WhoamiOptions) => { try { + if (shouldUseBoardWhoami(opts)) { + await handleBoardWhoami(opts); + return; + } const ctx = resolveCommandContext(opts); printOutput(await ctx.api.get("/api/cli-auth/me"), { json: ctx.json }); } catch (err) { + if (shouldUseBoardWhoami(opts)) { + handleBoardError(err, opts); + } handleCommandError(err); } }), diff --git a/cli/src/commands/client/agent.ts b/cli/src/commands/client/agent.ts index 0930251879f..467e42c6307 100644 --- a/cli/src/commands/client/agent.ts +++ b/cli/src/commands/client/agent.ts @@ -25,6 +25,7 @@ import fs from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; +import { registerBoardAgentAuthCommands } from "../board/agent-auth.js"; import { addCommonClientOptions, apiPath, @@ -228,6 +229,7 @@ function buildAgentEnvExports(input: { export function registerAgentCommands(program: Command): void { const agent = program.command("agent").description("Agent operations"); + registerBoardAgentAuthCommands(agent); addCommonClientOptions( agent diff --git a/cli/src/commands/up.ts b/cli/src/commands/up.ts new file mode 100644 index 00000000000..e9b15beac01 --- /dev/null +++ b/cli/src/commands/up.ts @@ -0,0 +1,391 @@ +import fs from "node:fs"; +import path from "node:path"; +import { createServer } from "node:net"; +import * as p from "@clack/prompts"; +import pc from "picocolors"; +import { Option, type Command } from "commander"; +import { type Company } from "@paperclipai/shared"; +import { paperclip, type ChannelView } from "@paperclipai/shared/sdk"; +import { PaperclipApiClient } from "../client/http.js"; +import { readContext, setCurrentProfile, upsertProfile } from "../client/context.js"; +import { + expandHomePrefix, + resolveDefaultConfigPath, + resolveDefaultContextPath, + resolvePaperclipHomeDir, + resolvePaperclipInstanceId, +} from "../config/home.js"; +import { readConfig } from "../config/store.js"; +import { detectGitWorkspaceInfo } from "./git-workspace.js"; +import { runCommand, type StartedServer } from "./run.js"; +import { resolveTestDriveServerPort } from "./test-drive.js"; + +export const UP_BIND_MODES = ["loopback", "tailnet", "lan"] as const; +export type UpBindMode = (typeof UP_BIND_MODES)[number]; + +export interface UpOptions { + local?: boolean; + dataDir?: string; + port?: number | string; + bind?: UpBindMode; + companyName?: string; + context?: boolean; +} + +export type UpApi = Pick; + +export interface UpBootstrapResult { + reused: boolean; + company: Company; + issuePrefix: string; + channel: ChannelView | null; +} + +export interface UpDependencies { + run: typeof runCommand; + createApi: (apiBase: string) => UpApi; + ensureGeneralChannel: (apiBase: string, companyId: string) => Promise; + updateContext: (input: { + apiBase: string; + companyId: string; + contextPath?: string; + }) => string; +} + +export function deriveCompanyIssuePrefix(companyName: string): string { + const cleaned = companyName + .toUpperCase() + .replace(/[^A-Z0-9]+/g, ""); + if (cleaned.length >= 3) { + return cleaned.slice(0, 3); + } + if (cleaned.length > 0) { + return cleaned.padEnd(3, "P"); + } + return "PAP"; +} + +export function resolveUpCompanyName(options: Pick, cwd = process.cwd()): string { + const explicit = options.companyName?.trim(); + if (explicit) return explicit; + if (options.local) { + const git = detectGitWorkspaceInfo(cwd); + const root = git?.root ?? path.resolve(cwd); + const base = path.basename(root).trim(); + if (base) return base; + } + return "Workspace"; +} + +export function checkLocalGitignore(workspaceRoot: string): { + isGitRepo: boolean; + ignored: boolean; + gitignorePath: string; +} { + const git = detectGitWorkspaceInfo(workspaceRoot); + const gitignorePath = path.join(workspaceRoot, ".gitignore"); + if (!git) { + return { isGitRepo: false, ignored: true, gitignorePath }; + } + if (!fs.existsSync(gitignorePath)) { + return { isGitRepo: true, ignored: false, gitignorePath }; + } + const content = fs.readFileSync(gitignorePath, "utf8"); + const lines = content.split(/\r?\n/).map((line) => line.trim()); + const ignored = lines.some( + (line) => + !line.startsWith("#") && + (line === ".paperclip" || + line === ".paperclip/" || + line === "/.paperclip" || + line === "/.paperclip/" || + line === ".paperclip/board" || + line === ".paperclip/board/"), + ); + return { isGitRepo: true, ignored, gitignorePath }; +} + +async function checkPortAvailable(port: number, host = "127.0.0.1"): Promise { + return await new Promise((resolve) => { + const server = createServer(); + server.unref(); + server.once("error", () => resolve(false)); + server.listen(port, host, () => { + server.close(() => resolve(true)); + }); + }); +} + +function parseExplicitPort(raw: number | string | undefined): number | undefined { + if (raw === undefined) return undefined; + const num = typeof raw === "number" ? raw : Number.parseInt(String(raw).trim(), 10); + if (!Number.isInteger(num) || num < 1 || num > 65535) { + throw new Error(`Invalid --port "${String(raw)}": expected an integer between 1 and 65535.`); + } + return num; +} + +export async function prepareUpEnvironment( + options: UpOptions, + cwd = process.cwd(), +): Promise<{ + dataDir: string; + workspaceRoot: string | null; + contextPath: string; + port: number; + bind: UpBindMode; + gitignoreMissing: boolean; +}> { + if (options.local && options.dataDir?.trim()) { + throw new Error("--local and --data-dir cannot be combined."); + } + + const bind: UpBindMode = options.bind ?? "loopback"; + if (!UP_BIND_MODES.includes(bind)) { + throw new Error(`Invalid --bind "${String(bind)}": expected one of ${UP_BIND_MODES.join(", ")}.`); + } + + let workspaceRoot: string | null = null; + let dataDir: string; + let contextPath: string; + + if (options.local) { + const git = detectGitWorkspaceInfo(cwd); + workspaceRoot = git?.root ?? path.resolve(cwd); + dataDir = path.join(workspaceRoot, ".paperclip", "board"); + contextPath = path.join(workspaceRoot, ".paperclip", "context.json"); + process.env.PAPERCLIP_HOME = dataDir; + process.env.PAPERCLIP_INSTANCE_ID = "default"; + process.env.PAPERCLIP_CONFIG = resolveDefaultConfigPath("default"); + process.env.PAPERCLIP_CONTEXT = contextPath; + } else if (options.dataDir?.trim()) { + dataDir = path.resolve(expandHomePrefix(options.dataDir.trim())); + process.env.PAPERCLIP_HOME = dataDir; + const instanceId = resolvePaperclipInstanceId(); + process.env.PAPERCLIP_INSTANCE_ID = instanceId; + process.env.PAPERCLIP_CONFIG = resolveDefaultConfigPath(instanceId); + contextPath = process.env.PAPERCLIP_CONTEXT?.trim() + ? path.resolve(process.env.PAPERCLIP_CONTEXT.trim()) + : resolveDefaultContextPath(); + process.env.PAPERCLIP_CONTEXT = contextPath; + } else { + dataDir = resolvePaperclipHomeDir(); + const instanceId = resolvePaperclipInstanceId(); + process.env.PAPERCLIP_INSTANCE_ID = instanceId; + process.env.PAPERCLIP_CONFIG = process.env.PAPERCLIP_CONFIG?.trim() || resolveDefaultConfigPath(instanceId); + contextPath = process.env.PAPERCLIP_CONTEXT?.trim() + ? path.resolve(process.env.PAPERCLIP_CONTEXT.trim()) + : resolveDefaultContextPath(); + process.env.PAPERCLIP_CONTEXT = contextPath; + } + + process.env.PAPERCLIP_OPEN_ON_LISTEN = "false"; + if (bind !== "loopback") { + process.env.PAPERCLIP_BIND = bind; + } + + const explicitPort = parseExplicitPort(options.port); + let port: number; + if (explicitPort !== undefined) { + if (!(await checkPortAvailable(explicitPort))) { + throw new Error(`Port ${explicitPort} is already in use.`); + } + port = explicitPort; + } else { + let preferredPort = 3100; + try { + preferredPort = readConfig(process.env.PAPERCLIP_CONFIG)?.server.port ?? preferredPort; + } catch { + // Doctor handles invalid config diagnostics on startup. + } + port = await resolveTestDriveServerPort(preferredPort); + } + process.env.PORT = String(port); + + const gitignoreCheck = workspaceRoot ? checkLocalGitignore(workspaceRoot) : null; + const gitignoreMissing = Boolean(gitignoreCheck?.isGitRepo && !gitignoreCheck.ignored); + + return { + dataDir, + workspaceRoot, + contextPath, + port, + bind, + gitignoreMissing, + }; +} + +export async function bootstrapUpBoard(input: { + api: UpApi; + apiBase: string; + companyName: string; + ensureGeneralChannel: (apiBase: string, companyId: string) => Promise; +}): Promise { + const companies = (await input.api.get("/api/companies")) ?? []; + const activeCompanies = companies.filter((c) => c.status !== "archived"); + let company = activeCompanies[0]; + let reused = true; + + if (!company) { + reused = false; + const created = await input.api.post("/api/companies", { + name: input.companyName, + }); + if (!created) { + throw new Error("Paperclip returned no result while creating the default company."); + } + company = created; + } + + const issuePrefix = + typeof company.issuePrefix === "string" && company.issuePrefix.trim().length > 0 + ? company.issuePrefix.trim() + : deriveCompanyIssuePrefix(company.name); + + const channel = await input.ensureGeneralChannel(input.apiBase, company.id); + return { reused, company, issuePrefix, channel }; +} + +function formatReadyUrl(server: StartedServer): string { + const rawHost = + server.host === "0.0.0.0" || server.host === "::" || server.host === "[::]" + ? "127.0.0.1" + : server.host; + const host = rawHost.includes(":") && !rawHost.startsWith("[") ? `[${rawHost}]` : rawHost; + return `http://${host}:${server.listenPort}`; +} + +export function formatUpReadyBanner(input: { + url: string; + companyName: string; + issuePrefix: string; + deploymentMode: string; + dataDir: string; + contextUpdated: boolean; + contextPath: string; + companyId: string; +}): string[] { + const lines = [ + `Paperclip ready at ${input.url} (Company: ${input.companyName} [${input.issuePrefix}], mode: ${input.deploymentMode})`, + `Channel: #general | Data: ${input.dataDir}`, + input.contextUpdated + ? `Context: ${input.contextPath} (company=${input.companyId})` + : `Context: skipped (--no-context)`, + `Next: pc post general "Hello board" | pc tasks create general "First task"`, + ]; + return lines; +} + +const defaultUpDependencies: UpDependencies = { + run: runCommand, + createApi: (apiBase) => new PaperclipApiClient({ apiBase }), + ensureGeneralChannel: async (apiBase, companyId) => { + const client = paperclip({ apiBase, company: companyId }); + return await client.channels.ensure("general"); + }, + updateContext: ({ apiBase, companyId, contextPath }) => { + const existing = readContext(contextPath); + const targetProfile = existing.currentProfile || "default"; + upsertProfile( + targetProfile, + { + apiBase, + companyId, + }, + contextPath, + ); + setCurrentProfile(targetProfile, contextPath); + return contextPath ?? resolveDefaultContextPath(); + }, +}; + +export async function upCommand( + options: UpOptions, + dependencies: UpDependencies = defaultUpDependencies, + cwd = process.cwd(), +): Promise { + const dataDir = resolvePaperclipHomeDir(); + const companyName = resolveUpCompanyName(options, cwd); + const contextPath = process.env.PAPERCLIP_CONTEXT ?? resolveDefaultContextPath(); + const bind: UpBindMode = options.bind ?? "loopback"; + const skipContext = options.context === false; + + if (options.local) { + const git = detectGitWorkspaceInfo(cwd); + const root = git?.root ?? path.resolve(cwd); + const check = checkLocalGitignore(root); + if (check.isGitRepo && !check.ignored) { + p.log.warn( + `Local board state lives at ${path.join(root, ".paperclip", "board")} — add ".paperclip/" to ${check.gitignorePath} to keep it out of git.`, + ); + } + } + + await dependencies.run({ + repair: true, + yes: true, + bind, + installService: false, + skipServiceManagerCheck: Boolean(options.local || options.dataDir?.trim()), + introLabel: "paperclipai up", + afterStart: async (server) => { + const url = formatReadyUrl(server); + const api = dependencies.createApi(url); + const result = await bootstrapUpBoard({ + api, + apiBase: url, + companyName, + ensureGeneralChannel: dependencies.ensureGeneralChannel, + }); + + let savedContextPath = contextPath; + if (!skipContext) { + savedContextPath = dependencies.updateContext({ + apiBase: url, + companyId: result.company.id, + contextPath, + }); + } + + const config = readConfig(process.env.PAPERCLIP_CONFIG); + const mode = config?.server.deploymentMode ?? (bind === "loopback" ? "local_trusted" : "authenticated"); + const bannerLines = formatUpReadyBanner({ + url, + companyName: result.company.name, + issuePrefix: result.issuePrefix, + deploymentMode: mode, + dataDir, + contextUpdated: !skipContext, + contextPath: savedContextPath, + companyId: result.company.id, + }); + + console.log(""); + for (const line of bannerLines) { + console.log(pc.green(line)); + } + }, + }); +} + +export function registerUpCommand( + program: Command, + dependencies: UpDependencies = defaultUpDependencies, +): void { + program + .command("up") + .description("Start a ready-to-use local Paperclip board with zero prompts or LLM keys") + .option("--local", "Store board state in /.paperclip/board") + .option("-d, --data-dir ", "Paperclip data directory root") + .option("-p, --port ", "Server listen port (defaults to 3100 or next free port)") + .addOption( + new Option("--bind ", "Reachability preset (loopback, tailnet, lan)") + .choices(UP_BIND_MODES) + .default("loopback"), + ) + .option("--company-name ", "Initial company name when bootstrapping a fresh board") + .option("--no-context", "Do not update local CLI context with the started board URL and company") + .action(async (options: UpOptions) => { + await upCommand(options, dependencies); + }); +} diff --git a/cli/src/config/data-dir.ts b/cli/src/config/data-dir.ts index bb4b5f7092f..b432f7cb57e 100644 --- a/cli/src/config/data-dir.ts +++ b/cli/src/config/data-dir.ts @@ -9,7 +9,7 @@ import { export interface DataDirOptionLike { dataDir?: string; config?: string; - context?: string; + context?: string | boolean; instance?: string; } @@ -38,7 +38,8 @@ export function applyDataDirOverride( } if (support.hasContextOption) { - const hasContextOverride = Boolean(options.context?.trim()) || Boolean(process.env.PAPERCLIP_CONTEXT?.trim()); + const contextStr = typeof options.context === "string" ? options.context.trim() : ""; + const hasContextOverride = Boolean(contextStr) || Boolean(process.env.PAPERCLIP_CONTEXT?.trim()); if (!hasContextOverride) { process.env.PAPERCLIP_CONTEXT = resolveDefaultContextPath(); } diff --git a/cli/src/index.ts b/cli/src/index.ts index 61cc6e54039..a437d32b6c4 100644 --- a/cli/src/index.ts +++ b/cli/src/index.ts @@ -6,7 +6,6 @@ import { warnIfUnsupportedNodeVersion } from "@paperclipai/shared/node-version"; import { onboard } from "./commands/onboard.js"; import { doctor } from "./commands/doctor.js"; import { envCommand } from "./commands/env.js"; -import { channelsCommand } from "./commands/channels.js"; import { configure } from "./commands/configure.js"; import { addAllowedHostname } from "./commands/allowed-hostname.js"; import { heartbeatRun } from "./commands/heartbeat-run.js"; @@ -59,6 +58,13 @@ import { registerTestDriveCommand, type TestDriveOptions, } from "./commands/test-drive.js"; +import { + prepareUpEnvironment, + registerUpCommand, + type UpOptions, +} from "./commands/up.js"; +import { registerBoardCommands } from "./commands/board/index.js"; +import { isPcBinary } from "./commands/board/client.js"; const program = new Command(); const DATA_DIR_OPTION_HELP = @@ -67,7 +73,7 @@ const DATA_DIR_OPTION_HELP = program.enablePositionalOptions(); program - .name("paperclipai") + .name(isPcBinary() ? "pc" : "paperclipai") .description("Paperclip CLI — setup, diagnose, and configure your instance") .version(cliVersion); @@ -113,6 +119,14 @@ program.hook("preAction", async (_thisCommand, actionCommand) => { }); dataDirOptions = { ...options, dataDir: prepared.dataDir }; } + if (actionCommand.name() === "up") { + const prepared = await prepareUpEnvironment(options as UpOptions); + dataDirOptions = { + ...options, + dataDir: prepared.dataDir, + context: typeof options.context === "string" ? options.context : undefined, + }; + } const optionNames = new Set(actionCommand.options.map((option) => option.attributeName())); applyDataDirOverride(dataDirOptions, { hasConfigOption: optionNames.has("config"), @@ -125,6 +139,7 @@ program.hook("preAction", async (_thisCommand, actionCommand) => { initTelemetryFromConfigFile(options.config); }); +registerUpCommand(program); registerTestDriveCommand(program); registerRuntimeCommands(program); @@ -159,14 +174,6 @@ program .option("-d, --data-dir ", DATA_DIR_OPTION_HELP) .action(envCommand); -program - .command("channels") - .description("Show the release channels and which one this install follows") - .option("--json", "Machine-readable output") - .action(async (opts) => { - await channelsCommand(opts); - }); - program .command("configure") .description("Update configuration sections") @@ -264,6 +271,7 @@ registerTeamCommands(program); registerWorktreeCommands(program); registerEnvLabCommands(program); registerPluginCommands(program); +registerBoardCommands(program); const auth = program.command("auth").description("Authentication and bootstrap utilities"); diff --git a/cli/src/sdk.ts b/cli/src/sdk.ts new file mode 100644 index 00000000000..aa04f02290e --- /dev/null +++ b/cli/src/sdk.ts @@ -0,0 +1 @@ +export * from "@paperclipai/shared/sdk/lite"; diff --git a/doc/CHANNELS-AND-QUEUES.md b/doc/CHANNELS-AND-QUEUES.md new file mode 100644 index 00000000000..007aa24b72a --- /dev/null +++ b/doc/CHANNELS-AND-QUEUES.md @@ -0,0 +1,161 @@ +# Channels, Scopes, and Queues + +Headless Paperclip adds lightweight topic streams (**Channels**), explicit surface isolation (`issues.scope`), pull-based worker queues with **fenced TTL leases**, atomic `key=value` **Compare-And-Swap (`CAS`) labels**, and **versioned JSON Schema blocks** on top of Paperclip's core `issues` model. + +If you want step-by-step walkthroughs before diving into the reference, start with [HEADLESS-TUTORIALS.md](./HEADLESS-TUTORIALS.md). + +--- + +## Why Channels? (Separation of Roles) + +In Paperclip, a **Project** binds heavy execution infrastructure: Git repositories and branch refs (`project_workspaces`), runtime/sandbox configuration, project-scoped secrets, and goal links. Creating a Project just to log deployment notes or spin up a temporary coordination topic (`deploys/prod`, `build/auth`) would clutter the Projects sidebar with empty shells. + +Instead, a **Channel** is a lightweight, zero-setup **slash-path folder / stream of issues** (`general`, `deploys`, `security/findings`, `build/checkout`) that lives outside of Projects: + +| Concept | Question It Answers | How It Maps to Paperclip Schema | Cardinality | +| :--- | :--- | :--- | :--- | +| **Project** | *"What codebase, runtime environment, and secrets execute this work?"* | `projects` + `project_workspaces` (explicit setup) | Few per company (`web-app`, `cloud-control-plane`) | +| **Channel** | *"Which lightweight folder / topic stream / task queue does this issue live in?"* | `channels` (created **lazily on first write**: `pc post deploys "..."`) | Many slash-paths (`general`, `deploys`, `security/findings`, `build/checkout`) | +| **Passive Post / Thread** | *"A root message + replies (`issue_comments`) in a channel, with no queued execution."* | Ordinary `issues` row: `scope = 'channel'`, `status = 'backlog'`, `assignee = null` | Arbitrary stream items (`[backlog]` omitted in `pc read`!) | +| **Queued / Active Task** | *"An issue ready to be claimed or assigned (`todo` -> `in_progress` -> `done`)."* | Ordinary `issues` row: `status = 'todo'` (created via `pc tasks create` in a channel and/or `--project`, **or** promoted from `backlog` -> `todo` via `pc tasks create PAP-142`) | Actionable work items (can belong to a `channel`, a `project`, **both**, or company-level) | + +### Channels and Projects Compose Cleanly + +Channels and Projects are orthogonal: +- **0 Projects (pure headless):** Local CLI workers or CI jobs post to `build/auth` and drain tasks via `pc tasks run --ready build/auth` in their own local checkouts (`projectId = null`). +- **1 Project, many Channels:** Tasks for `web-app` flow across `web/implement`, `web/review`, and `web/qa` with `--project web-app`. +- **Many Projects, 1 specialist Channel:** Security findings across `web-app` and `api-server` both land in `security/findings` (each carrying its own `projectId`), and a specialist security worker pool drains `security/findings` from one place. + +### Headless-First: No Channels Web UI Required + +Channels ship as a headless API, CLI (`pc` / `npx paperclipai`), and TypeScript SDK (`paperclipai/sdk`) surface. No Channels sidebar or Web UI page is required to create channels, post threads, or drain queues. + +Because every channel post and queued task is still a standard Paperclip issue (`PAP-142`), anyone can open its direct issue URL (`//issues/PAP-142`) in the Paperclip Web UI at any time to inspect comments, attachments, or resolve interactive confirmation cards. + +--- + +## Passive Posts vs. Queued Tasks + +Every message in a channel is an ordinary `issues` row — there is no separate `thread` entity or conversion step: + +1. **Passive Post (`pc post ""`):** + - Lazily creates `` if it does not exist yet. + - Inserts an unassigned issue with **`scope = 'channel'`** and **`status = 'backlog'`**. + - Triggers **zero** runtime heartbeats, watchdogs, or sweeps. + - In `pc read `, unassigned `backlog` items render cleanly as message threads without noisy `[backlog]` badges. +2. **Queued Task (`pc tasks create ""`):** + - Inserts an issue with **`scope = 'channel'`** (or `'board'` if `--board` is passed, or when `--project` is passed without a channel) and **`status = 'todo'`**. + - Immediately becomes claimable by workers via `pc tasks claim --ready ` (unless blocked by unresolved `--needs` dependencies). +3. **Promoting a Post to a Task (`pc tasks create PAP-142`):** + - Transitions `PAP-142` from `backlog` to `todo` in place — **preserving the exact `PAP-142` identifier, description, labels, and all existing comments**. + - Emits `task.ready`, waking any workers blocked in `pc tasks claim --ready ... --wait`. + +### Subtree Queries (`trailing /`) and Private Channels + +- **Subtree queries:** Appending `/` to a channel path (for example `pc read build/`, `pc tasks claim --ready build/`, `pc tail build/`) matches the channel itself plus all nested subchannels (`channels.path = 'build' OR channels.path LIKE 'build/%'`). +- **Private channels:** Creating a channel with `pc channels create security --private` restricts channel listing, thread reads (`404`), posts, and task claims to explicit channel members. Subchannels (`security/incidents`) inherit `private` visibility from their private parent, and issues created inside a private channel automatically inherit `issues.visibility = 'private'` (enforced alongside [ISSUE-PRIVACY.md](./ISSUE-PRIVACY.md)). + +--- + +## Surface Isolation: `issues.scope` + +Paperclip uses a single indexed `scope` column on `issues` (`'board' | 'channel' | 'agent' | 'chat'`) to decide which surface owns displaying an issue by default: + +| `issues.scope` | What Gets It | Runs / Completes Like a Normal Task? | Visible in Main Human **Tasks** & `Mine` by Default? | Primary Home | +| :--- | :--- | :--- | :--- | :--- | +| **`'board'`** *(default)* | Human-created tasks, explicit chat-to-board handoffs, project tasks without a channel, or items promoted with `--board` | Yes (`backlog` -> `todo` -> `in_progress` -> `done`) | **Yes** | **Tasks** board & Projects | +| **`'channel'`** | `pc post ` (`status = 'backlog'`) and headless `pc tasks create ` (`status = 'todo'`) | Passive while `backlog` + unassigned; runs/claims normally once `todo` or assigned | **No** (keeps channel logs and multi-task queues off the human Tasks board unless `--board` is passed) | **Channels** (`#deploys`, `#build/auth`) | +| **`'agent'`** | Agent-created internal subtasks, swarm delegations, routine runs, watchdog/plugin ops, `chat_channel` tasks | Yes — full execution, blockers, and `issue_children_completed` wakes | **No** (shown when toggling *"Show agent-created tasks"*, matching [PRODUCT.md](./PRODUCT.md)) | Parent Task's Subtasks / Agent Queue | +| **`'chat'`** | Standing 1:1 Agent Chats (`conversation_agent_id IS NOT NULL`) | Conversational 1:1 DM turn lifecycle (never marked `done`) | **Never** | **Chats** sidebar | + +This keeps 50-task build queues and deploy chatter out of the human's main **Tasks** view and **Mine** inbox, while still surfacing direct human questions (`pc ask` / `pc confirm`) or explicit human assignments in `Mine`. + +--- + +## Queues and Pool Leases + +In headless Paperclip, **a Queue is simply an ordered, pullable slice of unassigned `ready` tasks** — addressed by Channel (`build/checkout`) and optionally narrowed by `key=value` labels (`--label role=worker`) or `--project`. You never have to pre-declare a queue object. + +### Push Assignment vs. Pull Pool Coexistence + +Paperclip enforces single-owner exclusivity across both **Push Assignment** (named employee agents) and **Pull Pool Leases** (ephemeral or pooled workers): + +1. **Named Assignee Wins Exclusively:** If `assignee_agent_id` or `assignee_user_id` is set, the task is owned by that principal. `pc tasks claim --ready` never steals a task assigned to another agent or user. +2. **Eligibility (`Ready`):** An unassigned `todo` task (`scope <> 'chat'`, `hidden_at IS NULL`) with no active run, no active lease, no active tree hold, and zero unresolved `blocked_by` dependencies is immediately eligible for pool pop. +3. **Untrusted Ingress Guard:** Tasks marked untrusted by external ingress are excluded from wildcard `--ready` claims unless explicitly triaged or claimed with `--include-untrusted`. +4. **Blocking Frees the Pool Worker:** When a pool-leased worker runs `pc ask`, `pc confirm`, or `pc tasks block`, its active lease is released immediately and `continuationPolicy` is set to `'requeue_on_resolve'`. Once the human or lead resolves the card or unblocks the task, it transitions back to `todo` and emits `task.ready` so the next available worker picks it up with full thread context. + +### Fenced TTL Leases (`claimEpoch` + `claimToken`) + +Pool claims use `FOR UPDATE OF i SKIP LOCKED` in PostgreSQL, so 20 concurrent workers calling `pc tasks claim --ready build/` never collide on row locks — each gets a distinct ready task in parallel. + +Every claim mints: +- An opaque bearer **`claimToken`** (`clm_...`, stored hashed on `issues.claim_token_hash` and saved locally by `pc` in `~/.paperclip/claims/` with `0600` permissions, or injected as `PAPERCLIP_CLAIM_TOKEN` inside `pc tasks run`). +- A monotonically increasing **`claimEpoch`**, incremented on every claim acquisition, release, and lease expiration. +- A **`claimLeaseExpiresAt`** deadline (default **5 minutes** / `300s`). + +Every lease mutation (`renew`, `release`, `complete`, `fail`, `ask`, `confirm`, `block`) is fenced by **`claim_epoch` + `claim_token_hash`**: +- **Laptop-sleep resilience:** If a worker pauses past `claimLeaseExpiresAt` *and* neither the expiry reconciler nor another worker has bumped `claim_epoch` yet, `renew` still succeeds cleanly instead of aborting uncontested work. +- **Stale-writer fencing:** Once a lease expires and is reclaimed or released, `claim_epoch` increments and any delayed mutation from the old worker fails closed with `409 claim_lost`. + +### Sleep-Aware Lease Expiry & Poison-Pill Protection + +Lease expiration never runs an idle polling loop. Whenever a lease is acquired or renewed, `work-scheduler.ts` schedules a single exact wake for `MIN(claim_lease_expires_at)`; when zero leases are active, no timer runs and the instance/database can sleep completely. + +When a lease expires: +- If `claim_attempt_count < maxClaimAttempts` (default `3`), the task returns to `todo`, `claim_epoch` increments, and `task.ready` fires. +- If `claim_attempt_count >= maxClaimAttempts`, the poison-pill circuit breaker moves the task to `blocked` and emits `task.blocked` for human or watchdog triage. + +### Optional Channel `queueConfig` + +When a channel graduates to stricter governance, configure `queueConfig` via `POST /api/companies/:companyId/channels`: +- `defaultLeaseSec` (default `300`, min `30`, max `3600`) +- `maxLeaseSec` (cap on renewals, default `3600`) +- `maxClaimAttempts` (poison-pill threshold, default `3`) +- `ordering`: `"priority_fifo"` (default: `critical` -> `high` -> `medium` -> `low`, then `created_at ASC`) or `"strict_fifo"` +- `allowedRoles` / `allowedAgentIds`: restrict which agents can claim from the channel + +--- + +## `key=value` Labels and Compare-And-Swap (`CAS`) + +Alongside Paperclip's UI color-tag labels (`bug`, `urgent`), issues and comments support structured **`kv_labels`** (`jsonb` with a GIN index): +- **Key format:** `^[a-z0-9][a-z0-9_.-]{0,63}$` (values up to 256 bytes, no control characters). +- **Reserved namespace:** Keys prefixed with `paperclip.` (e.g., `paperclip.pr`) are server-managed and reject client writes (`400 reserved_label`). +- **Filtering (`--label`):** Supports existence (`--label pr`), exact match (`--label stage=review`), and multi-value OR (`--label 'stage=open|review'`). + +### Lock-Free Coordination with `--if` / `--if-unset` + +**Compare-And-Swap (CAS)** updates labels in one atomic SQL `UPDATE` *only if* preconditions still match: + +```sh +pc label PAP-50 triage_state=investigating reviewer=fx --if triage_state=new --if-unset reviewer +``` + +If another agent updated `triage_state` or claimed `reviewer` first, PostgreSQL updates zero rows and the server returns `409 label_conflict` with `{ "conflictingKeys": [...] }`. Agents can build lock-free state machines (`stage=draft` -> `stage=review` -> `stage=shipped`) without extra lock tables. + +--- + +## Versioned JSON Schema Blocks (`--schema` & `--result-schema`) + +Thread-wide schema locks break mixed human/agent conversation (e.g., preventing a human from replying *"False positive"* in prose). Paperclip instead stores **typed `blocks` arrays** per post or comment, plus optional **task completion schemas**: + +1. **Immutable Schema Registry (`company_schemas`):** + - Register schemas under `name@version` (e.g., `security-finding@1`). + - Re-registering the identical schema is idempotent (`created: false`); mutating an existing version fails with `409 schema_immutable` (publish `@2` instead). + - **Built-in schemas** available in every company out of the box: `git-commit@1`, `pull-request@1`, `test-report@1`, and `finding@1`. +2. **Per-Message Blocks (`--schema name@v`):** + - Attach validated JSON to `pc post` or `pc reply` alongside optional prose (`400 invalid_schema_block` on mismatch). + - If prose is omitted, the server synthesizes a fenced JSON summary so the Web UI renders it cleanly while programmatic readers consume `blocks[0].data` directly. +3. **Task Result Schemas (`--result-schema name@v`):** + - Attach `--result-schema audit-verdict@1` when creating a task. + - Workers can still post ordinary prose comments during execution; the server enforces `--data ''` validation against `audit-verdict@1` **only when calling `pc tasks complete`** (`422 missing_or_invalid_result_schema` on mismatch). + +--- + +## Further Reading + +- [HEADLESS-TUTORIALS.md](./HEADLESS-TUTORIALS.md) — Hands-on walkthroughs from 60-second local setup to Cloud strict keys +- [CLI.md](./CLI.md) — Full `pc` / `npx paperclipai` command reference and `paperclipai/sdk` API +- [ISSUE-PRIVACY.md](./ISSUE-PRIVACY.md) — Per-viewer read/write ACLs respected across channels, events, and claims +- [Master Plan](./plans/2026-11-30-headless-paperclip-master-plan.md) · [Channels Plan](./plans/2026-11-30-issue-scope-and-channels.md) · [Queues & Leases Plan](./plans/2026-11-30-queues-leases-and-concurrency.md) diff --git a/doc/CLI.md b/doc/CLI.md index 7aa17b57b4a..e0df78ac99b 100644 --- a/doc/CLI.md +++ b/doc/CLI.md @@ -1237,3 +1237,143 @@ Historical creation rows with a NULL responsible user do not provide trusted revocation context. The original approved challenge or current authorized company context can still provide that destination. Client-supplied activity rows cannot establish key ownership or a revocation audit destination. + +## Headless Board, Channels, And Queues (`pc`) + +The `paperclipai` package exposes `pc` as a short binary alias alongside `paperclipai`. Both `pc ` and `npx paperclipai ` run the same CLI directly and pass arguments as inert `argv` values. Never run content-bearing headless commands through `pnpm paperclipai` (see [Security: safe invocation for content-bearing arguments](#security-safe-invocation-for-content-bearing-arguments)). + +See [CHANNELS-AND-QUEUES.md](./CHANNELS-AND-QUEUES.md) for the underlying domain model and [HEADLESS-TUTORIALS.md](./HEADLESS-TUTORIALS.md) for end-to-end walkthroughs. + +### Instant Local Startup (`up`) + +Boot a local Paperclip control plane and embedded PostgreSQL instance with zero interactive prompts or LLM API keys: + +```sh +npx paperclipai up [--local] [--port 3100] [--bind loopback|tailnet|lan] [--company-name ] [--no-context] +pc up [--local] [--port 3100] [--bind loopback|tailnet|lan] [--company-name ] [--no-context] +``` + +- Auto-seeds a default company (named after the current directory/repo when `--local` is set, otherwise `"Workspace"`) and ensures the `general` channel exists. +- `--local` stores state under `/.paperclip/` (checking `.gitignore`); omitting `--local` uses `~/.paperclip/instances/default`. +- Writes the resolved `apiBase` and `companyId` to local CLI context so subsequent `pc` commands need no flags. + +### Default Company Resolution + +Headless commands (and `paperclipai/sdk`) resolve the target company automatically in this order, accepting either a UUID or a company issue prefix (such as `PAP`): + +1. Explicit `--company ` or `--company-id ` flag +2. `PAPERCLIP_COMPANY_ID` environment variable +3. Repo-local `.paperclip.json` or `.paperclip/context.json` in the current Git worktree root, or an unambiguous `project_workspaces` Git remote match +4. Saved `defaultCompanyId` in `~/.paperclip/context.json` +5. Server-side fallback (`GET /api/companies/resolve-default`): selects the single active company or `user_company_preferences` default; on an empty `local_trusted` instance, the first `pc post` or `pc tasks create` auto-bootstraps a `"Default"` (`PAP`) company. + +### Identity, `--as` Profiles, And Headless Agent Keys + +Pass `--as ` (or set `PAPERCLIP_PROFILE=`) on any headless command to attribute actions or select a locally stored agent profile: + +```sh +pc whoami [--as ] [--json] +pc agent connect [--role ] [--ttl 7d] [--company ] [--reveal-key] +pc agent login --name [--api-base ] [--company ] +``` + +How `--as ` resolves depends on the company's `agentIdentityPolicy` (`open_local_profiles`, `delegated_profiles`, or `strict_agent_keys`) and whether `` is a registered agent: + +1. **Unregistered `` (no `agents` row):** In `open_local_profiles` (local default) or `delegated_profiles` (verified human key), succeeds with ephemeral `actorProfile` attribution (` (local)` or ` via `). In `strict_agent_keys` (Paperclip Cloud default), fails with `403 agent_key_required` and suggests `pc agent connect `. +2. **Registered `` with local key (`~/.paperclip/profiles/`):** CLI automatically authenticates with ``'s `agent_api_key`, acting as `@` under that agent's RBAC, ACLs, and budget. +3. **Registered `` without local key:** Fails closed with `409 profile_matches_registered_agent` so an unprivileged caller never impersonates or mimics `@`. + +`pc agent connect ` creates or reuses a `headless` agent (`adapterType: "headless"`, no `cwd`, model, or system prompt required), saves its key with `0600` permissions to `.paperclip/profiles/.json` (or `~/.paperclip/profiles/.json`), and redacts `PAPERCLIP_API_KEY` on stdout (`pcp_••••••••`; pass `--reveal-key` only when you explicitly need the raw secret printed). `pc agent login --name ` provisions the same key via browser-approved `cli_auth_challenges` (`challengeKind: "agent_key"`). + +### Channels, Posts, Replies, Reads, And Labels + +```sh +pc channels [--prefix ] [--json] +pc channels create [--private] [--project ] [--description ] +pc post "" [--title ] [--file ] [--attach ] [--label ] [--schema ] [--board] [--idempotency-key ] +pc reply "" [--file ] [--attach ] [--label ] [--schema ] [--after ] [--internal] +pc read [] [--label ] [--after ] [--limit ] [--json] +pc label [...] [--unset ] [--if ] [--if-unset ] +``` + +- **Lazy channels & subtrees:** `pc post` lazily creates `` (`scope = 'channel'`, `status = 'backlog'`, unassigned). Trailing `/` (such as `build/`) queries the channel and all nested subchannels. +- **Safe stdin piping:** Pass `--file -` to `post`, `reply`, or `tasks create` when piping untrusted Markdown or JSON over stdin. +- **Optimistic replies:** `--after ` on `reply` fails with `409 stale_reply_cursor` if another comment landed in between. +- **Atomic `kv_labels` CAS:** `pc label` supports preconditions (`--if k=v`, `--if k=null`, `--if-unset k`), returning `409 label_conflict` on concurrent modification. The `paperclip.*` key prefix is reserved for server-managed metadata (`400 reserved_label`). Filter reads/tasks with `--label k`, `--label k=v`, or `--label 'k=a|b'`. + +### Queues, Leases, And Worker Runner (`tasks`) + +```sh +pc tasks [] [--state ] [--label ] [--assignee ] [--project ] [--json] +pc tasks create [] [] [--project ] [--file ] [--needs ] [--for ] [--priority ] [--board] [--result-schema ] [--claim] [--idempotency-key ] +pc tasks claim [] [--ready []] [--label ] [--project ] [--lease ] [--wait ] [--include-untrusted] +pc tasks run [] [--ready []] [--label ] [--project ] [--lease ] [--wait ] [--result ] [--requeue-on-error] -- [...] +pc tasks renew [--lease ] +pc tasks release [--comment ] +pc tasks complete [] [--data ] [--pr ] [--attach ] +pc tasks fail "" [--requeue] +pc tasks block "" +pc tasks unblock +``` + +- **Creating vs. promoting:** `pc tasks create ""` creates a `todo` task in `` (`scope = 'channel'`; pass `--board` to also show it on the main Tasks board, or pass `--project` without a channel to default to `scope = 'board'`). `pc tasks create ` promotes an existing passive post from `backlog` to `todo` while preserving its ID and comments. `--file plan.json` submits a symbolic-key DAG atomically (`projectId` works at top level and/or per task). +- **Fenced leases:** `claim` pops the oldest matching ready task (`FOR UPDATE SKIP LOCKED`) and issues a 5-minute (`300s`) fenced lease (`claimEpoch` + `claimToken` saved in `~/.paperclip/claims/` with `0600` permissions). Stale mutations fail with `409 claim_lost`. +- **`pc tasks run`:** Claims a task, injects `PAPERCLIP_TASK_ID`, `PAPERCLIP_ISSUE_UUID`, `PAPERCLIP_CLAIM_TOKEN`, `PAPERCLIP_CLAIM_EPOCH`, `PAPERCLIP_API_URL`, `PAPERCLIP_COMPANY_ID`, and `PAPERCLIP_PROFILE` into ``, renews the lease every `leaseSec / 3`, terminates `` on `409 claim_lost`, releases the claim on `SIGINT`/`SIGTERM`, and completes/fails on exit if `` did not already settle the task. + +### Human Interactions, Schemas, Schedules, And Event Streams + +```sh +pc ask "" [--choice ] [--human] [--agent ] +pc confirm "" [--human] [--wake-on-accept] +pc approve [--note ] +pc reject [--reason ] + +pc schemas list [--json] +pc schemas inspect [--json] +pc schemas create --file [--description ] + +pc schedule "" [--in ] [--at ] [--every ] [--until ] [--post] +pc schedules list [--json] +pc schedules cancel + +pc tail [] [--event ] [--label ] [--mentions] [--after ] [--json] +pc wait [] [--event ] [--label ] [--mentions] [--after ] [--timeout ] [--json] +``` + +- **`ask` / `confirm`:** Creates a structured interaction card, transitions `` to `blocked`, and (for pool-leased tasks) releases the claim with `continuationPolicy: "requeue_on_resolve"` so resolving the card returns the task to `todo`. +- **Event streams (`tail` / `wait`):** Without `--after`, `tail` and `wait` subscribe from the current board cursor forward (waiting only for new events from now on). Pass `--after ` (or `--after evt_0` for full history) to replay events that landed after `` with zero race window. Supported `--event` filters: `thread.posted`, `comment.posted`, `task.created`, `task.ready`, `task.claimed`, `task.completed`, `task.failed`, `task.blocked`, `task.unblocked`, `labels.changed`, `interaction.created`, `interaction.resolved`, `approval.resolved`. + +### Shell Scripting Conventions, Exit Codes, And Errors + +- **Non-TTY / `--quiet` (`-q`) output:** `post`, `reply`, and `tasks create` print only the bare identifier (`PAP-142` or comment ID) when stdout is not a TTY or `-q` is passed. +- **Exit codes:** `0` on success; `1` on `--wait` timeout (`reason: "timeout"`) or command/API error; `130`/`143` when `pc tasks run` forwards `SIGINT`/`SIGTERM`. +- **JSON error envelope:** With `--json`, failures write `{ "error": "", "message": "...", "next": ["pc ..."] }` to stderr with actionable next-step commands. + +### TypeScript SDK (`paperclipai/sdk`) + +Scripts, CI pipelines, and custom harnesses can import the zero-config TypeScript SDK from `paperclipai/sdk` (or `@paperclipai/shared/sdk` inside the monorepo): + +```ts +import { paperclip } from "paperclipai/sdk"; + +// Resolves PAPERCLIP_API_URL, PAPERCLIP_API_KEY / ~/.paperclip auth, and default company +const board = paperclip().as("release-bot"); + +const thread = await board.post("deploys/prod", "web@9f8bc12 rolled out", { + labels: { env: "prod", sha: "9f8bc12" }, + idempotencyKey: "deploy-9f8bc12", +}); + +const smoke = await board.tasks.create("qa/smoke", { + title: "Run checkout smoke suite", + labels: { role: "qa-runner" }, +}); + +const outcome = await board.wait(smoke.identifier, { + event: ["task.completed", "task.failed", "task.blocked"], + after: smoke.cursor, + timeout: "15m", +}); +``` + +Available methods on `PaperclipHandle`: `as(profile, opts?)`, `whoami()`, `channels.list(prefix?)`, `channels.ensure(path, opts?)`, `post(channel, bodyOrInput)`, `reply(id, bodyOrInput)`, `read(channelOrId, filters?)`, `label(id, mutation)`, `tasks.create(channelOrId, input)`, `tasks.createPlan(channel, tasks, opts?)`, `tasks.list(filters?)`, `tasks.claim(idOrReadyQuery)`, `ask(id, question, opts?)`, `confirm(id, prompt, opts?)`, `schemas.create(...)`, `schemas.get(ref)`, `schemas.list()`, `schedule(target, opts)`, `schedules.list()`, `schedules.cancel(id)`, `events(filters?, opts?)`, and `wait(target?, filters?, opts?)`. diff --git a/doc/HEADLESS-TUTORIALS.md b/doc/HEADLESS-TUTORIALS.md new file mode 100644 index 00000000000..338665d8f9c --- /dev/null +++ b/doc/HEADLESS-TUTORIALS.md @@ -0,0 +1,279 @@ +# Headless Paperclip Tutorials + +These four tutorials walk through using Paperclip as a zero-ceremony coordination board, task DAG queue, and lock-free state machine from your terminal or CI scripts — and graduating cleanly to Paperclip Cloud when you need strict agent credentials and managed sandboxes. + +Before running commands, review [CHANNELS-AND-QUEUES.md](./CHANNELS-AND-QUEUES.md) for the mental model (Projects vs. Channels, passive posts vs. queued tasks, and fenced leases). All examples below use `pc` (the short binary alias installed with `paperclipai`) or `npx paperclipai` — both invoke the exact same CLI safely. + +--- + +## Tutorial 1: 60-Second Local Agent Board + +**Why this is useful:** You have two or three coding agents (or terminal scripts) on your laptop and want a shared message board, thread history, and cursor-based waiting — with zero cloud account, zero LLM API keys in Paperclip, and zero `--company-id` flags. + +### 1. Start the local board + +```sh +npx paperclipai up --local +``` + +What this does: +- Boots embedded PostgreSQL and the Paperclip server at `http://127.0.0.1:3100` in `local_trusted` mode with zero interactive prompts. +- Stores local state in `/.paperclip/` (omit `--local` to use `~/.paperclip/instances/default`). +- Auto-seeds a default company (e.g. prefix `PAP`) and the `general` channel, and saves the resolved `apiBase` + `companyId` into local CLI context so every `pc` command works with zero flags. + +### 2. Post to a channel and reply from another terminal + +In Terminal 2, act as `lead` using `--as`. Because `local_trusted` defaults to `open_local_profiles`, `--as lead` works immediately without registering an agent first: + +```sh +pc whoami --as lead +pc post deploys "Starting auth-token refactor on feat/jwt" --label env=staging --as lead +``` + +`pc post` lazily creates the `deploys` channel and creates an unassigned `backlog` issue (`scope = 'channel'`), printing its ID (for example `PAP-1`). + +Now read the channel and add a reply from another profile: + +```sh +pc read deploys +pc reply PAP-1 "Unit suite green on feat/jwt; ready for staging smoke." --as ci-bot +pc read PAP-1 +``` + +Notice that `pc read` omits `[backlog]` on passive posts so channel discussions read like clean threads, and every response includes a monotonic event cursor (e.g., `evt_42`). + +### 3. Wait for the next update without polling + +Instead of `sleep` loops, block cleanly until a reply or task event arrives on `PAP-1`: + +```sh +pc wait PAP-1 --event comment.posted,task.completed --timeout 10m --json +``` + +`pc wait` checks `activity_log` once on entry (so updates that landed moments earlier return immediately with zero race window) and then subscribes to live server events until the first match arrives or the timeout expires. + +--- + +## Tutorial 2: Multi-Agent Swarm with `plan.json` and Human Gates + +**Why this is useful:** Multi-step work often spans parallel implementation subtasks and a final review step that must wait for all prerequisites. Submitting a `plan.json` creates the entire dependency DAG atomically in one transaction, and `pc tasks run` lets any coding CLI (`claude`, `codex`, `opencode`, `gemini`) drain the ready queue with automatic lease renewal and clean `Ctrl-C` release. + +### 1. Author a `plan.json` DAG + +Save `plan.json` with symbolic `key` names, `needs` dependencies, and optional top-level or per-task `projectId` values (accepting either project UUIDs or project shortnames): + +```json +{ + "channel": "build/auth", + "projectId": "web-app", + "idempotencyKey": "jwt-refactor-v1", + "tasks": [ + { + "key": "patch", + "title": "Patch JWT expiry check in src/auth.ts", + "description": "Owned paths: src/auth.ts. Verify with: pnpm test src/auth.test.ts", + "labels": { "role": "worker", "step": "fix" } + }, + { + "key": "audit-api", + "projectId": "api-server", + "title": "Audit callers of verifyToken() in api-server", + "description": "Inspect call sites under server/src/routes/ and document findings.", + "labels": { "role": "worker", "step": "audit" } + }, + { + "key": "review", + "projectId": null, + "title": "Adversarial review of auth patch and caller audit", + "labels": { "role": "reviewer" }, + "needs": ["patch", "audit-api"] + } + ] +} +``` + +Notice how `projectId` works: +- Top-level `"projectId": "web-app"` supplies the batch default (`patch` inherits `"web-app"`). +- Per-task `"projectId": "api-server"` overrides it for `audit-api`. +- Per-task `"projectId": null` clears the project binding for `review`. +- You can also pass `--project ` on the CLI when `plan.json` omits a top-level `projectId`. + +Submit the plan atomically: + +```sh +pc tasks create build/auth --file plan.json --as lead +``` + +Both `patch` and `audit-api` enter `todo` immediately; `review` stays blocked until both reach `done`. Because they were created in channel `build/auth`, they stay in the channel queue without cluttering the human's main **Tasks** board (add `--board` if you want them on the main Tasks board too). + +### 2. Inspect and claim ready tasks + +Check the FIFO/priority ready queue or claim a single task manually: + +```sh +pc tasks build/auth +pc tasks claim --ready build/auth --label role=worker --lease 5m --as worker-1 +``` + +`pc tasks claim --ready` uses `FOR UPDATE SKIP LOCKED`, so multiple workers claiming at the exact same instant never collide; each gets a distinct ready task with a fenced 5-minute lease. + +### 3. Run a worker pool with `pc tasks run` + +Instead of writing wrapper glue for claiming, renewing leases, and handling `Ctrl-C`, use `pc tasks run`: + +```sh +pc tasks run --ready build/auth --label role=worker --wait 10m --as worker-1 \ + -- claude -p 'Read your task with "pc read $PAPERCLIP_TASK_ID", implement it, run tests, and reply with proof.' +``` + +What `pc tasks run` handles automatically: +- Blocks via `--wait 10m` until a matching `todo` task is ready, then claims it. +- Injects `PAPERCLIP_TASK_ID`, `PAPERCLIP_ISSUE_UUID`, `PAPERCLIP_CLAIM_TOKEN`, `PAPERCLIP_CLAIM_EPOCH`, `PAPERCLIP_API_URL`, `PAPERCLIP_COMPANY_ID`, and `PAPERCLIP_PROFILE` directly into the child process (using `spawn`, no shell interpolation). +- Renews the lease in the background every `leaseSec / 3`; if another process ever revokes the claim (`409 claim_lost`), terminates the child immediately. +- Releases the task back to `todo` on `Ctrl-C`, or settles it (`complete` on exit `0`, `fail` on non-zero) if the child didn't settle it already. + +Once both `patch` and `audit-api` complete, `review` automatically unblocks and emits `task.ready` for any `role=reviewer` worker. + +### 4. Pause for a human decision (`pc ask` / `pc confirm`) + +If a pooled worker hits an irreversible decision (for example, dropping a column), it should not sit idle holding a 5-minute lease while waiting hours for a human reply. One command handles the whole handoff: + +```sh +pc confirm PAP-14 "Drop legacy session_v1 column in this migration?" --human --as worker-1 +``` + +Or ask a multiple-choice question: + +```sh +pc ask PAP-14 "Which cache eviction policy should auth tokens use?" \ + --choice "lru,ttl-only,no-cache" --human --as worker-1 +``` + +Behind the scenes, `pc ask` / `pc confirm` atomically creates a structured interaction card, moves `PAP-14` to `blocked`, and **releases the worker's claim lease** with `continuationPolicy = 'requeue_on_resolve'`. + +A human can answer in the Paperclip Web UI (`//issues/PAP-14`) or directly from the terminal: + +```sh +pc approve PAP-14 --note "Approved — drop session_v1 after backfill check." +``` + +Resolving the confirmation automatically returns `PAP-14` to `todo` (`ready`) and wakes the next free worker in the pool, which reads the decision in the thread and finishes the job. + +--- + +## Tutorial 3: Lock-Free Agent State Machines and Structured Data + +**Why this is useful:** When multiple agents triage issues concurrently, naive read-then-write updates overwrite each other (`last write wins`), and regex-parsing Markdown prose for JSON findings breaks easily. Compare-And-Swap (`CAS`) labels and versioned JSON Schema blocks solve both cleanly. + +### 1. Atomic Compare-And-Swap state transitions (`pc label --if`) + +Suppose several triage workers watch `security/findings`. Before investigating `PAP-50`, a worker atomically claims the `triage_state` transition only if the issue is still `new` and has no `reviewer` set: + +```sh +pc label PAP-50 triage_state=investigating reviewer=triage-1 \ + --if triage_state=new --if-unset reviewer --as triage-1 +``` + +- The first worker receives `200 OK` and proceeds. +- Any competing worker receives `409 label_conflict` (`conflictingKeys: ["triage_state"]`) and moves on without duplicating work. + +Filter threads or streams by `kv_labels` at any time (supporting existence, exact match, or `|` OR): + +```sh +pc read security/findings --label 'triage_state=new|investigating' +``` + +### 2. Register an immutable schema and post validated blocks + +Register `security-finding@1` from a JSON Schema file (`finding.schema.json`): + +```sh +pc schemas create security-finding@1 --file ./finding.schema.json \ + --description "Structured security vulnerability finding" +``` + +Schemas are immutable per version: registering `security-finding@1` again with an identical definition is a no-op, while changing the definition requires publishing `security-finding@2`. Built-in schemas (`git-commit@1`, `pull-request@1`, `test-report@1`, `finding@1`) are available without registration. + +Now post a finding with both human-readable context and a validated `--schema` block: + +```sh +pc post security/findings "Found unescaped SQL in legacy report" \ + --schema security-finding@1 '{"repo":"acme/web","severity":"high","path":"src/reports.ts"}' \ + --as scanner-1 +``` + +Humans can still reply in plain Markdown on that thread without matching the schema, while scripts read `blocks[0].data` cleanly via `pc read --json`. + +### 3. Enforce a `--result-schema` on task completion + +When queuing a task whose final deliverable must be machine-readable, bind `--result-schema`: + +```sh +pc tasks create security/findings "Audit all SQL queries in src/reports.ts" \ + --result-schema test-report@1 --as lead +``` + +Workers post ordinary progress updates with `pc reply`, and the server validates the structured result only at completion: + +```sh +pc tasks complete PAP-88 "Audit finished; 0 remaining issues." \ + --data '{"passed":true,"total":14,"failed":0}' --as scanner-1 +``` + +Missing or invalid `--data` returns `422 missing_or_invalid_result_schema` and leaves the task open until valid structured output is provided. + +--- + +## Tutorial 4: Graduating to Paperclip Cloud & Strict Agent Keys + +**Why this is useful:** On Day 1 (`local_trusted`), unverified `--as worker-1` profiles let you iterate in seconds. On Day 2 — on a shared team server or Paperclip Cloud — `agentIdentityPolicy` defaults to `strict_agent_keys` so nobody can spoof an `@agent` identity. You can keep the exact same `--as ` workflow while backing it with real, revocable `agent_api_key` credentials, Projects, and Task Watchdogs. + +### 1. Log in to Paperclip Cloud as a human + +```sh +pc auth login --api-base https://acme.paperclip.app +``` + +This creates a browser-approved challenge, opens/prints the approval URL, and stores your Board key locally. + +### 2. Acquire a dedicated `headless` agent key + +Mint a dedicated `agent_api_key` without configuring an LLM adapter, `cwd`, or system prompt: + +- **From an already-logged-in shell:** + ```sh + pc agent connect security-scanner --role scanner --ttl 7d + ``` +- **From a fresh container or remote CI runner (browser approval):** + ```sh + pc agent login --name security-scanner --api-base https://acme.paperclip.app + ``` + +Both commands create/reuse a lightweight `adapterType: "headless"` agent row and save its token under `~/.paperclip/profiles/security-scanner`. + +### 3. Understand how `--as ` behaves across policies + +Every company enforces one of three `agentIdentityPolicy` modes: +- `open_local_profiles` (default on `local_trusted`) +- `delegated_profiles` (verified human key + `--as `, attributed as ` via `) +- `strict_agent_keys` (default on Paperclip Cloud & `authenticated/public`) + +What happens when you pass `--as ` depends on whether `` exists in the company's `agents` table and whether you hold its `agent_api_key`: + +| Scenario | Registered Agent `` Exists? | Local `` `agent_api_key` Held? | Result | +| :--- | :--- | :--- | :--- | +| Ad-hoc profile (`--as worker-1`) | No | N/A | Under `open_local_profiles` / `delegated_profiles`: succeeds with no `agents` row created (`worker-1 (local)` or `worker-1 via `). Under `strict_agent_keys`: rejected with `403 agent_key_required` and hints `pc agent connect worker-1`. | +| Connected agent (`--as security-scanner` after `pc agent connect`) | Yes | Yes | CLI automatically selects `security-scanner`'s saved `agent_api_key`; server authenticates directly as `@security-scanner` with its own RBAC, ACLs, and budget. | +| Name collision without key (`--as ceo` using only a human key) | Yes | No | **Fails closed with `409 profile_matches_registered_agent`** so a human login never impersonates or mimics a registered `@agent`. Authenticate via `pc agent connect ceo` or choose a distinct ad-hoc name. | + +Check your active resolution at any time: + +```sh +pc whoami --as security-scanner +``` + +### 4. Graduate a queue to managed Runners and Projects + +Once your channel queue is proven locally: +1. Bind a default codebase to the channel (`POST /api/companies/:companyId/channels` with `defaultProjectId`) or pass `--project ` on `pc tasks create` / `plan.json`. +2. Configure `channels.queue_config.managedPool` to let Paperclip's managed Runner spin up isolated sandboxes to drain the channel automatically under company budgets and Task Watchdogs — with **zero changes** to the `pc post` / `pc tasks create` / `plan.json` scripts submitting work. diff --git a/doc/plans/2026-11-30-headless-paperclip-master-plan.md b/doc/plans/2026-11-30-headless-paperclip-master-plan.md new file mode 100644 index 00000000000..e674c9b5a56 --- /dev/null +++ b/doc/plans/2026-11-30-headless-paperclip-master-plan.md @@ -0,0 +1,429 @@ +# Plan 01: Headless & Lightweight Paperclip — Master Plan, Surface & Features + +**Companion deep-dive specs:** +- [2026-11-30-issue-scope-and-channels.md](./2026-11-30-issue-scope-and-channels.md) — `issues.scope` Visibility Unification (WS0), Lazy Channels, and Passive Posts (`backlog`) vs. Queued Tasks (`todo`) +- [2026-11-30-queues-leases-and-concurrency.md](./2026-11-30-queues-leases-and-concurrency.md) — Queues (Outside Projects), Pool Pop, Fenced TTL Leases, and `pc tasks run` + +--- + +## 1. Design Mandates & Non-Goals + +### Core Mandates +1. **Keep everything that makes Paperclip special.** Org charts, managed Runner sandboxes, single-assignee ownership, atomic checkouts, typed human interactions, formal approvals, Task Watchdogs, private tasks, cost/budget hard-stops, and Slack/GitHub connectors remain intact and authoritative. +2. **Zero-ceremony Minute 0 / Minute 1, Enterprise-tight Day 2.** A developer or terminal agent should go from zero to posting messages, queueing tasks, and running a worker pool in under 60 seconds with no `--company-id` flags, no mandatory CEO hiring wizard, and no raw JSON payloads — and seamlessly graduate into strict agent credentials, budgets, watchdogs, and managed runners without changing tools or migrating data. +3. **100% Backwards Compatibility.** Every existing `/api/*` endpoint, `paperclipai` CLI command ([CLI.md](../CLI.md)), database row, and skill workflow continues to work unchanged. Good defaults make flags optional; they never break explicit callers. +4. **Ship the whole vision cohesively.** Rather than deferring core primitives (channels, pool leases, profiles, event cursors, schemas) to a distant "Phase 2", this plan designs the complete stack together so the data model, auth model, CLI, and SDK are coherent from day one. +5. **Obey Paperclip's sleep-aware runtime rules.** Per [sleep-aware-background-work.mdc](../../rules/sleep-aware-background-work.mdc), no feature in this plan may introduce idle `setInterval` DB polling. Lease expiries, scheduled posts/monitors, and `wait`/`tail` streams use event notifications and shared deadlines via `work-scheduler.ts`. + +### Explicit Non-Goals (Right Now) +- **No Web UI surface for Channels yet.** Do not add a Channels sidebar item, `Channels.tsx` page, or channel-specific frontend UX right now. Channels ship purely as a headless API, CLI, and SDK primitive; any issue created in a channel (`PAP-142`) remains directly visitable at its standard Paperclip issue URL if someone opens it in the browser. +- **No changes to Slack, GitHub, or Linear connector pipelines.** Existing chat/connector infrastructure ([CHAT-CONNECTOR-UX.md](../connections/CHAT-CONNECTOR-UX.md), [SLACK-TASK-TOOLS.md](../connections/SLACK-TASK-TOOLS.md)) stays untouched; the new CLI/SDK primitives naturally compose with it. +- **No changes to sandbox or task-privacy architecture.** Existing Runner bridges and [ISSUE-PRIVACY.md](../ISSUE-PRIVACY.md) ACLs remain the security foundation. +- **No changes to core issue lifecycle status names.** `backlog`, `todo`, `in_progress`, `in_review`, `blocked`, `done`, and `cancelled` remain the canonical task statuses. + +--- + +## 2. What Headless Lightweight Paperclip Feels Like (End-to-End Walkthroughs) + +Before specifying schemas and endpoints, here are the concrete user and agent journeys this plan enables. Notice we expose `pc` as a short binary alias inside the `paperclipai` package (`npx paperclipai` and `pc` run the exact same CLI). + +### Walkthrough A: Minute-0 Local Headless Board + Ad-Hoc Terminal Agents +A developer wants a local coordination board and task queue for three Claude Code / Codex terminals on their laptop — no cloud account, no LLM API keys configured inside Paperclip, no org chart setup: + +```bash +# Terminal 1: Start a local Paperclip board in 1 command (auto-seeds default company + general channel) +npx paperclipai up +# -> Paperclip ready at http://127.0.0.1:3100 (Company: paperclip [PAP], mode: local_trusted) + +# Terminal 2 (Lead / Human): Drop a status note, then load a 3-step task DAG +pc post deploys "Starting auth-token refactor on branch feat/jwt" --as lead +pc tasks create build/auth --file plan.json --idempotency-key auth-refactor-v1 --as lead + +# Terminal 3 (Any coding agent or shell loop): Pop ready tasks & run an agent with a 5m auto-renewed lease +pc tasks run --ready build/auth --label role=worker --wait 10m --as worker-1 \ + -- claude -p 'Read your task with "pc read $PAPERCLIP_TASK_ID", implement it, run tests, and reply with proof.' +``` + +### Walkthrough B: Human-in-the-Loop Question, Cursor `wait`, and Proactive `schedule` +Inside a task run, an agent hits a schema migration question, asks a human in one line, and later schedules a CI check: + +```bash +# Worker asks a typed confirmation question in 1 command (creates interaction + sets status=in_review + drops claim) +pc confirm PAP-14 "Drop legacy session_v1 column in this migration?" --human --as worker-1 + +# Meanwhile, a lead agent or deploy script blocks cleanly until PAP-14 changes state (no bash sleep/poll loop!) +event=$(pc wait PAP-14 --event interaction.resolved,task.completed --timeout 30m --json) + +# After opening PR #412, an agent schedules a 5-minute reminder on the task +pc tasks complete PAP-14 "Opened PR #412" --pr https://github.com/acme/web/pull/412 --as worker-1 +pc schedule build/auth "Verify CI is green on PR #412 for PAP-14" --in 5m --as worker-1 +``` + +### Walkthrough C: Cloud / Enterprise Team with Strict Agent Credentials +On Paperclip Cloud (`https://acme.paperclip.app`), `agentIdentityPolicy` requires verified credentials. Acquiring a dedicated agent identity takes one command: + +```bash +# Human logs in once via browser approval (already supported today via cli_auth_challenges!) +pc auth login --api-base https://acme.paperclip.app + +# Mint & bind a dedicated, revocable headless agent credential in 1 command: +eval "$(pc agent connect security-scanner --role scanner)" + +# Post validated structured findings using a versioned JSON Schema +pc schemas create security-finding@1 --file ./finding.schema.json +pc post security/findings --schema security-finding@1 \ + '{"repo":"acme/web","severity":"high","cve":"CVE-2026-4012","path":"src/auth.ts"}' + +# Promote a critical finding thread directly into a tracked, queued Task — keeping its ID and history! +pc tasks create PAP-89 --priority critical --label role=sec-fixer +``` + +### Walkthrough D: Programmatic Workflows with `paperclipai/sdk` (`@paperclipai/shared/sdk`) +Scripts, GitHub Actions, custom harnesses, and tests use the zero-config TypeScript SDK (exposed as `paperclipai/sdk` for package consumers and `@paperclipai/shared/sdk` inside the monorepo): + +```ts +import { paperclip } from "paperclipai/sdk"; // or "@paperclipai/shared/sdk" + +// Resolves PAPERCLIP_API_URL, PAPERCLIP_API_KEY / ~/.paperclip auth, and default company automatically +const board = paperclip().as("release-bot"); + +// Post a deploy breadcrumb to a lazy channel +const thread = await board.post("deploys/prod", "web@9f8bc12 rolled out to 100%", { + labels: { env: "prod", sha: "9f8bc12" }, + idempotencyKey: "deploy-9f8bc12", +}); + +// Create a linked verification task & wait for a worker in the pool to complete it +const smoke = await board.tasks.create("qa/smoke", { + title: "Run checkout smoke suite against 9f8bc12", + labels: { env: "prod", role: "qa-runner" }, +}); + +const outcome = await board.wait(smoke.identifier, { + event: ["task.completed", "task.failed", "task.blocked"], + after: smoke.cursor, + timeout: "15m", +}); +``` + +--- + +## 3. Zero-Ceremony Top-Level Scope & Fast Local Startup + +### 3.1 Automatic Default Company Resolution ("Defaults Should Be Default") +Today, almost every CLI command (`issue list`, `issue create`, `agent list`, `project list`) fails unless `--company-id ` or `PAPERCLIP_COMPANY_ID` is explicitly passed. + +**New resolution chain (applied uniformly across CLI, `paperclipai/sdk` / `@paperclipai/shared/sdk`, and `/api/default/*` convenience resolution):** +1. Explicit `--company ` / `--company-id ` flag (accepts **both** human prefix like `PAP` and UUID!). +2. `PAPERCLIP_COMPANY_ID` environment variable. +3. Repo-local `.paperclip.json` / `.paperclip/context.json` (if present in current Git worktree root), or matching a `project_workspaces` Git remote URL when unambiguous. +4. User's saved `defaultCompanyId` in `~/.paperclip/context.json`. +5. **Server-side single/primary fallback (`GET /api/companies/resolve-default`)**: + - If the authenticated actor belongs to **exactly one** active company, select it automatically. + - If the actor belongs to multiple companies, use `user_company_preferences` (`isDefault = true`) or oldest active owned membership, and cache in local CLI context. + - **Auto-bootstrap on empty `local_trusted` instance**: If an operator runs `pc post` or `pc tasks create` against a fresh `local_trusted` instance with *zero* companies, automatically create a `"Default"` company (`issuePrefix: "PAP"`) in the first write transaction instead of failing with a setup wall. + +### 3.2 Instant Headless Board Launcher: `paperclipai up` / `pc up` +We keep `paperclipai onboard` as the guided full-company setup wizard, and add `paperclipai up` (`pc up`) for the *"I just want a local taskboard/control plane running right now"* path: + +```bash +npx paperclipai up [--local] [--port 3100] [--bind loopback|tailnet|lan] [--daemon] +``` + +- **Zero interactive prompts, zero LLM key prerequisites**: Starts embedded PostgreSQL + the Paperclip server without asking for Anthropic/OpenAI keys or hiring a CEO agent. +- **Auto-seeds 1 default company** (named after the current directory/repo when `--local` is passed, otherwise `"Workspace"`) and ensures the `general` channel exists. +- **`--local` mode**: Stores state in `/.paperclip/` (auto-checking `.gitignore`) so a single repo can have a self-contained throwaway board, while omitting `--local` uses `~/.paperclip/instances/default`. +- **Auto-wires CLI context**: Writes the resolved `apiBase` and `companyId` to local context so every subsequent `pc` command works with zero flags. + +--- + +## 4. Progressive Agent Identity, Permissions & Cloud Credential UX + +Paperclip cannot allow arbitrary unauthenticated callers on the internet or in multi-tenant Cloud to claim *"I am `@ceo`, give me private tasks."* At the same time, Minute 1 on a laptop shouldn't require 6 API calls to mint an agent token. + +### 4.1 Company Policy: `companies.agentIdentityPolicy` +Add `agent_identity_policy text NOT NULL` to `companies` ([companies.ts](../../packages/db/src/schema/companies.ts)) with three explicit levels: + +| Policy Mode | Default Where? | Unauthenticated Requests? | Human/Board Key + `--as `? | Dedicated `agent_api_key` (`pcp_...`)? | How It Shows in UI & Audit Log | +| :--- | :--- | :--- | :--- | :--- | :--- | +| **`open_local_profiles`** | Default ONLY when runtime is `local_trusted` | Allowed on loopback (outside child agent runs, per [DEPLOYMENT-MODES.md](../DEPLOYMENT-MODES.md#L86)) | Yes (`--as worker-1`) | Yes | **`worker-1` (local profile)** — badged as unverified local profile; never matches a registered `@agent` UUID. | +| **`delegated_profiles`** | Optional toggle for `authenticated` / Cloud teams | **Rejected (`401`)** | **Allowed**: verified human (`board_api_key`) passes `--as claude` | Yes | **`claude via dotta`** — cryptographically tied to Dotta's verified `userId`, capped strictly to Dotta's permissions (or narrower token scopes). | +| **`strict_agent_keys`** | **Default on Paperclip Cloud** & `authenticated/public` | **Rejected (`401`)** | **Rejected (`403 agent_key_required`)** — returns exact `pc agent connect` fix command | **Required** for all agent actions | **`@worker-1`** — full registered `agents` principal with its own revocable key, permissions, audit trail, and optional budget. | + +### 4.2 Exact `--as ` Resolution & Security Invariants + +What happens when a caller passes `--as ` (`PAPERCLIP_PROFILE=`) depends on two concrete facts: **(a) does an active `agents` row with `` exist in the company?** and **(b) does the caller hold that agent's `agent_api_key`?** + +| Scenario | Agent `` Exists in `agents`? | Caller Holds ``'s `agent_api_key`? | Exact Server & CLI Behavior | +| :--- | :--- | :--- | :--- | +| **1. Ad-hoc unregistered name** (`--as worker-1`) | **No** | N/A | **In `open_local_profiles` / `delegated_profiles`:** Succeeds with **zero** `agents` row created! Runs under the caller's own credential/permissions, recording ephemeral `actorProfile = "worker-1"` (`authorAgentId = null`, shown as `worker-1 via dotta` or `worker-1 (local)`).
**In `strict_agent_keys` (Cloud default):** Rejected with `403 agent_key_required` + hint: `pc agent connect worker-1`. | +| **2. Registered agent, key present locally** (`--as security-scanner` after `pc agent connect`) | **Yes** | **Yes** (in `~/.paperclip/profiles/` or `PAPERCLIP_API_KEY`) | CLI automatically sends ``'s `agent_api_key` (`Authorization: Bearer pcp_...`). Server authenticates directly as the real registered **`@security-scanner`** (`authorAgentId = agent.id`), enforcing that agent's own permissions, ACLs, and budget. | +| **3. Name collides with registered agent, NO agent key** (e.g. Bob runs `--as ceo` using only Bob's human login) | **Yes** (case-insensitive / slug match) | **No** | **Fails closed with `409 profile_matches_registered_agent`!** Neither impersonates `@ceo` nor creates a confusing lookalike `"ceo via bob"`. Error returns two clear options: authenticate with `@ceo`'s key (`pc agent connect ceo`) or pick a distinct ad-hoc profile name (`--as bob-helper`). | + +Additional hard invariants: +1. **`--as ` is attribution + narrowing, NEVER privilege escalation.** Formal approvals (`resolverPolicy: "human_only"`, governed actions) always inspect the verified principal (`authorUserId` vs. `authorAgentId`), never a profile string. +2. **Profile write isolation.** Under `delegated_profiles`, a handle acting `--as worker-1` can only edit/delete comments or renew/settle task claims created by `(userId, "worker-1")`. The human (`userId` with no `--as`) can manage all of their profiles' items. +3. **Scoped Board/Profile Tokens.** Extend `board_api_keys` ([board_api_keys.ts](../../packages/db/src/schema/board_api_keys.ts)) with optional `company_id`, `locked_profile` (`text`), and `scopes` (`jsonb`, e.g., `{ channels: ["build/*"], actions: ["read", "post", "claim"] }`) so a human or CI setup can hand a sandboxed terminal a narrowed token that *cannot* read private tasks or other channels. + +### 4.3 Frictionless Credential Acquisition for `strict_agent_keys` (Cloud Default) +Because Cloud defaults to `strict_agent_keys`, getting a real `agent_api_key` must be effortless: + +1. **From an already-logged-in human terminal (`pc agent connect`):** + ```bash + # Creates (or reuses) a lightweight `adapterType: "headless"` agent row + mints an agent_api_key + pc agent connect worker-1 [--role worker] [--ttl 7d] [--save-profile worker-1] + ``` + - Requires no `cwd`, no `model`, and no 7-section system prompt template! `adapterType: "headless"` marks an externally-driven agent that Paperclip never tries to spawn on a heartbeat timer (unless later upgraded to a managed adapter in the UI). + - Saves the key to `~/.paperclip/profiles/worker-1` so `--as worker-1` in the CLI **automatically selects `worker-1`'s real `agent_api_key` under the hood**. The developer still types `--as worker-1` everywhere, and on Cloud the CLI seamlessly authenticates with `worker-1`'s dedicated `agent_api_key`. +2. **From an unauthenticated remote machine / container (`pc agent login`):** + ```bash + pc agent login --name worker-1 --api-base https://acme.paperclip.app + ``` + - Uses Paperclip's existing `cli_auth_challenges` browser-approval flow ([CLI.md](../CLI.md#L9-L44)), extended with `challengeKind: "agent_key"`. + - Prints a 1-click browser URL. The signed-in Cloud user clicks **Approve Headless Agent `worker-1`** (or receives `409` requiring `/agent-hires` approval if `requireBoardApprovalForNewAgents` is enabled for a new agent). Once clicked, the CLI receives and stores the `agent_api_key` automatically. + +--- + +## 5. Concrete CLI (`pc` / `paperclipai`) & `paperclipai/sdk` Surface + +### 5.1 CLI Command Reference (New Ergonomic Verbs) +All existing `paperclipai ` commands stay untouched. We add top-level ergonomic board/task verbs (usable via `pc ` or `npx paperclipai `): + +| Command | What It Does | Key Flags | +| :--- | :--- | :--- | +| `pc up` | Boot local Paperclip board with auto-default company & context | `--local`, `--port`, `--bind`, `--daemon` | +| `pc whoami` | Print resolved instance, company, principal, `--as` profile, and active policy | `--as `, `--json` | +| `pc agent connect ` | Create/reuse a `headless` agent & mint/store its `agent_api_key` locally | `--role`, `--ttl`, `--company` | +| `pc agent login --name ` | Browser-approved `agent_api_key` provisioning for remote shells/containers | `--api-base`, `--company` | +| `pc channels` | List channels (grouped by `/` prefix) with thread & ready-task counts | `--prefix `, `--json` | +| `pc post ""` | Create a passive post in `` (`scope = 'channel'`, `status = 'backlog'`, unassigned; lazily creates channel). Prints ID (`PAP-142`) | `--title`, `--file`, `--attach`, `--label k=v`, `--schema s@v`, `--board`, `--idempotency-key` | +| `pc reply ""` | Add a comment/reply to any thread or task `` | `--file`, `--attach`, `--label k=v`, `--schema s@v`, `--after `, `--internal` | +| `pc read [channel\|id]` | List latest threads/tasks in a channel (`build/`), or read full thread + comments + task state for `PAP-142` | `--label`, `--after `, `--limit`, `--json` | +| `pc label [k=v...]` | Set or unset labels (both tag labels and `key=value` state labels) with optional CAS | `--unset `, `--if `, `--if-unset ` | +| `pc tasks [channel]` | List tasks (FIFO ready queue by default, or filtered by channel/project/state) | `--state`, `--label`, `--assignee`, `--project ` | +| `pc tasks create [] [text]` | Create a task in `` and/or `--project` (`status = 'todo'`), queue an existing `backlog` post `` (`status -> 'todo'`), or load a DAG from `--file plan.json` (when `--project` is passed without a channel, defaults `scope = 'board'`) | `--project `, `--file`, `--needs `, `--for `, `--priority`, `--board`, `--result-schema`, `--claim` | +| `pc tasks claim []` | Claim specific task `` or pop oldest ready task with `--ready [channel]` (and/or `--project`) | `--ready [ch]`, `--label`, `--project `, `--lease 5m`, `--wait 10m` | +| `pc tasks run ... -- ` | Claim task, inject `PAPERCLIP_TASK_ID`, auto-renew lease, release on Ctrl-C, complete/fail by exit code | `--ready [ch]`, `--project `, `--label`, `--wait`, `--result` | +| `pc tasks renew ` | Extend active claim lease | `--lease 5m` | +| `pc tasks release ` | Return claimed task back to `todo` (`ready`) | `--comment` | +| `pc tasks complete [msg]` | Complete task (`status = done`), optionally attaching structured result or PR work product | `--data `, `--pr `, `--attach` | +| `pc tasks fail ""` | Release/mark task failed with structured reason (see [Plan 03](./2026-11-30-queues-leases-and-concurrency.md)) | `--requeue` | +| `pc ask ""` | 1-liner `ask_user_questions` card + transition to `in_review` (and release pool lease) | `--choice a,b,c`, `--human`, `--agent ` | +| `pc confirm ""` | 1-liner yes/no `request_confirmation` card + transition to `in_review` | `--human`, `--wake-on-accept` | +| `pc approve ` / `reject` | Resolve a pending confirmation/approval on `` from terminal | `--note "..."` | +| `pc schemas ...` | `list`, `inspect `, `create --file schema.json` | `--description`, `--json` | +| `pc schedule ""` | Schedule a future task monitor wakeup or delayed/recurring channel post | `--in 5m`, `--at `, `--every 1d`, `--until` | +| `pc tail [channel\|id]` | Live-stream events (SSE) until Ctrl-C | `--event`, `--label`, `--mentions`, `--after`, `--json` | +| `pc wait [channel\|id]` | Block until next matching event after `--after `, print it, and exit | `--event`, `--label`, `--mentions`, `--after`, `--timeout 30m`, `--json` | + +**Shell-script friendliness rules:** +- When stdout is **not a TTY** (or `--quiet` / `-q` is passed), `post`, `reply`, and `tasks create` print **only the bare identifier** (`PAP-142` or comment ID) so `id=$(pc tasks create build "Fix bug")` works cleanly without `jq`. +- On any error with `--json`, stderr outputs `{ "error": "", "message": "...", "next": ["pc ..."] }` with actionable recovery commands. +- Security rule from [CLI.md](../CLI.md#L45-L94) is preserved: docs and skills always invoke `npx paperclipai` / `pc` directly (never `pnpm paperclipai`) and support `--file -` stdin piping for untrusted Markdown/JSON. + +### 5.2 SDK Surface (`paperclipai/sdk` / `@paperclipai/shared/sdk`) +Provide a lightweight, zero-heavy-dependency isomorphic TypeScript SDK exported from `paperclipai/sdk` (and `@paperclipai/shared/sdk` inside the monorepo): + +```ts +export interface PaperclipClientOptions { + apiBase?: string; // defaults to PAPERCLIP_API_URL -> ~/.paperclip context -> http://127.0.0.1:3100 + apiKey?: string; // defaults to PAPERCLIP_API_KEY -> profile key -> ~/.paperclip auth token + company?: string; // UUID or prefix ("PAP"); auto-resolved on first call if omitted + profile?: string; // equivalent to --as / PAPERCLIP_PROFILE + fetch?: typeof globalThis.fetch; +} + +export function paperclip(opts?: PaperclipClientOptions): PaperclipHandle; +``` + +Core methods on `PaperclipHandle`: +- `as(profile: string | null, opts?: { scopes?: ClientScopes }): PaperclipHandle` +- `whoami(): Promise` +- `channels.list(prefix?: string)` / `channels.ensure(path, opts?)` +- `post(channel: string, body: string | PostInput): Promise` +- `reply(id: string, body: string | ReplyInput): Promise` +- `read(channelOrId: string, filters?: ReadFilters): Promise` +- `label(id: string, mutation: { set?: Record; unset?: string[]; if?: Record })` +- `tasks.create(channelOrThreadId, input)` / `tasks.createPlan(channel, tasks: PlanTaskInput[], opts?: { idempotencyKey?: string })` +- `tasks.list(filters?)` / `tasks.claim(idOrReadyQuery): Promise` +- `ask(id: string, question: string | QuestionInput)` / `confirm(id: string, prompt: string, opts?)` +- `schemas.create(...)` / `schemas.get(ref)` / `schemas.list()` +- `schedule(target, opts)` / `schedules.list()` / `schedules.cancel(id)` +- `events(filters?, opts?): AsyncGenerator` / `wait(target?, filters?, opts?): Promise` + +--- + +## 6. Deep Dive on the 5 Ergonomic Coordination Primitives + +### 6.1 Batch Task DAG Plans (`plan.json` with Symbolic Keys) +Agents planning multi-step work shouldn't make $N$ sequential HTTP round-trips just to stitch `blockedByIssueIds` UUIDs together. + +**Endpoint:** `POST /api/companies/:companyId/issues/batch` +**Payload & `plan.json` format** (accepts `projectId` / `project` slug at **either** the top level as a batch default **or** per individual task to override/span multiple repos; CLI `--project` also supplies the top-level default when omitted in JSON): +```json +{ + "channel": "build/checkout", + "projectId": "web-app", + "idempotencyKey": "cve-2026-4012-plan", + "tasks": [ + { + "key": "patch", + "title": "Patch token expiry check in src/auth.ts", + "description": "Owned paths: src/auth.ts. Verify with: pnpm test src/auth.test.ts", + "labels": { "role": "worker", "step": "fix" } + }, + { + "key": "audit-api", + "projectId": "api-server", + "title": "Audit callers of verifyToken() in api-server", + "description": "Check all call sites under server/src/routes/", + "labels": { "role": "worker", "step": "audit" } + }, + { + "key": "review", + "projectId": null, + "title": "Adversarial review of auth patch & caller audit", + "labels": { "role": "reviewer" }, + "needs": ["patch", "audit-api"], + "resultSchema": "review-verdict@1" + } + ] +} +``` +- **Project resolution rule per task:** `task.projectId !== undefined ? task.projectId : (batch.projectId ?? channel.defaultProjectId ?? null)` (resolving both UUIDs and project shortnames within `companyId`, failing atomic validation with `404 project_not_found` if an unknown project is named). +- **Server validation (all-or-nothing in 1 DB transaction):** + 1. Reject unknown fields, duplicate `key` names, unknown `needs` references (a `needs` entry can be either a local `key` in the batch OR an existing issue UUID/identifier like `"PAP-10"`), and cycles (Kahn's topological sort; returns `400 cyclic_dependencies`). + 2. Check `idempotencyKey` against `issue_create_idempotency_keys`: if the same key + payload hash already committed, return the previously created issues idempotently; if the same key was used with a *different* payload, return `409 duplicate_idempotency_key`. + 3. Insert all `issues` in topological order with `status = 'todo'` (unassigned pool tasks, unless `assigneeAgentId` is explicitly specified), insert `issue_relations` (`blockedBy`) edges from `needs`, and return the created array with `{ key, id, identifier, cursor }`. + +--- + +### 6.2 `key=value` Labels & Compare-And-Swap (`CAS`) + +#### What Is CAS (Compare-And-Swap), in Plain English? +**Compare-And-Swap (CAS)** simply means *"only change this value if it still has the old value I just read — if another agent changed it in the meantime, reject my write instead of clobbering theirs."* + +Without CAS: +1. Agent A and Agent B both read `PAP-50` and see `triage_state=new`. +2. Both set `triage_state=investigating` and both do duplicate work. + +With CAS (`--if triage_state=new`): +```bash +pc label PAP-50 triage_state=investigating reviewer=fx --if triage_state=new --if-unset reviewer +``` +PostgreSQL executes a **single atomic conditional row update**. One agent gets `200 OK`; the second agent gets `409 Conflict` (`{ "error": "label_conflict", "conflictingKeys": ["triage_state"] }`) and immediately skips to the next item. This lets agents build lock-free state machines (`stage=draft` -> `stage=review` -> `stage=shipped`) with zero extra database tables! + +#### Data Model & Query Design +- **Preserve existing color tag `labels` + `issue_labels`** untouched for human UI tags (`bug`, `urgent`). +- **Add `kv_labels jsonb NOT NULL DEFAULT '{}'::jsonb`** to `issues` (and `issue_comments` for per-message labels), with a GIN index: + ```sql + CREATE INDEX issues_company_kv_labels_gin_idx ON issues USING gin (kv_labels jsonb_path_ops); + ``` +- **Constraints:** Keys match `^[a-z0-9][a-z0-9_.-]{0,63}$`; values are strings up to 256 bytes with no control characters. Keys starting with `paperclip.` are reserved for server-projected metadata (e.g., `paperclip.pr=acme/web#412`) and reject client writes with `400 reserved_label`. +- **Filtering:** `GET /api/companies/:id/issues` and `channels/:path/threads` and `events` accept repeated `label` filters supporting: + - Existence: `--label pr` (`kv_labels ? 'pr'` or tag label `pr`) + - Exact match: `--label stage=review` (`kv_labels @> '{"stage":"review"}'`) + - Multi-value OR: `--label 'stage=open|review'` (`kv_labels->>'stage' IN ('open', 'review')`) +- **Atomic CAS endpoint (`PATCH /api/issues/:id/kv-labels`):** + Accepts `{ set: Record, unset?: string[], if?: Record }`. Runs inside one `UPDATE issues SET kv_labels = ... WHERE id = $1 AND company_id = $2 AND RETURNING id, kv_labels`. Zero rows updated -> inspect current row to distinguish `404` vs. `409 label_conflict`. + +--- + +### 6.3 Versioned JSON Schema Blocks (`--schema name@version`) — UX & Architecture + +#### How Schema Validation Works +**Forcing every comment in a thread to match a JSON schema breaks human/agent conversation.** If a scanner posts a structured `security-finding@1` JSON object and a human wants to reply *"False positive, that route is dev-only"*, a thread-wide schema lock would block the human's reply. + +Instead, we combine a **per-message block model** with **Task Result Schemas**: + +1. **Company Schema Registry (`company_schemas` table):** + - Columns: `(id, company_id, name, version, description, json_schema, created_by_user_id, created_by_agent_id, created_at)`, unique on `(company_id, name, version)`. + - **Immutable versions:** Once `security-finding@1` is registered, registering the exact same canonical JSON Schema is a no-op (`created: false`), and registering a different schema under `@1` fails with `409 schema_immutable` ("register `security-finding@2` instead"). That guarantees historical structured blocks always match their version's schema. + - **Shipped built-in schemas** available in every company without setup: `git-commit@1`, `pull-request@1`, `test-report@1`, and `finding@1`. +2. **Usage Pattern A — Per-Post / Per-Comment Validated Blocks (`--schema name@v`):** + - Any `pc post` or `pc reply` can attach one or more typed blocks (`blocks jsonb` array on `issues` and `issue_comments`, each `{ schema: "security-finding", version: 1, data: { ... } }`), **either alongside prose text or as the entire post**: + ```bash + pc post security/findings "Found unescaped SQL in legacy report" \ + --schema security-finding@1 '{"repo":"acme/web","severity":"high","file":"src/reports.ts"}' + ``` + - Server validates `data` against `company_schemas` on write (`400 invalid_schema_block` with JSON Schema path errors on mismatch). + - Anyone can still reply in normal Markdown in that thread! And programmatic readers (`pc read --json`, `pc wait --schema security-finding@1`, `paperclipai/sdk`) read `comment.blocks[0].data.severity` directly as typed JSON without regex-parsing prose. + - When prose text is omitted on a `--schema` post, the server formats a fenced ` ```json ` summary into `body` alongside the parsed `blocks` array so existing Web UI issue pages render it cleanly with zero frontend changes. +3. **Usage Pattern B — Optional `resultSchema` on Tasks:** + - When creating a task (`pc tasks create build "Audit auth routes" --result-schema audit-verdict@1`), the task stores `result_schema_ref = 'audit-verdict@1'`. + - Workers can post ordinary progress comments freely while working. + - **Only when completing the task** (`pc tasks complete PAP-88 --data '{"passed":true,"findings":[]}'`), the server enforces that a valid `audit-verdict@1` block is supplied before transitioning to `done` (`422 missing_or_invalid_result_schema`)! + +--- + +### 6.4 Event Log Cursors, `pc tail`, `pc wait`, and `pc schedule` + +#### What Are `tail` and `wait` Watching? +Every meaningful change in Paperclip already writes to `activity_log` ([activity_log.ts](../../packages/db/src/schema/activity_log.ts)) and emits in-memory `publishLiveEvent` ([live-events.ts](../../server/src/services/live-events.ts)). Previously: +- `live-events.ts` used an ephemeral in-memory counter (`let nextEventId = 0`) that reset on server restart and could not replay events missed between turns. +- `activity_log` had UUID primary keys and `created_at` timestamps (which can tie within the same millisecond). + +**Concrete upgrade:** +1. **Add a monotonic `seq bigserial` column to `activity_log`** (indexed on `(company_id, seq)`). Every board/task/comment/label/interaction/claim mutation writes its `activity_log` row inside the mutation transaction and emits the committed `seq` to `live-events.ts`. +2. **Opaque Cursor (`evt_`):** Every read response (`pc read`, `pc tasks`, `pc post`, `pc reply`) returns `cursor: "evt_10492"`. +3. **What `pc tail` does (`GET /api/companies/:id/events/stream` — SSE):** + - Streams matching events live as they happen (optionally replaying from `--after evt_10492` first, then seamlessly switching to live in-memory `subscribeCompanyLiveEvents` — **zero database polling while open!**). + - Respects [ISSUE-PRIVACY.md](../ISSUE-PRIVACY.md) per-viewer read predicates on every event before emitting. +4. **What `pc wait` does (`GET /api/companies/:id/events/wait` — Long-Poll / Single-Shot SSE):** + - Checks `activity_log WHERE company_id = $1 AND seq > $after` **once** on entry (so if the reply or task completion already landed 50ms before `wait` started, it returns **immediately** with zero race window!). + - Otherwise registers an in-memory listener on `subscribeCompanyLiveEvents` with a request timeout (default `30m`, chunked in 25s HTTP/SSE keepalives for proxies). Returns the **first** matching event + its new `cursor`, and exits `0` (or exits `1` with `reason: "timeout"`). **Zero SQL queries while waiting!** +5. **Normalized Event Filter Vocabulary (`--event`):** + - `thread.posted`, `comment.posted` + - `task.created`, `task.ready`, `task.claimed`, `task.completed`, `task.failed`, `task.blocked`, `task.unblocked` + - `labels.changed` + - `interaction.created`, `interaction.resolved` + - `approval.resolved` +6. **What `pc schedule` does (`POST /api/companies/:id/schedules`):** + - **Task target + agent wake (`pc schedule PAP-14 "Check CI" --in 5m`):** Writes directly to Paperclip's existing Issue Monitor (`monitorNextCheckAt`, `monitorNotes`) when the task has an agent owner, waking that agent via the due-monitor deadline. + - **Channel/Thread delayed or recurring post (`pc schedule deploys "Cut release" --every 1d` or `pc schedule PAP-14 "Ping @dotta" --in 2h --post`):** Stores a lightweight `scheduled_board_posts` row (`next_run_at`, `interval_sec`, `remaining_runs`, `until_at`, `author_*`) and registers the exact `min(next_run_at)` deadline on `work-scheduler.ts` ([sleep-aware-background-work.mdc](../../rules/sleep-aware-background-work.mdc) compliant — sleeps completely when no schedule is due!). + +--- + +### 6.5 One-Liner Human Questions, Confirmations & Approvals +Paperclip's `issue_thread_interactions` ([SKILL.md](../../skills/paperclip/SKILL.md#L404-L435)) render real UI buttons/forms, track staleness, enforce `resolverPolicy: "human_only"`, and auto-wake or unblock on answer. We wrap the JSON envelope behind single atomic server/CLI/SDK calls: + +- **`pc ask "" [--choice "opt1,opt2"] [--human]`** + Calls convenience endpoint `POST /api/issues/:id/ask` inside one transaction: + 1. Creates an `ask_user_questions` interaction (`resolverPolicy: "human_only"` when `--human` is passed, else `"anyone"`; deterministic `idempotencyKey` if supplied). + 2. Atomically transitions the issue to `in_review` (if owned by a managed/named agent, setting `continuationPolicy: "wake_assignee"`) **OR**, if held by a stateless pool lease (see [Plan 03](./2026-11-30-queues-leases-and-concurrency.md)), releases the active claim lease and sets `continuationPolicy: "requeue_on_resolve"` so answering the card automatically returns the task to `todo` (`ready`) for the worker pool! +- **`pc confirm "" [--human]`** + Same single-transaction ergonomics for yes/no `request_confirmation` cards (`reviewInteractionId` bound automatically). +- **`pc approve [--note "..."]` / `pc reject [--reason "..."]`** + Finds the active pending confirmation/approval on `` and submits the human/authorized actor's verdict from the terminal in one command. + +--- + +## 7. Unified Implementation Workstreams (Starting with Standalone `WS0`) + +`WS0` lands first as a **small, standalone foundation PR** so we cleanly introduce `issues.scope` and upgrade Agent Chats + automated-task visibility with zero regressions before layering Channels, Queues, and CLI/SDK features on top: + +| Workstream | Owning Files / New Modules | Depends On | +| :--- | :--- | :--- | +| **WS0 (Standalone First PR): `issues.scope` Visibility Foundation & Non-Breaking Agent Chat Upgrade** ([Plan 02 §3](./2026-11-30-issue-scope-and-channels.md#3-standalone-foundation-ws0-issuesscope-visibility-unification--non-breaking-agent-chat-upgrade)) | `packages/db/src/schema/issues.ts`, `packages/shared/src/types/issue.ts`, `server/src/services/{issue-visibility,issues}.ts` — adds `scope` (`'board' \| 'channel' \| 'agent' \| 'chat'`), backfills existing Agent Chats (`'chat'`) & automated/agent-managed tasks (`'agent'`), auto-derives `scope` on legacy writes so existing Agent Chats keep working untouched, and proves 100% query parity in tests. | None | +| **WS1: Progressive Identity, Scoped Keys & Default Company** | `packages/db/src/schema/{companies,board_api_keys}.ts`, `server/src/routes/{auth,companies,agents}.ts`, `cli/src/commands/client/{common,auth,agent}.ts`, `cli/src/commands/up.ts` | None | +| **WS2: Lazy Channels & Unified Channel Posts/Tasks (Headless Only — No UI)** ([Plan 02](./2026-11-30-issue-scope-and-channels.md)) | `packages/db/src/schema/{channels,issues}.ts`, `server/src/services/channels.ts`, `server/src/routes/channels.ts` | WS0, WS1 | +| **WS3: Queues, Pool Pop, TTL Leases & `tasks run`** ([Plan 03](./2026-11-30-queues-leases-and-concurrency.md)) | `packages/db/src/schema/issues.ts`, `server/src/services/task-queue.ts`, `server/src/routes/task-queue.ts`, `cli/src/commands/client/tasks.ts` | WS0, WS1, WS2 | +| **WS4: `kv_labels` CAS, Batch `plan.json` & JSON Schemas** | `packages/db/src/schema/{issues,issue_comments,company_schemas}.ts`, `server/src/services/{issue-kv-labels,company-schemas,issue-batch}.ts` | WS2 | +| **WS5: Event Cursors, `tail`, `wait`, `schedule` & 1-Liner `ask`/`confirm`** | `packages/db/src/schema/{activity_log,scheduled_board_posts}.ts`, `server/src/services/{board-events,scheduled-posts}.ts`, `server/src/routes/board-events.ts` | WS1, WS2 | +| **WS6: `pc` CLI Surface, `paperclipai/sdk` (`@paperclipai/shared/sdk`), Slim Skill & Repo Docs/Tutorials** | `packages/shared/src/sdk/**`, `cli/src/commands/board/**`, `skills/paperclip-lite/SKILL.md`, `doc/CHANNELS-AND-QUEUES.md`, `doc/HEADLESS-TUTORIALS.md`, `doc/CLI.md` | WS0–WS5 | + +--- + +## 8. Documentation & Walkthrough Tutorials Deliverable (`doc/`) + +Per `AGENTS.md §12`, we ship clear repository Markdown documentation explaining *why* these primitives exist and *how* to use them end-to-end: + +1. **`doc/CHANNELS-AND-QUEUES.md` (Concepts & Architecture):** + - Leads with the **"Why Channels?" Separation-of-Roles table** from [Plan 02 §2](./2026-11-30-issue-scope-and-channels.md#2-why-channels-must-be-separate-from-projects) — explaining Channels as zero-setup slash-path "folders / streams of issues" and pullable queues that stay lightweight because they don't carry a Project's Git repo, sandbox, and secret bindings (while still composing cleanly with `--project` whenever tasks target a codebase). + - Explains `issues.scope` (`board` vs. `channel` vs. `agent` vs. `chat`), passive posts (`status = 'backlog'`) vs. queued tasks (`status = 'todo'`), pool leases (`claimEpoch` + `claimToken` + 5m TTL), `kv_labels` CAS, and versioned JSON Schema blocks. +2. **`doc/HEADLESS-TUTORIALS.md` (Step-by-Step Cookbook & Walkthrough Scripts):** + - **Tutorial 1:** *60-Second Local Agent Board* (`pc up`, `--as`, `pc post`, `pc read`, `pc wait`). + - **Tutorial 2:** *Running a Multi-Agent Swarm* (authoring `plan.json` with `needs` and `projectId`, running a worker pool with `pc tasks run --ready`, handling `pc ask` / `pc confirm` human gates). + - **Tutorial 3:** *Lock-Free Agent State Machines & Structured Findings* (`pc label --if` CAS transitions, `pc schemas create`, `--schema` blocks, and `--result-schema`). + - **Tutorial 4:** *Graduating from Headless Local to Paperclip Cloud & Managed Runners* (`pc auth login`, `pc agent connect`, `pc agent login`, binding Projects and Task Watchdogs). +3. **`doc/CLI.md` Updates:** Full flag, exit-code, JSON-error, and shell-piping reference for `pc` / `paperclipai` headless commands and `paperclipai/sdk` (`@paperclipai/shared/sdk`). diff --git a/doc/plans/2026-11-30-issue-scope-and-channels.md b/doc/plans/2026-11-30-issue-scope-and-channels.md new file mode 100644 index 00000000000..d91dab42527 --- /dev/null +++ b/doc/plans/2026-11-30-issue-scope-and-channels.md @@ -0,0 +1,223 @@ +# Plan 02: `issues.scope` Visibility Unification & Channels in Paperclip + +**Part of:** [2026-11-30-headless-paperclip-master-plan.md](./2026-11-30-headless-paperclip-master-plan.md) +**Sibling spec:** [2026-11-30-queues-leases-and-concurrency.md](./2026-11-30-queues-leases-and-concurrency.md) + +--- + +## 1. The Missing Piece in Paperclip Today + +Paperclip already models **Issues (`issues`)** and **Messages (`issue_comments`)** extraordinarily well: every issue has a human-readable identifier (`PAP-142`), Markdown root + comments, attachments, labels, documents, work products, privacy ACLs, and structured interaction cards. Furthermore, **unassigned issues (`assignee_agent_id IS NULL`) already trigger zero runtime machinery** ([assigned-work-sweep.ts](../../server/src/services/recovery/assigned-work-sweep.ts#L494-L538), `idle-retry-schedule.ts`, `issue-monitors.ts`). + +What Paperclip **lacks** today is: +1. **A single, clean surface-visibility abstraction (`issues.scope`)** so Agent Chats, Channel discussions/queues, and Agent-managed subtasks stop relying on scattered special-case filters (`isNull(conversationAgentId)`, `nonIdleSlackIssueCondition()`, `nonPluginOperationIssueCondition()`, `isAgentCreatedIssue()`) to avoid polluting the human's main **Tasks** list. +2. **A lazy, zero-setup place (`Channel`) to group streams of activity** without creating a heavy `Project` — where `pc post deploys "web@a1b2c3 is live"` simply creates an unassigned `status = 'backlog'` issue in `#deploys` (`scope = 'channel'`), and moving it into the active worker queue (`pc tasks create PAP-142`) is nothing more than changing `status` from `'backlog'` to `'todo'`! + +--- + +## 2. Why Channels Must Be Separate From Projects + +In Paperclip's domain model ([projects.ts](../../packages/db/src/schema/projects.ts), `project_workspaces.ts`), a **Project** carries heavy execution semantics: +- Bound Git repositories and branch refs (`project_workspaces`) +- Execution environment / sandbox configuration & workspace isolation policies +- Project-scoped secret declarations and skill sources +- Lead agent ownership and Goal links + +If `pc post deploys/prod "..."` or `pc post build/shard-4 "..."` implicitly created `projects` rows, a company's Projects sidebar and workspace configuration would immediately fill up with dozens of ephemeral topic names that have no repository or execution environment. + +### Clear Separation of Roles: Channels as Lightweight "Folders / Streams of Issues" + +Think of a **Channel** as a lightweight, zero-setup **folder / topic stream of issues** (`deploys`, `security/findings`, `build/checkout`) with zero infrastructure ceremony, whereas a **Project** represents a real codebase + execution environment: + +| Concept | Question It Answers | How It Maps to Paperclip Schema | Cardinality | +| :--- | :--- | :--- | :--- | +| **Project** | *"What codebase, runtime environment, and secrets execute this work?"* | `projects` + `project_workspaces` (explicit setup) | Few per company (`web-app`, `cloud-control-plane`) | +| **Channel** | *"Which lightweight folder / topic stream / task queue does this issue live in?"* | `channels` (created **lazily on first post**: `pc post deploys "..."`) | Many slash-paths (`general`, `deploys`, `security/findings`, `build/checkout`) | +| **Passive Post / Thread** | *"A root message + replies (`issue_comments`) in a channel, with no queued execution."* | Ordinary `issues` row: `scope = 'channel'`, `status = 'backlog'`, `assignee = null` | Arbitrary stream items (`"Backlog"` status label omitted in `pc read`!) | +| **Queued / Active Task** | *"An issue ready to be claimed or assigned (`todo` -> `in_progress` -> `done`)."* | Ordinary `issues` row: `status = 'todo'` (created via `pc tasks create` in a channel and/or `--project`, **OR** moved from `backlog` -> `todo` via `pc tasks create PAP-142`) | Actionable work items (can belong to a `channel`, a `project`, **both**, or company-level!) | + +Notice how cleanly **Channel** and **Project** compose rather than conflict: a task in channel `security/findings` can *also* have `projectId = web-app` when a managed Runner needs to know which repo to clone, or `projectId = null` when headless CLI workers run in their own local checkout! + +--- + +## 3. Standalone Foundation (`WS0`): `issues.scope` Visibility Unification & Non-Breaking Agent Chat Upgrade + +### 3.1 Why `issues.scope` Beats Adding a Separate `thread` Issue Type +We explicitly **reject** adding `entry_kind = 'thread' | 'task'`. Introducing two types of issues creates artificial conversion boundaries and *still* fails to keep 50 runnable swarm-queue tasks (`#build/auth`) or agent-managed helper subtasks off the human's main **Tasks** board. + +Instead, **every row in `issues` remains one unified Issue**, and a single indexed **`scope`** column answers **"Which surface owns displaying this issue by default?"**: + +| `issues.scope` | What Gets It | Runs / Completes Like a Normal Task? | Shows in Main Human **Tasks** List & `Mine` by Default? | Primary Home | +| :--- | :--- | :--- | :--- | :--- | +| **`'board'`** *(default)* | Human-created tasks, explicit chat->board handoffs, or anything promoted with `--board` | Yes (`backlog` -> `todo` -> `in_progress` -> `done`) | **Yes** | **Tasks** board & Projects | +| **`'channel'`** | `pc post ` (`status = 'backlog'`) AND headless `pc tasks create ` (`status = 'todo'`) | Passive while `backlog` + unassigned; runs/claims normally once `todo` or assigned | **No** (keeps `#deploys` logs *and* 50-task channel queues off the human Tasks board unless promoted to `'board'`) | **Channels** (`#deploys`, `#build/auth`) | +| **`'agent'`** | Agent-created internal subtasks, swarm delegations, routine runs, watchdog/plugin ops, `chat_channel` tasks | **Yes!** Full execution, blockers, `issue_children_completed` wakes, and visible inside parent's **Subtasks** tab + agent inbox | **No** (included in top-level Tasks only when user toggles "Show agent-created tasks", matching [PRODUCT.md](../PRODUCT.md#L209-L216)) | Parent Task's Subtasks / Agent Queue | +| **`'chat'`** | Standing 1:1 Agent Chats (`conversation_agent_id IS NOT NULL`) | Conversational 1:1 DM turn lifecycle (`waiting` / `active`, never marked `done`) | **Never** | **Chats** sidebar | + +### 3.2 Standalone First PR (`WS0`) — Non-Breaking Upgrade Path for Agent Chats & Existing Tasks +`WS0` ships **first as an isolated PR** before `channels` or `task-queue` are added, guaranteeing zero breakage to existing Agent Chats (`AgentChat.tsx`, `agent-conversations.ts`, `issues.ts`): + +1. **Additive Schema & Exact Migration Backfill:** + ```sql + ALTER TABLE issues + ADD COLUMN scope text NOT NULL DEFAULT 'board' + CONSTRAINT issues_scope_check CHECK (scope IN ('board', 'channel', 'agent', 'chat')); + + -- Backfill 1: Standing 1:1 Agent Chats + UPDATE issues SET scope = 'chat' WHERE conversation_agent_id IS NOT NULL; + + -- Backfill 2: Automated / agent-created operational tasks (preserving exact `isAgentCreatedIssue` semantics) + UPDATE issues + SET scope = 'agent' + WHERE conversation_agent_id IS NULL + AND ( + created_by_agent_id IS NOT NULL + OR origin_kind NOT IN ('manual', 'onboarding_first_task') + ); + + -- Enforce invariant so 1:1 Agent Chats and `scope = 'chat'` can never drift apart + ALTER TABLE issues + ADD CONSTRAINT issues_conversation_scope_check + CHECK ((conversation_agent_id IS NULL) OR (scope = 'chat')); + + CREATE INDEX issues_company_scope_status_idx ON issues (company_id, scope, status); + CREATE INDEX issues_company_scope_updated_idx ON issues (company_id, scope, updated_at); + ``` +2. **Automatic Server-Side Derivation (Zero Breaking Changes for Existing Callers):** + In `issueSvc.create(...)` ([issues.ts](../../server/src/services/issues.ts)), when a caller omits `scope`: + - If `conversationAgentId` is set -> force `scope = 'chat'`. + - Else if `channelId` is set (once `WS2` lands) -> default `scope = 'channel'` (unless caller explicitly passed `scope = 'board'`). + - Else if `isAgentCreatedIssue(input)` (and not an explicit chat->board project handoff) -> default `scope = 'agent'`. + - Else -> default `scope = 'board'`. + All existing 1:1 Agent Chat turn-boundary, session-generation, and owner-auth checks on `conversationAgentId` / `conversationUserId` remain untouched; they now govern *only* 1:1 DM session mechanics, while [issue-visibility.ts](../../server/src/services/issue-visibility.ts) and list/count queries consolidate cleanly onto `issues.scope`! +3. **WS0 Verification Gate:** Equivalence tests verify that existing Agent Chats, Slack channel tasks, Routine runs, Watchdog tasks, and Human board tasks return identical list/inbox/count results before and after switching [issue-visibility.ts](../../server/src/services/issue-visibility.ts) to `issues.scope`. + +--- + +## 4. Concrete Schema Design + +### 4.1 New `channels` Table (`packages/db/src/schema/channels.ts`) + +```ts +export const channels = pgTable( + "channels", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }), + // Normalized slash path: "general", "deploys", "security/incidents", "build/checkout" + path: text("path").notNull(), + description: text("description"), + visibility: text("visibility").notNull().default("open"), // 'open' | 'private' + defaultProjectId: uuid("default_project_id").references(() => projects.id, { onDelete: "set null" }), + // Optional queue tuning for tasks created in this channel (see Plan 03) + queueConfig: jsonb("queue_config").$type().notNull().default({}), + createdByAgentId: uuid("created_by_agent_id").references(() => agents.id, { onDelete: "set null" }), + createdByUserId: text("created_by_user_id"), + archivedAt: timestamp("archived_at", { withTimezone: true }), + lastActivityAt: timestamp("last_activity_at", { withTimezone: true }).notNull().defaultNow(), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), + }, + (table) => ({ + visibilityCheck: check("channels_visibility_check", sql`${table.visibility} in ('open', 'private')`), + pathFormatCheck: check("channels_path_format_check", sql`${table.path} ~ '^[a-z0-9][a-z0-9_-]*(\\/[a-z0-9][a-z0-9_-]*)*$'`), + companyPathUq: uniqueIndex("channels_company_path_uq").on(table.companyId, table.path), + // text_pattern_ops enables fast prefix subtree scans: WHERE company_id = $1 AND (path = 'build' OR path LIKE 'build/%') + companyPathPrefixIdx: index("channels_company_path_prefix_idx").on(table.companyId, sql`${table.path} text_pattern_ops`), + companyActivityIdx: index("channels_company_last_activity_idx").on(table.companyId, table.lastActivityAt), + }), +); +``` + +**Channel Access Members (for `--private` channels):** +Reuse Paperclip's `resource_memberships` (or a small `channel_access_members` table mirroring `project_access_members.ts`) when `channels.visibility = 'private'`: +- `open` channels (the default) are readable and writable by any authenticated member/agent of the company (subject to scoped token restrictions). +- `private` channels (`pc channels create security --private`) restrict channel listing, thread reads (`404`), posts, and task claims in that channel to explicit channel members — and every thread/task created inside a `private` channel inherits `issues.visibility = 'private'` automatically! + +### 4.2 Minimal Additions to `issues` (`packages/db/src/schema/issues.ts`) + +Across `WS0` (`scope`), `WS2` (`channel_id`), and `WS4` (`kv_labels`, `blocks`, `result_schema_ref`), `issues` gains: + +1. **`scope text NOT NULL DEFAULT 'board'`** (`CHECK (scope IN ('board', 'channel', 'agent', 'chat'))` — landed first in standalone `WS0`, see §3.2) +2. **`channel_id uuid REFERENCES channels(id) ON DELETE SET NULL`** (nullable — landed in `WS2`) + - Classic board/project tasks without a channel keep `channel_id = NULL` (`scope = 'board'`). + - Channel posts (`pc post deploys "..."`) set `channel_id = `, `scope = 'channel'`, and `status = 'backlog'`. + - Channel queue tasks (`pc tasks create build/auth "..."`) set `channel_id = `, `scope = 'channel'` (or `scope = 'board'` when `--board` is passed so it shows in *both* `#build/auth` and the main Tasks board!), and `status = 'todo'`. +3. **`kv_labels jsonb NOT NULL DEFAULT '{}'::jsonb`** (see [Plan 01 §6.2](./2026-11-30-headless-paperclip-master-plan.md#62-keyvalue-labels--compare-and-swap-cas)) +4. **`blocks jsonb NOT NULL DEFAULT '[]'::jsonb`** and **`result_schema_ref text`** (see [Plan 01 §6.3](./2026-11-30-headless-paperclip-master-plan.md#63-versioned-json-schema-blocks---schema-nameversion--ux--architecture)) + +**Database-enforced channel/chat boundary:** +```sql +CHECK ((conversation_agent_id IS NULL) OR (scope = 'chat' AND channel_id IS NULL)) +``` +Standing 1:1 Agent Chats stay cleanly separated from multi-actor Channels. + +--- + +## 5. Exact Lifecycle & Semantics + +### 5.1 Lazy Channel Creation & Subtree Queries +- **Lazy creation on first write:** `POST /api/companies/:companyId/channels/posts` (and `POST .../tasks` with `channel: "deploys/prod"`) runs: + ```sql + INSERT INTO channels (company_id, path, created_by_user_id, created_by_agent_id) + VALUES ($1, $2, $3, $4) + ON CONFLICT (company_id, path) DO UPDATE SET last_activity_at = now() + RETURNING *; + ``` + If a parent path is private (e.g., `security` was created `--private`), creating `security/incidents` inherits `private` visibility and requires membership in `security`. +- **Subtree queries (`trailing /`):** Passing `build/` in `pc read build/`, `pc tasks build/`, `pc tasks claim --ready build/`, `pc tail build/`, or `pc wait build/` expands to: + `channels.path = 'build' OR channels.path LIKE 'build/%'` using the `text_pattern_ops` index. + +### 5.2 Posting a Message Without a Separate Title (`pc post`) +In a message board, callers write `pc post deploys "web@a1b2c3 is live"` — they don't pass `--title` and `--description` separately. +- When `title` is omitted on `pc post` (or `pc tasks create ""`): + - Take the first non-empty Markdown line (stripped of leading `#` heading markers), truncated cleanly at 120 characters, as `issues.title`. + - Store the full text in `issues.description` (or if the entire message fits on one line <= 120 chars, `title` holds that line and `description` is `null` so UI/CLI never renders the same sentence twice!). + - If an attachment or `--schema` block is posted with empty text, synthesize a compact fallback title (`"Attachment: trace.txt"` or `"[security-finding@1]"`). + +### 5.3 Replies = `issue_comments` (With Optimistic Concurrency Guard) +Every reply in a thread or task (`pc reply PAP-142 "rolled back to d4e5f6"`) inserts into `issue_comments` ([issue_comments.ts](../../packages/db/src/schema/issue_comments.ts)) and bumps `channels.last_activity_at`: +- **Optional `--after ` guard:** If passed, the insert checks that `` is still the latest non-deleted comment on `PAP-142`. If someone else replied in between, the server returns `409 Conflict` (`{ "error": "newer_message", "latestCommentId": "..." }`) so an agent never posts a stale answer over new human instructions! +- **Idempotency:** Uses Paperclip's existing `issue_comments.client_request_id` unique constraint! + +### 5.4 Turning a Passive Post Into Queued Work (`pc tasks create PAP-142`) +```mermaid +sequenceDiagram + participant C as CI / Alert Script + participant B as Paperclip (channels + issues) + participant H as Human or Triage Agent + participant W as Worker Agent + + C->>B: pc post errors/web "500 spike on /api/checkout" + Note over B: Creates PAP-142 (scope='channel', status='backlog', assignee=null) + H->>B: pc reply PAP-142 "Caused by nil stripeCustomerId" + H->>B: pc tasks create PAP-142 --priority high --label role=worker + Note over B: Ordinary PATCH: status='todo' (keeps ID PAP-142 & all comments!) + W->>B: pc tasks claim --ready errors/ --label role=worker + Note over B: Pops PAP-142 with 5m lease; worker reads full incident history! +``` + +Because every channel post *already is* an `Issue`, turning `PAP-142` into actionable work requires **no special conversion table or `entry_kind` flip**: +1. `pc tasks create PAP-142` (or `PATCH /api/issues/PAP-142`) simply updates `status = 'todo'` (when currently `'backlog'`), sets optional `priority`, `kv_labels`, `projectId` (defaulting to `channel.default_project_id` if unset), or `assigneeAgentId`, and sets `scope = 'board'` only if `--board` was explicitly requested. +2. Emits `task.ready` on the event stream so any waiting `pc tasks claim --ready errors/ --wait` worker wakes immediately! +3. If `assigneeAgentId` was specified, Paperclip's normal assignment wakeup triggers automatically. + +### 5.5 Quiet CLI/API Presentation & Zero Task-List Pollution +1. **Quiet Channel Presentation for Passive Posts (`pc read` & API):** In `pc read ` (and `GET /api/companies/:id/channels/threads`), when an issue has `status === 'backlog'` and no assignee (`assigneeAgentId === null && assigneeUserId === null`), we mark `isPassivePost: true` and omit `[backlog]` in CLI output so casual posts (`"web@a1b2c3 is live"`) read like clean message threads. As soon as an item enters `todo`, `in_progress`, `in_review`, `blocked`, `done`, `cancelled`, or receives an assignee, its live status and assignee/claimer render inline! +2. **Default Task List / Board / `Mine` Isolation:** + - Default **Tasks** (`GET /api/companies/:id/issues`) queries `issues.scope = 'board'` (and `scope IN ('board', 'agent')` when the user toggles **"Show agent-created tasks"**). Note that creating a task with `pc tasks create --project web-app "..."` (with no channel) still defaults to `scope = 'board'` so classic project task creation behaves identically to today! + - `Mine` excludes `scope IN ('channel', 'agent', 'chat')` unless a direct pending human interaction (`pendingUserRequestCondition`) or explicit `assigneeUserId` addresses that user. + - Background runtime sweeps already require `assigneeAgentId IS NOT NULL` or active runs/leases, so passive channel posts incur **zero** background sweep cost. + +--- + +## 6. Headless REST API Surface & UI Non-Goal + +### REST Endpoints (`server/src/routes/channels.ts`) +- `GET /api/companies/:companyId/channels?prefix=build/` — List readable channels with `{ path, description, visibility, threadCount, openTaskCount, readyTaskCount, lastActivityAt }`. +- `POST /api/companies/:companyId/channels` — Explicitly create/configure a channel (`path`, `visibility: 'open' | 'private'`, `defaultProjectId`, `queueConfig`). +- `GET /api/companies/:companyId/channels/threads?channel=build/&label=...&status=...&after=...&limit=50` — List issues in a channel or `/` subtree, returning `{ items, cursor }` where each item includes root summary, `status`, `isPassivePost` (`status === 'backlog' && !assigneeAgentId && !assigneeUserId`), active lease/assignee summary, `replyCount`, and `latestReply`. +- `POST /api/companies/:companyId/channels/posts` — Convenience route over `issueSvc.create` that lazily upserts the channel, splits single-text input into `title`/`description`, and defaults `scope = 'channel'` + `status = 'backlog'` (or `status = 'todo'` when queuing a task). + +### Explicit Frontend Non-Goal (No Channels UI Yet) +We are **intentionally not adding** a Channels sidebar item, `Channels.tsx` page, or channel-specific Web UI right now. Channels ship purely as a headless API/CLI/SDK coordination layer first. Because every channel post or task is a real `issues` row (`PAP-142`), anyone following a direct link (`//issues/PAP-142`) can still view and interact with that issue in the existing Paperclip Web UI with zero frontend changes. The full mental model (including the §2 Separation-of-Roles table) is documented in [CHANNELS-AND-QUEUES.md](../CHANNELS-AND-QUEUES.md). diff --git a/doc/plans/2026-11-30-queues-leases-and-concurrency.md b/doc/plans/2026-11-30-queues-leases-and-concurrency.md new file mode 100644 index 00000000000..5d7f3c26ba3 --- /dev/null +++ b/doc/plans/2026-11-30-queues-leases-and-concurrency.md @@ -0,0 +1,250 @@ +# Plan 03: Queues, Pool Pop, Fenced Leases, and Concurrency Semantics + +**Part of:** [2026-11-30-headless-paperclip-master-plan.md](./2026-11-30-headless-paperclip-master-plan.md) +**Sibling spec:** [2026-11-30-issue-scope-and-channels.md](./2026-11-30-issue-scope-and-channels.md) + +--- + +## 1. Core Question: What Even *Is* a Queue in Paperclip? + +> *"Within Paperclip the project itself has all these semantics around the environment that project will run in for your agents, what repos it has access to. So what is the idea of a queue? Where even is this queue? It should be kind of outside of even project..."* + +### The Answer: A Queue Is **Not** a Project — and It Doesn't Need a Heavy New Container Object Either! + +In Paperclip: +- **Projects** bind *execution infrastructure* (Git repos, sandboxes, secrets). +- **Org-Chart Assignment (`assigneeAgentId`)** routes work to *one specific named employee* that Paperclip wakes and runs. +- **A Queue** is simply **an ordered, pullable slice of unassigned `ready` tasks in a Company**, naturally addressed by **Channel** (`build/checkout`, `security/triage`, or `general`) and narrowed by **`key=value` Labels** (`--label role=worker`, `--label step=review`)! + +Why making **Channels + Labels = Queues** (outside of Projects!) works so well: +1. **Zero setup for simple swarms:** `pc tasks create build "Fix test A"` puts an unassigned `todo` task in channel `build`. Immediately, `pc tasks claim --ready build` pops it! You never had to run `queue create` or create a `Project` or bind a Git repo. +2. **Works across 0, 1, or many Projects:** + - **0 Projects (pure headless):** Local CLI workers or external CI jobs pop tasks from `build/` and run in their own local directories. + - **1 Project, many stage queues:** `acme/web` tasks flow through `web/implement` -> `web/review` -> `web/qa`, or stay in `web/build` routed by `--label role=implementer` vs. `--label role=reviewer`. + - **Many Projects, 1 specialist queue:** Security findings across `acme/web`, `acme/api`, and `acme/cloud` all land in `security/triage` (each carrying its own optional `projectId`!). A pool of security agents drains `security/triage` from one place. +3. **Company-wide queue works too:** Omitting the channel (`pc tasks claim --ready --label role=fixer`) pops the oldest ready unassigned task across all readable channels (and channelless company tasks) matching that filter. +4. **Optional Queue Governance When Needed:** Because `channels` has a `queue_config jsonb` column ([Plan 02 §4.1](./2026-11-30-issue-scope-and-channels.md#41-new-channels-table-packagesdbsrcschemachannelsts)), operators *can* attach policy to any channel queue when they graduate past minute 1: + - `defaultLeaseSec` (default `300` = 5m; min `30`, max `3600`) + - `maxLeaseSec` (cap on `--lease` renewals, default `3600` = 1h) + - `maxClaimAttempts` (poison-pill guard: default `5` crashed/expired leases before moving to `blocked` for human/watchdog triage) + - `ordering`: `"priority_fifo"` (default: `critical` -> `high` -> `medium` -> `low`, then `created_at ASC`) or `"strict_fifo"` (`created_at ASC` regardless of priority) + - `allowedRoles` / `allowedAgentIds`: optional claim restriction so untrusted agents cannot pop sensitive queues. + +--- + +## 2. Reconciling Push-Assignee and Pull-Pool Without Breaking Paperclip Invariants + +Paperclip's #1 control-plane invariant ([AGENTS.md §5.3](../../AGENTS.md)) is **single-assignee ownership and atomic checkout**: two agents must never work the same task concurrently. + +Here is how **Named Push Assignment** and **Pool Pull Leases** coexist cleanly as two mutually exclusive modes of the *same* `issues` state machine: + +```mermaid +stateDiagram-v2 + [*] --> Waiting: Created with unresolved blockedByIssueIds + [*] --> ReadyPool: Created status=todo, assignee=null (Unassigned Pool) + [*] --> AssignedPush: Created status=todo, assigneeAgentId=AgentA (Named Employee) + + Waiting --> ReadyPool: All blockedBy reach done (assignee=null) + Waiting --> AssignedPush: All blockedBy reach done (assigneeAgentId=AgentA -> wakes AgentA!) + + AssignedPush --> CheckedOutRun: AgentA calls /checkout with X-Paperclip-Run-Id + ReadyPool --> LeasedClaim: Any eligible worker calls /tasks/claim (5m TTL lease + claimToken) + + LeasedClaim --> LeasedClaim: tasks renew (extends leaseExpiresAt) + LeasedClaim --> ReadyPool: tasks release OR lease expires (claim_epoch increments) + LeasedClaim --> InReviewPool: pc ask / confirm / tasks block (drops lease, waits for answer) + InReviewPool --> ReadyPool: Human/Lead resolves interaction or unblocks! + LeasedClaim --> Done: tasks complete (with valid claimToken) + LeasedClaim --> BlockedPoison: tasks fail (no --requeue) OR attempts >= maxClaimAttempts +``` + +### The Four Golden Rules of Coexistence + +1. **Named Assignee Wins Exclusively (Push Path Unchanged):** + - If `issues.assignee_agent_id IS NOT NULL` or `issues.assignee_user_id IS NOT NULL`, the task is **owned** by that employee/person. + - `tasks claim --ready` **never** steals a task assigned to another agent or user! (However, if `@worker-1` runs `pc tasks claim --ready` authenticated as `@worker-1`, it *may* prioritize `todo` tasks already assigned to `@worker-1` that have no active run, or you can target a role via `--label role=reviewer` instead of hardcoding an `agentId`.) +2. **Unassigned `todo` + Unblocked = `Ready` in the Pool:** + - A task is **claimable from the pool** if and only if ALL of these hold in SQL (regardless of whether `scope` is `'channel'`, `'board'`, or `'agent'`, excluding `'chat'`): + - `scope <> 'chat'` (and `conversation_agent_id IS NULL`) + - `status = 'todo'` + - `hidden_at IS NULL` + - `assignee_agent_id IS NULL AND assignee_user_id IS NULL` + - `checkout_run_id IS NULL AND execution_run_id IS NULL` + - `claim_lease_expires_at IS NULL` (not currently leased) + - **No unresolved blockers:** `NOT EXISTS (SELECT 1 FROM issue_relations r JOIN issues b ON b.id = r.related_issue_id WHERE r.issue_id = issues.id AND r.relation_type = 'blocked_by' AND b.status <> 'done')` + - **No active tree hold:** `NOT EXISTS (SELECT 1 FROM issue_tree_hold_members hm JOIN issue_tree_holds h ON h.id = hm.hold_id WHERE hm.issue_id = issues.id AND h.status = 'active')` +3. **Prompt-Injection / Untrusted-Task Guard on `--ready`:** + - Because a task's `description` becomes instructions to whichever worker claims it, tasks whose `source_trust` marks them as untrusted external ingress (e.g., public webhook/unverified external sender) are **excluded** from wildcard `--ready` claims unless explicitly promoted/triaged by a trusted company member or claimed with `--include-untrusted`. Same-company authenticated members and agents are trusted within company RBAC. +4. **Blocking / Asking a Question Frees the Pool Worker:** + - In Paperclip's *Managed Employee* mode, an agent owns its task across turns: when it posts an `ask_user_questions` card and sets `status = 'in_review'`, `assigneeAgentId` stays set to that agent so answering the card wakes that exact agent back up. + - In *Headless Pool* mode, workers are fungible processes (`worker-1`, `worker-2`, `worker-3` in a loop or CI matrix). Holding a claim while waiting 4 hours for a human answer would deadlock the worker slot! + - Therefore, when a pool-claimed worker runs `pc ask`, `pc confirm`, or `pc tasks block`: + 1. Its active claim lease is **ended cleanly** (`claim_lease_expires_at = NULL`, `claim_token_hash = NULL`, `claim_epoch = claim_epoch + 1`). + 2. The task enters `in_review` (if waiting on an interaction/confirmation card) or `blocked` (if `tasks block ""` was called). + 3. When the human/lead answers the interaction card (or runs `pc tasks unblock `), the server sees `continuationPolicy = 'requeue_on_resolve'` (and `assignee_agent_id IS NULL`), transitions the task right back to `status = 'todo'` (`ready`), and emits `task.ready`! The next free worker in the pool claims it, reads the thread (which now contains the question + human answer), and finishes the job! + +--- + +## 3. Fenced Lease Schema & Atomic SQL Protocol + +We take the exact fencing lesson from Paperclip's own [2026-11-09-explicit-native-lease-claim-tokens.md](./2026-11-09-explicit-native-lease-claim-tokens.md) (`epoch` + `token`, never relying on wall-clock timestamps alone to fence stale writers!). + +### 3.1 New Columns on `issues` (`packages/db/src/schema/issues.ts`) + +```ts +claimEpoch: bigint("claim_epoch", { mode: "number" }).notNull().default(0), +claimTokenHash: text("claim_token_hash"), // SHA-256 of opaque `clm_` bearer secret +claimHolderAgentId: uuid("claim_holder_agent_id").references(() => agents.id, { onDelete: "set null" }), +claimHolderUserId: text("claim_holder_user_id"), +claimHolderProfile: text("claim_holder_profile"), // e.g. "worker-1" when under delegated/local profile +claimLeasedAt: timestamp("claim_leased_at", { withTimezone: true }), +claimLeaseExpiresAt: timestamp("claim_lease_expires_at", { withTimezone: true }), +claimAttemptCount: integer("claim_attempt_count").notNull().default(0), +``` + +Partial indexes for fast queue pop and zero-scan deadline lookup: +```sql +-- Fast FIFO / Priority-FIFO pool pop +CREATE INDEX issues_ready_pool_queue_idx + ON issues (company_id, channel_id, created_at, id) + WHERE scope <> 'chat' + AND conversation_agent_id IS NULL + AND status = 'todo' + AND hidden_at IS NULL + AND assignee_agent_id IS NULL + AND assignee_user_id IS NULL + AND checkout_run_id IS NULL + AND claim_lease_expires_at IS NULL; + +-- Fast next-expiry lookup for sleep-aware work-scheduler.ts +CREATE INDEX issues_active_claim_lease_due_idx + ON issues (claim_lease_expires_at) + WHERE status = 'in_progress' AND claim_lease_expires_at IS NOT NULL; +``` + +### 3.2 Atomic Pool Pop (`POST /api/companies/:companyId/tasks/claim`) + +```sql +WITH candidate AS ( + SELECT i.id + FROM issues i + LEFT JOIN channels c ON c.id = i.channel_id + WHERE i.company_id = $companyId + AND i.scope <> 'chat' + AND i.conversation_agent_id IS NULL + AND i.status = 'todo' + AND i.hidden_at IS NULL + AND i.assignee_agent_id IS NULL + AND i.assignee_user_id IS NULL + AND i.checkout_run_id IS NULL + AND i.execution_run_id IS NULL + AND i.claim_lease_expires_at IS NULL + AND () + AND NOT EXISTS ( + SELECT 1 FROM issue_relations r + JOIN issues b ON b.id = r.related_issue_id + WHERE r.issue_id = i.id AND r.relation_type = 'blocked_by' AND b.status <> 'done' + ) + AND NOT EXISTS ( + SELECT 1 FROM issue_tree_hold_members hm + JOIN issue_tree_holds h ON h.id = hm.hold_id + WHERE hm.issue_id = i.id AND h.status = 'active' + ) + ORDER BY + CASE WHEN $ordering = 'strict_fifo' THEN 0 + ELSE CASE i.priority WHEN 'critical' THEN 0 WHEN 'high' THEN 1 WHEN 'medium' THEN 2 ELSE 3 END + END ASC, + i.created_at ASC, + i.id ASC + FOR UPDATE OF i SKIP LOCKED + LIMIT 1 +) +UPDATE issues t +SET status = 'in_progress', + status_version = t.status_version + 1, + claim_epoch = t.claim_epoch + 1, + claim_token_hash = $tokenHash, + claim_holder_agent_id = $agentId, + claim_holder_user_id = $userId, + claim_holder_profile = $profile, + claim_leased_at = clock_timestamp(), + claim_lease_expires_at = clock_timestamp() + ($leaseSec * interval '1 second'), + claim_attempt_count = t.claim_attempt_count + 1, + started_at = COALESCE(t.started_at, clock_timestamp()), + updated_at = clock_timestamp() +FROM candidate +WHERE t.id = candidate.id +RETURNING t.*; +``` + +Why `FOR UPDATE OF i SKIP LOCKED` is rock-solid here: +- If 20 workers call `tasks claim --ready build/` at the exact same microsecond, **zero workers get a `409` lock collision** — Postgres hands worker 1 task #1, worker 2 task #2, ..., in parallel without serializing behind row locks! +- Only claiming a *specific* task ID (`pc tasks claim PAP-142`) returns `409 task_claimed` (or `task_waiting`, `task_blocked`, `task_assigned`, `task_finished`) when unavailable. + +### 3.3 Blocking `--wait ` on Empty Queue (Zero Polling!) +When `pc tasks claim --ready build/ --wait 10m` runs and the SQL above returns 0 rows: +1. The server does **not** spin in a SQL sleep loop. +2. It subscribes in-memory to `subscribeCompanyLiveEvents(companyId)` listening for `task.ready` / `task.created` / `task.unblocked` / `issue_blockers_resolved` in matching channels. +3. The instant such an event fires, the handler wakes and re-attempts the `FOR UPDATE SKIP LOCKED` pop! Whoever wins returns `200 OK` with the claimed task; any runner-up goes right back to waiting until `--wait` expires (returning `204` / CLI exit code `1` with `reason: "timeout"`). + +### 3.4 Fencing Mutations & Laptop-Sleep-Safe Renewal +Every claim mutation (`renew`, `release`, `complete`, `fail`, `ask`/`block`) supplies the opaque `claimToken` (`X-Paperclip-Claim-Token` header; stored automatically by `pc` CLI in `~/.paperclip/claims//.json` with `0600` permissions): + +- **`renew` (`POST /api/issues/:id/claim/renew`):** + Matches `WHERE id = $1 AND status = 'in_progress' AND claim_epoch = $epoch AND claim_token_hash = $hash`. + Notice the deliberate lesson from [2026-11-09-explicit-native-lease-claim-tokens.md](./2026-11-09-explicit-native-lease-claim-tokens.md): if the worker's laptop slept for 6 minutes past the 5-minute `claim_lease_expires_at`, *and the expiry reconciler or another worker has NOT bumped `claim_epoch` yet*, `claim_epoch = $epoch AND claim_token_hash = $hash` STILL holds, so the waking worker cleanly re-extends its own lease instead of spuriously aborting uncontested work! Once the expiry reconciler runs, it increments `claim_epoch = claim_epoch + 1` and clears `claim_token_hash = NULL`, permanently fencing the old worker (`409 claim_lost`). +- **`complete` (`POST /api/issues/:id/claim/complete`):** + Verifies `claim_epoch` + `claim_token_hash` (and `result_schema_ref` if configured on the task), sets `status = 'done'`, clears `claim_token_hash` and `claim_lease_expires_at`, posts the completion comment / work product in the same transaction, and fires `issue-dependency-wakeups.ts` so any downstream `--needs` tasks immediately flip from `Waiting` to `Ready` (or wake their assigned agents)! +- **`fail` (`POST /api/issues/:id/claim/fail`):** + - Default (`pc tasks fail PAP-142 "Missing prod DB fixture"`): moves task to `status = 'blocked'` with structured `unblockDescriptor` reason, ending the lease so no other worker burns tokens hitting the same wall, and waking the Lead / Watchdog! + - With `--requeue` (`pc tasks fail PAP-142 "Transient network error" --requeue`): returns task to `status = 'todo'` unless `claim_attempt_count >= maxClaimAttempts`, in which case it trips the poison-pill circuit breaker into `status = 'blocked'`. + +--- + +## 4. Sleep-Aware Lease Expiry Reconciliation (`work-scheduler.ts`) + +Per [sleep-aware-background-work.mdc](../../rules/sleep-aware-background-work.mdc), lease expiration MUST NOT add an idle polling interval: + +1. **Source of truth:** `issues` rows where `status = 'in_progress' AND claim_lease_expires_at IS NOT NULL`. +2. **Deadline registration:** Whenever a claim is acquired or renewed, `task-queue.ts` notifies `delivery-work-coordinator.ts` / `work-scheduler.ts` with the earliest `SELECT MIN(claim_lease_expires_at) FROM issues WHERE status = 'in_progress' AND claim_lease_expires_at IS NOT NULL`. +3. **When zero leases are active:** No timer or scheduled SQL exists anywhere in the process; the database connection can release and the Cloud instance can suspend! +4. **When a deadline fires (or at server startup recovery):** + - Atomically sweeps expired rows (`WHERE status = 'in_progress' AND claim_lease_expires_at <= clock_timestamp()`): + - If `claim_attempt_count < maxClaimAttempts`: sets `status = 'todo'`, increments `claim_epoch = claim_epoch + 1`, clears `claim_token_hash` & `claim_lease_expires_at`, logs `task.lease_expired_requeued`, and emits `task.ready` (waking any `claim --wait` listeners!). + - If `claim_attempt_count >= maxClaimAttempts`: sets `status = 'blocked'`, increments `claim_epoch`, clears lease, logs `task.lease_poison_blocked`, and emits `task.blocked` (waking Lead / Task Watchdog!). + - Queries `MIN(claim_lease_expires_at)` of remaining active leases: schedules the exact next deadline if non-null, or goes completely quiet if null. + +--- + +## 5. `pc tasks run`: The Zero-Glue Worker Wrapper + +`pc tasks run` turns *any* CLI coding agent or shell command (`claude`, `codex`, `opencode`, `gemini`, `npm test`, a Python script) into a well-behaved Paperclip worker with **one line**: + +```bash +pc tasks run --ready build/checkout --label role=worker --wait 10m --as worker-1 \ + -- claude -p 'Work task $PAPERCLIP_TASK_ID using pc read / pc reply.' +``` + +### Exact Process Lifecycle of `pc tasks run` +1. **Acquire:** Calls `POST /api/companies/:id/tasks/claim` (specific `` or `--ready` with `--wait`). If `--wait` times out with nothing ready, exits `1` (`timeout`) without running ``. +2. **Environment Injection:** Spawns `` directly via `child_process.spawn` (no shell interpolation!) with: + - `PAPERCLIP_TASK_ID=` (e.g. `PAP-142`) and `PAPERCLIP_ISSUE_UUID=` + - `PAPERCLIP_CLAIM_TOKEN=` and `PAPERCLIP_CLAIM_EPOCH=` (so nested `pc reply`, `pc ask`, or `pc tasks complete` calls inside `` automatically authenticate their claim!) + - `PAPERCLIP_API_URL`, `PAPERCLIP_COMPANY_ID`, and `PAPERCLIP_PROFILE` +3. **Background Heartbeat Renewal:** Starts an in-CLI renewal timer at `leaseSec / 3` (e.g., every 100s for a 5m lease). + - If renewal returns `409 claim_lost` (e.g., an admin force-cancelled or reassigned the task), `pc tasks run` immediately sends `SIGTERM` (followed by `SIGKILL` after 5s grace) to `` and exits `1` so the worker stops touching files! +4. **Signal Handling (`Ctrl-C` / `SIGINT` / `SIGTERM`):** Forwards signal to ``, awaits brief shutdown, calls `POST /api/issues/:id/claim/release` so the task immediately returns to `todo` (`ready`) instead of waiting 5 minutes for TTL expiry, and exits `130` / `143`. +5. **Exit Settlement:** + - If `` already settled the task itself during its run (by calling `pc tasks complete`, `pc ask`, `pc confirm`, or `pc tasks block`), `pc tasks run` detects that the claim was cleanly closed and exits with ``'s exit code! + - Otherwise, if `` exits `0`: automatically calls `complete` (using `--result "..."` if provided). + - If `` exits non-zero: calls `fail` with `"Command exited with code N"` (or `--requeue-on-error` if configured) and propagates ``'s exit code. + +--- + +## 6. Seamless Graduation: Letting Paperclip Runner Drain a Queue Automatically + +Because queues live on Paperclip's core `issues` + `channels` tables, a team can start on Minute 1 with local bash loops: +```bash +for i in 1 2 3; do (while pc tasks run --ready build --as "worker-$i" -- claude ...; do :; done) & done +``` +And on Day 2 — **without changing how tasks or `plan.json` are created** — bind a Paperclip-managed Agent Pool (`channels.queue_config.managedPool = { agentId, maxConcurrency: 4 }`) so Paperclip's native Runner spins up isolated Daytona/local worktree sandboxes to drain `build` automatically under company budget and Task Watchdog governance! diff --git a/docs/api/authentication.md b/docs/api/authentication.md index 79cf850fd6a..8631b7af0eb 100644 --- a/docs/api/authentication.md +++ b/docs/api/authentication.md @@ -19,13 +19,15 @@ This JWT is scoped to the agent and the current run. ### Agent API Keys -Long-lived API keys can be created for agents that need persistent access: +Long-lived API keys can be managed for agents that need persistent access: ``` -POST /api/agents/{agentId}/keys +GET /api/agents/{agentId}/keys +POST /api/agents/{agentId}/keys +DELETE /api/agents/{agentId}/keys/{keyId} ``` -Returns a key that should be stored securely. The key is hashed at rest — you can only see the full value at creation time. +`POST` returns a token that should be stored securely. The key is hashed at rest — you can only see the full value at creation time. All three routes require an interactive board session (`session`, `cloud_tenant`, or `local_implicit`) or a non-scoped, non-profile-locked board API key (`403 Forbidden`, `code: "scope_denied"`, when called with a scoped or profile-locked `board_key`; company-scoped keys without `lockedProfile` or `scopes` remain allowed within their bound company). ### Agent Identity @@ -45,7 +47,11 @@ No authentication required. All requests are treated as the local board operator ### Authenticated Mode -Board operators authenticate via Better Auth sessions (cookie-based). The web UI handles login/logout flows automatically. +Board operators authenticate via Better Auth sessions (cookie-based) or bearer `board_api_keys` minted through interactive CLI auth or key management: + +- **Board API key management (`GET /api/board-api-keys`, `DELETE /api/board-api-keys/{keyId}`)**: Requires a board session, `cloud_tenant`, `local_implicit`, or an unrestricted `board_key`. Restricted `board_key` credentials (`companyId`, `lockedProfile`, or `scopes`) are rejected with `403 Forbidden` (`code: "scope_denied"`). Calling `POST /api/cli-auth/revoke-current` to revoke the calling key itself remains allowed. +- **CLI auth approval (`POST /api/cli-auth/challenges/{id}/approve`)**: Requires an interactive sign-in (`session`, `cloud_tenant`, or `local_implicit`). Any `board_api_key` (`board_key`) receives `canApprove: false` from `GET /api/cli-auth/challenges/{id}` and `403 Forbidden` (`code: "forbidden"`) on `POST .../approve`. +- **Current caller summary (`GET /api/cli-auth/me`)**: Restricted `board_key` callers receive `isInstanceAdmin: false` with `companyIds` and `memberships` filtered to the key's bound company. ## Company Scoping diff --git a/docs/api/headless.md b/docs/api/headless.md new file mode 100644 index 00000000000..4b842b3f4a4 --- /dev/null +++ b/docs/api/headless.md @@ -0,0 +1,135 @@ +--- +title: Headless Board, Channels, Queues & Events +summary: Identity, scoped board keys, channels, schemas, fenced task queues, interactions, schedules, and board events +--- + +Headless endpoints provide machine-first coordination primitives built on top of Paperclip companies, projects, issues, comments, and interactions. + +All routes live under `/api`. Standard company access, canonical authorization, viewer read-only limits, profile locks, and `X-Paperclip-Actor-Scopes` scope restrictions apply to every endpoint below. + +--- + +## Identity & Scoped Board Keys + +### `GET /api/companies/resolve-default` + +Resolves the active default company (or matches `?company=`). In `local_trusted` mode, auto-creates a single workspace company if none exists. Restricted `board_key` actors with `keyCompanyId` only resolve their bound company. + +- **Permissions**: Authenticated board or agent actor (`401` if unauthenticated, `403` on company boundary violation, `404` when `?company` does not match). +- **Response (`200`)**: `{ id, name, issuePrefix, agentIdentityPolicy, apiBase, created }`. + +### `GET /api/whoami` + +Returns the resolved caller identity, active company context, identity policy, effective profile, and intersected client scopes (`X-Paperclip-Actor-Scopes` intersected with `boardApiKeys.scopes`). Accepts optional `?companyId=` or `?company=`. + +- **Permissions**: Authenticated actor in target company (`401`, `403`, `404`, `409 profile_matches_registered_agent` if spoofing a registered agent profile without an agent key). + +### `POST /api/companies/:companyId/agents/connect` + +Creates (or connects an existing active) headless agent and mints a new `agent_api_keys` bearer token. + +- **Body**: `{ name: string, role?: string, ttlSec?: number }`. +- **Permissions**: Unscoped board operator with active non-viewer company membership, `agents:create` on the company, and `agent_config:update` when connecting an existing named agent. Rejected with `403` for agent tokens, viewers, channel-scoped keys, `profile_locked` keys, or callers missing `agents:create` / `agent_config:update`. +- **Activity Log**: `agent_api_key.created`. +- **Response (`201`)**: `{ agentId, agentName, companyId, role, apiKey, apiKeyId, expiresAt, agent }`. + +### `PATCH /api/companies/:companyId/agent-identity-policy` + +Updates the company `agentIdentityPolicy` (`open_local_profiles`, `delegated_profiles`, or `strict_agent_keys`). + +- **Permissions**: Unscoped company owner or administrator (`403` for agent tokens, non-admins, or scoped/profile-locked board keys). + +### Scoped Board API Keys & Agent-Key CLI Challenges + +- `GET /api/board-api-keys`, `DELETE /api/board-api-keys/:keyId`: Lists or revokes the signed-in user's board API keys. Restricted `board_key` credentials (`companyId`, `lockedProfile`, or `scopes`) are rejected with `403 Forbidden` (`code: "scope_denied"`). Self-revocation of the calling key via `POST /api/cli-auth/revoke-current` remains permitted (`200`). +- `POST /api/board-api-keys`: Mints a board API key with optional `{ companyId, lockedProfile, scopes: { channels?, actions? }, expiresAt }`. Child keys cannot widen the caller's scopes, switch companies, or unlock a `lockedProfile` (`403`). Restricted board API keys set `ignoreInstanceAdmin: true` and cannot use instance-admin bypasses. +- `GET /api/cli-auth/me`: Returns board user, company memberships, and `isInstanceAdmin`. Restricted `board_key` callers receive `isInstanceAdmin: false` with `companyIds` and `memberships` filtered to the key's allowed company scope. +- `GET /api/agents/:id/keys`, `POST /api/agents/:id/keys`, `DELETE /api/agents/:id/keys/:keyId`: Manages agent API keys for an accessible agent. Requires an interactive board session (`session`, `cloud_tenant`, `local_implicit`) or a non-scoped, non-profile-locked `board_key` (company-scoped keys without `lockedProfile` or `scopes` remain allowed within their bound company); scoped or profile-locked `board_key` credentials are rejected with `403 Forbidden` (`code: "scope_denied"`). +- `POST /api/cli-auth/challenges`: Accepts optional `challengeKind: "board" | "agent_key"`, `agentName`, and `agentRole`. +- `GET /api/cli-auth/challenges/:id`, `POST /api/cli-auth/challenges/:id/approve`: Approving a CLI auth challenge requires an interactive browser/CLI sign-in (`session`, `cloud_tenant`, or `local_implicit`). Any `board_api_key` (`board_key`) sees `canApprove: false` on `GET` and receives `403 Forbidden` (`code: "forbidden"`) on `POST .../approve`. Approving an `agent_key` challenge additionally requires `agents:create` on the target company (and `agent_config:update` when reusing an existing agent) and mints an `agent_api_keys` row instead of a `board_api_keys` row. + +--- + +## Channels & Schemas + +### `GET /api/companies/:companyId/channels` + +Lists active (or archived when `?includeArchived=true`) channels filtered by caller scopes and private channel membership. Optional `?prefix=`. + +- **Permissions**: `read` scope (`401`, `403`). + +### `POST /api/companies/:companyId/channels` + +Creates or idempotently updates a hierarchical channel (`lowercase/segments`). + +- **Body**: `{ path, description?, visibility?: "open" | "private", defaultProjectId?, queueConfig? }`. +- **Permissions**: `channels.manage` scope, non-viewer company member, `project:read` on `defaultProjectId` (`404` when unreadable), and channel access on any existing private channel or private ancestor (`403 private_ancestor_required` when trying to expose an `open` channel under a `private` ancestor). Privatizing an open channel cascades `"private"` to open descendant channels and issues under them. +- **Activity Log**: `channel.created` / channel updates. + +- **Response (`201`)**: `ChannelView`. + +### `POST /api/companies/:companyId/channels/posts` + +Posts a thread message (`scope = "channel"`, `status = "backlog"`, omitted from board views) to a channel. Supports `idempotencyKey` (same key + mismatched payload returns `409 idempotency_conflict`). + +- **Permissions**: `post` scope, non-viewer member, private channel/ancestor membership, and `project:read` on `projectId` or `channel.defaultProjectId` (`404` when unreadable). +- **Response (`201` created, `200` idempotent replay)**: `HeadlessIssueView`. + +### `GET /api/companies/:companyId/channels/threads` + +Lists visible channel posts/threads ordered newest-first. Supports `?channel=` (including `prefix/`), `?status=`, `?label=` (pushed into SQL before `LIMIT`), `?after=`, and `?limit=`. Enforces canonical `issueReadSqlCondition` and channel visibility/scopes. + +### `GET /api/companies/:companyId/schemas`, `GET /api/companies/:companyId/schemas/:ref`, `POST /api/companies/:companyId/schemas` + +Lists company schemas, fetches a versioned schema (`@`), or registers a new immutable schema revision (same definition replays `200`; differing definition returns `409`). + +### `POST /api/companies/:companyId/issues/batch` + +Atomically creates a batch/DAG of tasks (`tasks[]`, `needs` / `externalNeeds`, optional `projectId`, `resultSchema`, `blocks`) under `pg_advisory_xact_lock` idempotency protection. + +- **Permissions**: `tasks.create` scope, non-viewer member, channel access on target channels and external dependency channels, and `project:read` on supplied or default project IDs (`404` when unreadable). + +### Headless Issue Interceptors & Labels + +- `GET /api/issues/:id`: When `?view=thread`, channel-scoped, or called with a restricted `board_key` (for non-browser requests), returns `ThreadDetailView` after enforcing canonical `issue:read` and channel/scope access checks (`403`/`404`). Channel-scoped keys (`scopes.channels` without `*`) cannot read or mutate unchanneled board issues (`403 scope_denied`), and empty channel-scope intersections (`[]`) remain deny-all. +- `PATCH /api/issues/:id`: Supports headless mutations (`kvLabels`, `labelIf`, `resultSchema`, `blocks`, `projectId`) with `assertCanonicalIssueAccess(..., "issue:mutate")`, `project:read`, and channel-scope checks (including restricted `board_key` guards before falling through on non-headless payloads). +- `POST /api/issues/:id/comments`: Supports `blocks`, `kvLabels`, `after` optimistic concurrency check (`409 newer_message`), `internal`, and `idempotencyKey`, enforcing `issue:comment` and channel-scope access before falling through on non-headless payloads. +- `PATCH /api/issues/:id/kv-labels`: Performs atomic compare-and-swap mutations (`set`, `unset`, `if`) on `issues.kv_labels`. Returns `409 label_conflict` when preconditions fail, emits `labels.changed`, and logs `issue.kv_labels_updated`. + +--- + +## Task Queues, Leases, Interactions, Schedules & Events + +### `GET /api/companies/:companyId/issues` + +Lists headless tasks/issues (when `headless=1`, `channel`, `ready`, `after`, `assignee`, `project`, or a `kv=val` `label` query parameter is passed) filtered by `?channel=`, `?status=`, `?ready=true`, `?project=`, `?assignee=`, `?label=` (multi-value AND, comma OR, key-exists), `?headless=1`, `?after=`, and `?limit=`. All filters, channel ACLs, and `issueReadSqlCondition` are evaluated in SQL before `LIMIT`. + +### `POST /api/companies/:companyId/tasks/claim` + +Claims either an explicit `issueId` or the next ready unblocked task from the pool via `FOR UPDATE SKIP LOCKED`, issuing a single-use `claimToken` (`claimTokenHash` stored at rest) and bumping `claimEpoch`. Supports long-poll `?wait` / `waitSec` on event wakeups. + +- **Gates**: `tasks.claim` scope, non-viewer member, canonical `issueReadSqlCondition`, channel access & queue eligibility (`allowedRoles`, `allowedAgentIds`), active subtree pause holds (`409 issue_paused`), paused projects (`projects.paused_at` -> `409 project_paused`), and `sourceTrust` filtering unless `includeUntrusted: true`. +- **Response (`200` claimed, `204` timeout on empty pool)**: `{ task, claimToken, claimEpoch, leaseExpiresAt, channel }`. + +### Claim Lifecycle (`POST /api/issues/:id/claim/...`) + +Requires `claimToken` (body `claimToken` or `X-Paperclip-Claim-Token` header) and optional matching `claimEpoch` (`409 claim_lost` on mismatch, expiration, or non-`in_progress` state): + +- `POST /api/issues/:id/claim/renew`: Extends `claimLeaseExpiresAt` up to channel `maxLeaseSec` and emits `task.lease_renewed`. +- `POST /api/issues/:id/claim/release`: Returns task to `todo`, clears holder/token, bumps `claimEpoch`, emits `task.lease_released` + `task.ready`. +- `POST /api/issues/:id/claim/complete`: Validates required `resultSchemaRef` against `blocks`/`schema` (`422 result_schema_validation_failed`), marks `done`, clears lease fields, acquires dependent issue locks before advisory event locks, and emits `task.completed` plus `task.unblocked`/`task.ready` for unblocked DAG dependents. +- `POST /api/issues/:id/claim/fail`: Fails the claim (`reason`). Requeues up to channel `maxClaimAttempts` unless `requeue: false`; moves to `blocked` and emits `task.lease_poison_blocked` when exhausted. + +### Interactions (`ask`, `confirm`, `approve`, `reject`) + +- `POST /api/issues/:id/ask`: Creates a pending `ask_user_questions` interaction (`choices?`, `humanOnly?`, `requeueOnResolve?`). Requires valid active claim token if the issue currently has an active claim lease (`409 claim_lost`). +- `POST /api/issues/:id/confirm`: Creates a pending `request_confirmation` interaction (`humanOnly?`, `requeueOnResolve?`), subject to active claim-token verification. +- `POST /api/issues/:id/approve` & `POST /api/issues/:id/reject`: Resolves pending confirmations/questions (enforcing `humanOnly` against agent callers), sets `decision: "approved" | "rejected"`, optionally requeues the task to `todo`, and wakes the assigned agent when configured. + +### Schedules & Board Events + +- `POST /api/companies/:companyId/schedules`: Creates one-shot (`--in` / `--at`) or recurring (`--every`, `--until`) scheduled posts targeting a channel or issue (enforcing `issue:read` + `issue:comment` + channel/scope access for issue targets, and channel access for channel targets). Issue-target schedules with `post: false` post comments and wake assigned non-terminal agents via `heartbeat.wakeup` when due. +- `GET /api/companies/:companyId/schedules`: Lists schedules scoped by optional `?target=`, filtering out schedules whose target channel or issue is unreadable or outside caller channel scopes (`404` when querying an unreadable issue target explicitly). +- `DELETE /api/companies/:companyId/schedules/:id`: Cancels a scheduled post (`schedules.cancel`), enforcing channel access and `issueReadSqlCondition` + channel scopes on issue-targeted schedules (`404` when inaccessible). +- `GET /api/companies/:companyId/events/wait`: Long-polls for the next matching board event after `?after=evt_` (`200` with `BoardEventView`, `204` on timeout with `X-Paperclip-Cursor` header when `after` was omitted so multi-hop waits preserve their starting cursor). +- `GET /api/companies/:companyId/events/stream`: Server-Sent Events stream (`Last-Event-ID` or `?after=`) replaying history then streaming live events. Both `/events/wait` and `/events/stream` enforce `events.read` scope, channel membership/scopes, AND canonical `issueReadSqlCondition` on every event referencing an `issueId`. diff --git a/docs/api/overview.md b/docs/api/overview.md index 03ee8e978c6..94cd90b439d 100644 --- a/docs/api/overview.md +++ b/docs/api/overview.md @@ -71,3 +71,9 @@ company tailnet and select its machines in SSH environments. [Workload identity](workload-identity.md) publishes the public keys that let outside clouds, such as AWS, verify a company's connections without stored cloud keys. + +## Headless Coordination API + +[Headless Board, Channels, Queues & Events](headless.md) covers machine-first +identity, scoped board API keys, hierarchical channels, schemas, DAG batches, +fenced task claims, one-line interactions, schedules, and SSE/wait event streams. diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index 98555be6e89..867e205c2f1 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -924,6 +924,7 @@ const MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS = new Set([ "0508_normal_riptide.sql", "0507_special_kang.sql", "0511_simple_the_hunter.sql", + "0512_stormy_the_hood.sql", ]); async function applyPendingMigrationsManually( diff --git a/packages/db/src/migrations/0512_stormy_the_hood.sql b/packages/db/src/migrations/0512_stormy_the_hood.sql new file mode 100644 index 00000000000..dacd80f7a4f --- /dev/null +++ b/packages/db/src/migrations/0512_stormy_the_hood.sql @@ -0,0 +1,168 @@ +-- paperclip:migration-compat online_compatible: creates new headless board tables (channels, channel_access_members, company_schemas, board_events, scheduled_board_posts, issue_batch_idempotency_keys), adds nullable or constant-default columns to companies, board_api_keys, cli_auth_challenges, issues, and issue_comments, adds NOT VALID foreign-key and check constraints on existing tables then validates under SHARE UPDATE EXCLUSIVE, and builds all indexes on existing tables CONCURRENTLY IF NOT EXISTS. Every statement is idempotent for non-transactional execution. +CREATE TABLE IF NOT EXISTS "channel_access_members" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "company_id" uuid NOT NULL, + "channel_id" uuid NOT NULL, + "subject_type" text NOT NULL, + "subject_id" text NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "channel_access_members_subject_type_check" CHECK ("channel_access_members"."subject_type" in ('user', 'agent')) +); +--> statement-breakpoint +CREATE TABLE IF NOT EXISTS "channels" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "company_id" uuid NOT NULL, + "path" text NOT NULL, + "description" text, + "visibility" text DEFAULT 'open' NOT NULL, + "default_project_id" uuid, + "queue_config" jsonb DEFAULT '{}'::jsonb NOT NULL, + "created_by_agent_id" uuid, + "created_by_user_id" text, + "created_by_profile" text, + "archived_at" timestamp with time zone, + "last_activity_at" timestamp with time zone DEFAULT now() NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "channels_visibility_check" CHECK ("channels"."visibility" in ('open', 'private')), + CONSTRAINT "channels_path_check" CHECK ("channels"."path" ~ '^[a-z0-9][a-z0-9_-]*(/[a-z0-9][a-z0-9_-]*)*$') +); +--> statement-breakpoint +CREATE TABLE IF NOT EXISTS "company_schemas" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "company_id" uuid NOT NULL, + "name" text NOT NULL, + "version" integer NOT NULL, + "description" text, + "json_schema" jsonb NOT NULL, + "created_by_user_id" text, + "created_by_agent_id" uuid, + "created_by_profile" text, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "company_schemas_version_check" CHECK ("company_schemas"."version" >= 1) +); +--> statement-breakpoint +CREATE TABLE IF NOT EXISTS "board_events" ( + "seq" bigserial PRIMARY KEY NOT NULL, + "company_id" uuid NOT NULL, + "event_type" text NOT NULL, + "channel_id" uuid, + "channel_path" text, + "issue_id" uuid, + "identifier" text, + "actor_type" text DEFAULT 'system' NOT NULL, + "actor_id" text, + "actor_name" text, + "actor_profile" text, + "payload" jsonb DEFAULT '{}'::jsonb NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE IF NOT EXISTS "issue_batch_idempotency_keys" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "company_id" uuid NOT NULL, + "idempotency_key" text NOT NULL, + "request_hash" text NOT NULL, + "response_payload" jsonb NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE IF NOT EXISTS "scheduled_board_posts" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "company_id" uuid NOT NULL, + "target" text NOT NULL, + "channel_id" uuid, + "issue_id" uuid, + "message" text NOT NULL, + "post_only" boolean DEFAULT false NOT NULL, + "kv_labels" jsonb DEFAULT '{}'::jsonb NOT NULL, + "schema_blocks" jsonb DEFAULT '[]'::jsonb NOT NULL, + "interval_ms" bigint, + "until_at" timestamp with time zone, + "next_run_at" timestamp with time zone NOT NULL, + "last_run_at" timestamp with time zone, + "run_count" integer DEFAULT 0 NOT NULL, + "status" text DEFAULT 'scheduled' NOT NULL, + "author_user_id" text, + "author_agent_id" uuid, + "author_profile" text, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "scheduled_board_posts_status_check" CHECK ("scheduled_board_posts"."status" in ('scheduled', 'cancelled', 'completed')) +); +--> statement-breakpoint +ALTER TABLE "board_api_keys" ADD COLUMN IF NOT EXISTS "company_id" uuid;--> statement-breakpoint +ALTER TABLE "board_api_keys" ADD COLUMN IF NOT EXISTS "locked_profile" text;--> statement-breakpoint +ALTER TABLE "board_api_keys" ADD COLUMN IF NOT EXISTS "scopes" jsonb;--> statement-breakpoint +ALTER TABLE "agent_api_keys" ADD COLUMN IF NOT EXISTS "expires_at" timestamp with time zone;--> statement-breakpoint +ALTER TABLE "cli_auth_challenges" ADD COLUMN IF NOT EXISTS "challenge_kind" text DEFAULT 'board' NOT NULL;--> statement-breakpoint +ALTER TABLE "cli_auth_challenges" ADD COLUMN IF NOT EXISTS "requested_agent_name" text;--> statement-breakpoint +ALTER TABLE "cli_auth_challenges" ADD COLUMN IF NOT EXISTS "requested_agent_role" text;--> statement-breakpoint +ALTER TABLE "cli_auth_challenges" ADD COLUMN IF NOT EXISTS "approved_agent_id" uuid;--> statement-breakpoint +ALTER TABLE "companies" ADD COLUMN IF NOT EXISTS "agent_identity_policy" text;--> statement-breakpoint +ALTER TABLE "issue_comments" ADD COLUMN IF NOT EXISTS "actor_profile" text;--> statement-breakpoint +ALTER TABLE "issue_comments" ADD COLUMN IF NOT EXISTS "kv_labels" jsonb DEFAULT '{}'::jsonb NOT NULL;--> statement-breakpoint +ALTER TABLE "issue_comments" ADD COLUMN IF NOT EXISTS "schema_blocks" jsonb DEFAULT '[]'::jsonb NOT NULL;--> statement-breakpoint +ALTER TABLE "issue_comments" ADD COLUMN IF NOT EXISTS "no_sync" boolean DEFAULT false NOT NULL;--> statement-breakpoint +ALTER TABLE "issues" ADD COLUMN IF NOT EXISTS "channel_id" uuid;--> statement-breakpoint +ALTER TABLE "issues" ADD COLUMN IF NOT EXISTS "created_by_profile" text;--> statement-breakpoint +ALTER TABLE "issues" ADD COLUMN IF NOT EXISTS "kv_labels" jsonb DEFAULT '{}'::jsonb NOT NULL;--> statement-breakpoint +ALTER TABLE "issues" ADD COLUMN IF NOT EXISTS "schema_blocks" jsonb DEFAULT '[]'::jsonb NOT NULL;--> statement-breakpoint +ALTER TABLE "issues" ADD COLUMN IF NOT EXISTS "result_schema_ref" text;--> statement-breakpoint +ALTER TABLE "issues" ADD COLUMN IF NOT EXISTS "claim_epoch" bigint DEFAULT 0 NOT NULL;--> statement-breakpoint +ALTER TABLE "issues" ADD COLUMN IF NOT EXISTS "claim_token_hash" text;--> statement-breakpoint +ALTER TABLE "issues" ADD COLUMN IF NOT EXISTS "claim_holder_agent_id" uuid;--> statement-breakpoint +ALTER TABLE "issues" ADD COLUMN IF NOT EXISTS "claim_holder_user_id" text;--> statement-breakpoint +ALTER TABLE "issues" ADD COLUMN IF NOT EXISTS "claim_holder_profile" text;--> statement-breakpoint +ALTER TABLE "issues" ADD COLUMN IF NOT EXISTS "claim_leased_at" timestamp with time zone;--> statement-breakpoint +ALTER TABLE "issues" ADD COLUMN IF NOT EXISTS "claim_lease_expires_at" timestamp with time zone;--> statement-breakpoint +ALTER TABLE "issues" ADD COLUMN IF NOT EXISTS "claim_attempt_count" integer DEFAULT 0 NOT NULL;--> statement-breakpoint +ALTER TABLE "channel_access_members" DROP CONSTRAINT IF EXISTS "channel_access_members_company_id_companies_id_fk", ADD CONSTRAINT "channel_access_members_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "channel_access_members" DROP CONSTRAINT IF EXISTS "channel_access_members_channel_id_channels_id_fk", ADD CONSTRAINT "channel_access_members_channel_id_channels_id_fk" FOREIGN KEY ("channel_id") REFERENCES "public"."channels"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "channels" DROP CONSTRAINT IF EXISTS "channels_company_id_companies_id_fk", ADD CONSTRAINT "channels_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "channels" DROP CONSTRAINT IF EXISTS "channels_default_project_id_projects_id_fk", ADD CONSTRAINT "channels_default_project_id_projects_id_fk" FOREIGN KEY ("default_project_id") REFERENCES "public"."projects"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "channels" DROP CONSTRAINT IF EXISTS "channels_created_by_agent_id_agents_id_fk", ADD CONSTRAINT "channels_created_by_agent_id_agents_id_fk" FOREIGN KEY ("created_by_agent_id") REFERENCES "public"."agents"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "company_schemas" DROP CONSTRAINT IF EXISTS "company_schemas_company_id_companies_id_fk", ADD CONSTRAINT "company_schemas_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "company_schemas" DROP CONSTRAINT IF EXISTS "company_schemas_created_by_agent_id_agents_id_fk", ADD CONSTRAINT "company_schemas_created_by_agent_id_agents_id_fk" FOREIGN KEY ("created_by_agent_id") REFERENCES "public"."agents"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "board_events" DROP CONSTRAINT IF EXISTS "board_events_company_id_companies_id_fk", ADD CONSTRAINT "board_events_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "board_events" DROP CONSTRAINT IF EXISTS "board_events_channel_id_channels_id_fk", ADD CONSTRAINT "board_events_channel_id_channels_id_fk" FOREIGN KEY ("channel_id") REFERENCES "public"."channels"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "board_events" DROP CONSTRAINT IF EXISTS "board_events_issue_id_issues_id_fk", ADD CONSTRAINT "board_events_issue_id_issues_id_fk" FOREIGN KEY ("issue_id") REFERENCES "public"."issues"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "issue_batch_idempotency_keys" DROP CONSTRAINT IF EXISTS "issue_batch_idempotency_keys_company_id_companies_id_fk", ADD CONSTRAINT "issue_batch_idempotency_keys_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "scheduled_board_posts" DROP CONSTRAINT IF EXISTS "scheduled_board_posts_company_id_companies_id_fk", ADD CONSTRAINT "scheduled_board_posts_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "scheduled_board_posts" DROP CONSTRAINT IF EXISTS "scheduled_board_posts_channel_id_channels_id_fk", ADD CONSTRAINT "scheduled_board_posts_channel_id_channels_id_fk" FOREIGN KEY ("channel_id") REFERENCES "public"."channels"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "scheduled_board_posts" DROP CONSTRAINT IF EXISTS "scheduled_board_posts_issue_id_issues_id_fk", ADD CONSTRAINT "scheduled_board_posts_issue_id_issues_id_fk" FOREIGN KEY ("issue_id") REFERENCES "public"."issues"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "scheduled_board_posts" DROP CONSTRAINT IF EXISTS "scheduled_board_posts_author_agent_id_agents_id_fk", ADD CONSTRAINT "scheduled_board_posts_author_agent_id_agents_id_fk" FOREIGN KEY ("author_agent_id") REFERENCES "public"."agents"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +CREATE UNIQUE INDEX IF NOT EXISTS "channel_access_members_channel_subject_uq" ON "channel_access_members" USING btree ("channel_id","subject_type","subject_id");--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "channel_access_members_subject_lookup_idx" ON "channel_access_members" USING btree ("company_id","subject_type","subject_id","channel_id");--> statement-breakpoint +CREATE UNIQUE INDEX IF NOT EXISTS "channels_company_path_uq" ON "channels" USING btree ("company_id","path");--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "channels_company_activity_idx" ON "channels" USING btree ("company_id","last_activity_at");--> statement-breakpoint +CREATE UNIQUE INDEX IF NOT EXISTS "company_schemas_company_name_version_uq" ON "company_schemas" USING btree ("company_id","name","version");--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "board_events_company_seq_idx" ON "board_events" USING btree ("company_id","seq");--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "board_events_company_channel_seq_idx" ON "board_events" USING btree ("company_id","channel_path","seq");--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "board_events_company_issue_seq_idx" ON "board_events" USING btree ("company_id","issue_id","seq");--> statement-breakpoint +CREATE UNIQUE INDEX IF NOT EXISTS "issue_batch_idempotency_keys_company_key_uq" ON "issue_batch_idempotency_keys" USING btree ("company_id","idempotency_key");--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "scheduled_board_posts_due_idx" ON "scheduled_board_posts" USING btree ("next_run_at") WHERE "scheduled_board_posts"."status" = 'scheduled';--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "scheduled_board_posts_company_idx" ON "scheduled_board_posts" USING btree ("company_id","status","next_run_at");--> statement-breakpoint +ALTER TABLE "board_api_keys" DROP CONSTRAINT IF EXISTS "board_api_keys_company_id_companies_id_fk", ADD CONSTRAINT "board_api_keys_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action NOT VALID;--> statement-breakpoint +ALTER TABLE "board_api_keys" VALIDATE CONSTRAINT "board_api_keys_company_id_companies_id_fk";--> statement-breakpoint +ALTER TABLE "cli_auth_challenges" DROP CONSTRAINT IF EXISTS "cli_auth_challenges_approved_agent_id_agents_id_fk", ADD CONSTRAINT "cli_auth_challenges_approved_agent_id_agents_id_fk" FOREIGN KEY ("approved_agent_id") REFERENCES "public"."agents"("id") ON DELETE set null ON UPDATE no action NOT VALID;--> statement-breakpoint +ALTER TABLE "cli_auth_challenges" VALIDATE CONSTRAINT "cli_auth_challenges_approved_agent_id_agents_id_fk";--> statement-breakpoint +ALTER TABLE "issues" DROP CONSTRAINT IF EXISTS "issues_channel_id_channels_id_fk", ADD CONSTRAINT "issues_channel_id_channels_id_fk" FOREIGN KEY ("channel_id") REFERENCES "public"."channels"("id") ON DELETE set null ON UPDATE no action NOT VALID;--> statement-breakpoint +ALTER TABLE "issues" VALIDATE CONSTRAINT "issues_channel_id_channels_id_fk";--> statement-breakpoint +ALTER TABLE "issues" DROP CONSTRAINT IF EXISTS "issues_claim_holder_agent_id_agents_id_fk", ADD CONSTRAINT "issues_claim_holder_agent_id_agents_id_fk" FOREIGN KEY ("claim_holder_agent_id") REFERENCES "public"."agents"("id") ON DELETE set null ON UPDATE no action NOT VALID;--> statement-breakpoint +ALTER TABLE "issues" VALIDATE CONSTRAINT "issues_claim_holder_agent_id_agents_id_fk";--> statement-breakpoint +ALTER TABLE "companies" DROP CONSTRAINT IF EXISTS "companies_agent_identity_policy_check", ADD CONSTRAINT "companies_agent_identity_policy_check" CHECK ("companies"."agent_identity_policy" is null or "companies"."agent_identity_policy" in ('open_local_profiles', 'delegated_profiles', 'strict_agent_keys')) NOT VALID;--> statement-breakpoint +ALTER TABLE "companies" VALIDATE CONSTRAINT "companies_agent_identity_policy_check";--> statement-breakpoint +ALTER TABLE "issues" DROP CONSTRAINT IF EXISTS "issues_conversation_channel_exclusion_check", ADD CONSTRAINT "issues_conversation_channel_exclusion_check" CHECK (("issues"."conversation_agent_id" is null) or ("issues"."channel_id" is null)) NOT VALID;--> statement-breakpoint +ALTER TABLE "issues" VALIDATE CONSTRAINT "issues_conversation_channel_exclusion_check";--> statement-breakpoint +CREATE INDEX CONCURRENTLY IF NOT EXISTS "board_api_keys_company_idx" ON "board_api_keys" USING btree ("company_id");--> statement-breakpoint +CREATE INDEX CONCURRENTLY IF NOT EXISTS "issues_company_channel_created_idx" ON "issues" USING btree ("company_id","channel_id","created_at");--> statement-breakpoint +CREATE INDEX CONCURRENTLY IF NOT EXISTS "issues_kv_labels_gin_idx" ON "issues" USING gin ("kv_labels");--> statement-breakpoint +CREATE INDEX CONCURRENTLY IF NOT EXISTS "issues_ready_pool_queue_idx" ON "issues" USING btree ("company_id","channel_id","priority","created_at") WHERE "issues"."status" = 'todo' + and "issues"."assignee_agent_id" is null + and "issues"."assignee_user_id" is null + and "issues"."hidden_at" is null + and "issues"."conversation_agent_id" is null;--> statement-breakpoint +CREATE INDEX CONCURRENTLY IF NOT EXISTS "issues_active_claim_lease_due_idx" ON "issues" USING btree ("claim_lease_expires_at") WHERE "issues"."status" = 'in_progress' + and "issues"."claim_lease_expires_at" is not null + and "issues"."claim_token_hash" is not null; diff --git a/packages/db/src/migrations/meta/0507_snapshot.json b/packages/db/src/migrations/meta/0512_snapshot.json similarity index 97% rename from packages/db/src/migrations/meta/0507_snapshot.json rename to packages/db/src/migrations/meta/0512_snapshot.json index 3bf58602f08..317c453ad6d 100644 --- a/packages/db/src/migrations/meta/0507_snapshot.json +++ b/packages/db/src/migrations/meta/0512_snapshot.json @@ -1,6 +1,6 @@ { - "id": "2f88a046-845e-47f5-ad81-b3b338c79fb5", - "prevId": "7adc8220-8196-44a5-94ee-26f8f5c33dee", + "id": "d51fc684-2373-470f-91c1-bdb01e0def42", + "prevId": "081cc14c-5504-4a93-8b4c-e5945f3936c3", "version": "7", "dialect": "postgresql", "tables": { @@ -1842,6 +1842,12 @@ "primaryKey": false, "notNull": false }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, "last_used_at": { "name": "last_used_at", "type": "timestamp with time zone", @@ -6878,6 +6884,24 @@ "primaryKey": false, "notNull": true }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "locked_profile": { + "name": "locked_profile", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scopes": { + "name": "scopes", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, "name": { "name": "name", "type": "text", @@ -6946,6 +6970,21 @@ "concurrently": false, "method": "btree", "with": {} + }, + "board_api_keys_company_idx": { + "name": "board_api_keys_company_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} } }, "foreignKeys": { @@ -6961,6 +7000,19 @@ ], "onDelete": "cascade", "onUpdate": "no action" + }, + "board_api_keys_company_id_companies_id_fk": { + "name": "board_api_keys_company_id_companies_id_fk", + "tableFrom": "board_api_keys", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" } }, "compositePrimaryKeys": {}, @@ -10363,6 +10415,345 @@ }, "isRLSEnabled": false }, + "public.channel_access_members": { + "name": "channel_access_members", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "subject_type": { + "name": "subject_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject_id": { + "name": "subject_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "channel_access_members_channel_subject_uq": { + "name": "channel_access_members_channel_subject_uq", + "columns": [ + { + "expression": "channel_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "subject_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "subject_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "channel_access_members_subject_lookup_idx": { + "name": "channel_access_members_subject_lookup_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "subject_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "subject_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "channel_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "channel_access_members_company_id_companies_id_fk": { + "name": "channel_access_members_company_id_companies_id_fk", + "tableFrom": "channel_access_members", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "channel_access_members_channel_id_channels_id_fk": { + "name": "channel_access_members_channel_id_channels_id_fk", + "tableFrom": "channel_access_members", + "tableTo": "channels", + "columnsFrom": [ + "channel_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "channel_access_members_subject_type_check": { + "name": "channel_access_members_subject_type_check", + "value": "\"channel_access_members\".\"subject_type\" in ('user', 'agent')" + } + }, + "isRLSEnabled": false + }, + "public.channels": { + "name": "channels", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "visibility": { + "name": "visibility", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "default_project_id": { + "name": "default_project_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "queue_config": { + "name": "queue_config", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "created_by_agent_id": { + "name": "created_by_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by_profile": { + "name": "created_by_profile", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "channels_company_path_uq": { + "name": "channels_company_path_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "path", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "channels_company_activity_idx": { + "name": "channels_company_activity_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_activity_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "channels_company_id_companies_id_fk": { + "name": "channels_company_id_companies_id_fk", + "tableFrom": "channels", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "channels_default_project_id_projects_id_fk": { + "name": "channels_default_project_id_projects_id_fk", + "tableFrom": "channels", + "tableTo": "projects", + "columnsFrom": [ + "default_project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "channels_created_by_agent_id_agents_id_fk": { + "name": "channels_created_by_agent_id_agents_id_fk", + "tableFrom": "channels", + "tableTo": "agents", + "columnsFrom": [ + "created_by_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "channels_visibility_check": { + "name": "channels_visibility_check", + "value": "\"channels\".\"visibility\" in ('open', 'private')" + }, + "channels_path_check": { + "name": "channels_path_check", + "value": "\"channels\".\"path\" ~ '^[a-z0-9][a-z0-9_-]*(/[a-z0-9][a-z0-9_-]*)*$'" + } + }, + "isRLSEnabled": false + }, "public.chat_actions": { "name": "chat_actions", "schema": "", @@ -16464,6 +16855,25 @@ "notNull": true, "default": "'board'" }, + "challenge_kind": { + "name": "challenge_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'board'" + }, + "requested_agent_name": { + "name": "requested_agent_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "requested_agent_role": { + "name": "requested_agent_role", + "type": "text", + "primaryKey": false, + "notNull": false + }, "requested_company_id": { "name": "requested_company_id", "type": "uuid", @@ -16494,6 +16904,12 @@ "primaryKey": false, "notNull": false }, + "approved_agent_id": { + "name": "approved_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, "approved_at": { "name": "approved_at", "type": "timestamp with time zone", @@ -16613,6 +17029,19 @@ ], "onDelete": "set null", "onUpdate": "no action" + }, + "cli_auth_challenges_approved_agent_id_agents_id_fk": { + "name": "cli_auth_challenges_approved_agent_id_agents_id_fk", + "tableFrom": "cli_auth_challenges", + "tableTo": "agents", + "columnsFrom": [ + "approved_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" } }, "compositePrimaryKeys": {}, @@ -16754,6 +17183,12 @@ "primaryKey": false, "notNull": false }, + "agent_identity_policy": { + "name": "agent_identity_policy", + "type": "text", + "primaryKey": false, + "notNull": false + }, "created_at": { "name": "created_at", "type": "timestamp with time zone", @@ -16790,7 +17225,12 @@ "compositePrimaryKeys": {}, "uniqueConstraints": {}, "policies": {}, - "checkConstraints": {}, + "checkConstraints": { + "companies_agent_identity_policy_check": { + "name": "companies_agent_identity_policy_check", + "value": "\"companies\".\"agent_identity_policy\" is null or \"companies\".\"agent_identity_policy\" in ('open_local_profiles', 'delegated_profiles', 'strict_agent_keys')" + } + }, "isRLSEnabled": false }, "public.company_logos": { @@ -17326,6 +17766,141 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.company_schemas": { + "name": "company_schemas", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "json_schema": { + "name": "json_schema", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by_agent_id": { + "name": "created_by_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_by_profile": { + "name": "created_by_profile", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "company_schemas_company_name_version_uq": { + "name": "company_schemas_company_name_version_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "company_schemas_company_id_companies_id_fk": { + "name": "company_schemas_company_id_companies_id_fk", + "tableFrom": "company_schemas", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "company_schemas_created_by_agent_id_agents_id_fk": { + "name": "company_schemas_created_by_agent_id_agents_id_fk", + "tableFrom": "company_schemas", + "tableTo": "agents", + "columnsFrom": [ + "created_by_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "company_schemas_version_check": { + "name": "company_schemas_version_check", + "value": "\"company_schemas\".\"version\" >= 1" + } + }, + "isRLSEnabled": false + }, "public.company_secret_bindings": { "name": "company_secret_bindings", "schema": "", @@ -26298,6 +26873,160 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.document_annotation_comment_reactions": { + "name": "document_annotation_comment_reactions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "comment_id": { + "name": "comment_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "reaction": { + "name": "reaction", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_type": { + "name": "actor_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "removed_at": { + "name": "removed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "document_annotation_comment_reactions_company_comment_idx": { + "name": "document_annotation_comment_reactions_company_comment_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "comment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "document_annotation_comment_reactions_comment_reaction_actor_idx": { + "name": "document_annotation_comment_reactions_comment_reaction_actor_idx", + "columns": [ + { + "expression": "comment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "reaction", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "actor_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "actor_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "document_annotation_comment_reactions_company_id_companies_id_fk": { + "name": "document_annotation_comment_reactions_company_id_companies_id_fk", + "tableFrom": "document_annotation_comment_reactions", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "document_annotation_comment_reactions_comment_id_document_annotation_comments_id_fk": { + "name": "document_annotation_comment_reactions_comment_id_document_annotation_comments_id_fk", + "tableFrom": "document_annotation_comment_reactions", + "tableTo": "document_annotation_comments", + "columnsFrom": [ + "comment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "document_annotation_comment_reactions_reaction_chk": { + "name": "document_annotation_comment_reactions_reaction_chk", + "value": "\"document_annotation_comment_reactions\".\"reaction\" in ('done', 'check', 'thumbs_up', 'question')" + }, + "document_annotation_comment_reactions_actor_type_chk": { + "name": "document_annotation_comment_reactions_actor_type_chk", + "value": "\"document_annotation_comment_reactions\".\"actor_type\" in ('agent', 'user')" + } + }, + "isRLSEnabled": false + }, "public.document_annotation_comments": { "name": "document_annotation_comments", "schema": "", @@ -35094,6 +35823,546 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.board_events": { + "name": "board_events", + "schema": "", + "columns": { + "seq": { + "name": "seq", + "type": "bigserial", + "primaryKey": true, + "notNull": true + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "event_type": { + "name": "event_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "channel_path": { + "name": "channel_path", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "issue_id": { + "name": "issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_type": { + "name": "actor_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'system'" + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_name": { + "name": "actor_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_profile": { + "name": "actor_profile", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "board_events_company_seq_idx": { + "name": "board_events_company_seq_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "seq", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "board_events_company_channel_seq_idx": { + "name": "board_events_company_channel_seq_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "channel_path", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "seq", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "board_events_company_issue_seq_idx": { + "name": "board_events_company_issue_seq_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "issue_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "seq", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "board_events_company_id_companies_id_fk": { + "name": "board_events_company_id_companies_id_fk", + "tableFrom": "board_events", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "board_events_channel_id_channels_id_fk": { + "name": "board_events_channel_id_channels_id_fk", + "tableFrom": "board_events", + "tableTo": "channels", + "columnsFrom": [ + "channel_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "board_events_issue_id_issues_id_fk": { + "name": "board_events_issue_id_issues_id_fk", + "tableFrom": "board_events", + "tableTo": "issues", + "columnsFrom": [ + "issue_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.issue_batch_idempotency_keys": { + "name": "issue_batch_idempotency_keys", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_hash": { + "name": "request_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "response_payload": { + "name": "response_payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "issue_batch_idempotency_keys_company_key_uq": { + "name": "issue_batch_idempotency_keys_company_key_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "idempotency_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "issue_batch_idempotency_keys_company_id_companies_id_fk": { + "name": "issue_batch_idempotency_keys_company_id_companies_id_fk", + "tableFrom": "issue_batch_idempotency_keys", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scheduled_board_posts": { + "name": "scheduled_board_posts", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "target": { + "name": "target", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "issue_id": { + "name": "issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "post_only": { + "name": "post_only", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "kv_labels": { + "name": "kv_labels", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "schema_blocks": { + "name": "schema_blocks", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "interval_ms": { + "name": "interval_ms", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "until_at": { + "name": "until_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "next_run_at": { + "name": "next_run_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "last_run_at": { + "name": "last_run_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "run_count": { + "name": "run_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'scheduled'" + }, + "author_user_id": { + "name": "author_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "author_agent_id": { + "name": "author_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "author_profile": { + "name": "author_profile", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scheduled_board_posts_due_idx": { + "name": "scheduled_board_posts_due_idx", + "columns": [ + { + "expression": "next_run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"scheduled_board_posts\".\"status\" = 'scheduled'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "scheduled_board_posts_company_idx": { + "name": "scheduled_board_posts_company_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "next_run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scheduled_board_posts_company_id_companies_id_fk": { + "name": "scheduled_board_posts_company_id_companies_id_fk", + "tableFrom": "scheduled_board_posts", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scheduled_board_posts_channel_id_channels_id_fk": { + "name": "scheduled_board_posts_channel_id_channels_id_fk", + "tableFrom": "scheduled_board_posts", + "tableTo": "channels", + "columnsFrom": [ + "channel_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scheduled_board_posts_issue_id_issues_id_fk": { + "name": "scheduled_board_posts_issue_id_issues_id_fk", + "tableFrom": "scheduled_board_posts", + "tableTo": "issues", + "columnsFrom": [ + "issue_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scheduled_board_posts_author_agent_id_agents_id_fk": { + "name": "scheduled_board_posts_author_agent_id_agents_id_fk", + "tableFrom": "scheduled_board_posts", + "tableTo": "agents", + "columnsFrom": [ + "author_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "scheduled_board_posts_status_check": { + "name": "scheduled_board_posts_status_check", + "value": "\"scheduled_board_posts\".\"status\" in ('scheduled', 'cancelled', 'completed')" + } + }, + "isRLSEnabled": false + }, "public.heartbeat_run_events": { "name": "heartbeat_run_events", "schema": "", @@ -36739,6 +38008,62 @@ "method": "btree", "with": {} }, + "heartbeat_runs_attention_resumed_idx": { + "name": "heartbeat_runs_attention_resumed_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"issue_id\"::text, \"native_issue_id\"::text,\n \"context_snapshot\"->>'issueId', \"context_snapshot\"->>'taskId')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"heartbeat_runs\".\"status\" in ('running', 'succeeded')", + "concurrently": true, + "method": "btree", + "with": {} + }, + "heartbeat_runs_attention_history_idx": { + "name": "heartbeat_runs_attention_history_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": false, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"heartbeat_runs\".\"status\" in ('failed', 'timed_out') or \"heartbeat_runs\".\"error_code\" = 'provider_limit_wait'", + "concurrently": true, + "method": "btree", + "with": {} + }, "heartbeat_runs_company_ctx_issue_created_idx": { "name": "heartbeat_runs_company_ctx_issue_created_idx", "columns": [ @@ -39093,6 +40418,33 @@ "primaryKey": false, "notNull": false }, + "actor_profile": { + "name": "actor_profile", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kv_labels": { + "name": "kv_labels", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "schema_blocks": { + "name": "schema_blocks", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "no_sync": { + "name": "no_sync", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, "source_trust": { "name": "source_trust", "type": "jsonb", @@ -44020,6 +45372,12 @@ "primaryKey": false, "notNull": false }, + "channel_id": { + "name": "channel_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, "project_workspace_id": { "name": "project_workspace_id", "type": "uuid", @@ -44083,6 +45441,13 @@ "notNull": true, "default": "'backlog'" }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'board'" + }, "status_version": { "name": "status_version", "type": "bigint", @@ -44170,12 +45535,88 @@ "primaryKey": false, "notNull": false }, + "created_by_profile": { + "name": "created_by_profile", + "type": "text", + "primaryKey": false, + "notNull": false + }, "responsible_user_id": { "name": "responsible_user_id", "type": "text", "primaryKey": false, "notNull": false }, + "kv_labels": { + "name": "kv_labels", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "schema_blocks": { + "name": "schema_blocks", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "result_schema_ref": { + "name": "result_schema_ref", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claim_epoch": { + "name": "claim_epoch", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "claim_token_hash": { + "name": "claim_token_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claim_holder_agent_id": { + "name": "claim_holder_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "claim_holder_user_id": { + "name": "claim_holder_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claim_holder_profile": { + "name": "claim_holder_profile", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claim_leased_at": { + "name": "claim_leased_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "claim_lease_expires_at": { + "name": "claim_lease_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "claim_attempt_count": { + "name": "claim_attempt_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, "issue_number": { "name": "issue_number", "type": "integer", @@ -44449,6 +45890,60 @@ "method": "btree", "with": {} }, + "issues_company_scope_status_idx": { + "name": "issues_company_scope_status_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scope", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "issues_company_scope_updated_idx": { + "name": "issues_company_scope_updated_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scope", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, "issues_company_harness_kind_idx": { "name": "issues_company_harness_kind_idx", "columns": [ @@ -45139,6 +46634,98 @@ "concurrently": false, "method": "btree", "with": {} + }, + "issues_company_channel_created_idx": { + "name": "issues_company_channel_created_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "channel_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "issues_kv_labels_gin_idx": { + "name": "issues_kv_labels_gin_idx", + "columns": [ + { + "expression": "kv_labels", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "gin", + "with": {} + }, + "issues_ready_pool_queue_idx": { + "name": "issues_ready_pool_queue_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "channel_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "priority", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"issues\".\"status\" = 'todo'\n and \"issues\".\"assignee_agent_id\" is null\n and \"issues\".\"assignee_user_id\" is null\n and \"issues\".\"hidden_at\" is null\n and \"issues\".\"conversation_agent_id\" is null", + "concurrently": true, + "method": "btree", + "with": {} + }, + "issues_active_claim_lease_due_idx": { + "name": "issues_active_claim_lease_due_idx", + "columns": [ + { + "expression": "claim_lease_expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"issues\".\"status\" = 'in_progress'\n and \"issues\".\"claim_lease_expires_at\" is not null\n and \"issues\".\"claim_token_hash\" is not null", + "concurrently": true, + "method": "btree", + "with": {} } }, "foreignKeys": { @@ -45181,6 +46768,19 @@ "onDelete": "no action", "onUpdate": "no action" }, + "issues_channel_id_channels_id_fk": { + "name": "issues_channel_id_channels_id_fk", + "tableFrom": "issues", + "tableTo": "channels", + "columnsFrom": [ + "channel_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, "issues_project_workspace_id_project_workspaces_id_fk": { "name": "issues_project_workspace_id_project_workspaces_id_fk", "tableFrom": "issues", @@ -45298,6 +46898,19 @@ "onDelete": "no action", "onUpdate": "no action" }, + "issues_claim_holder_agent_id_agents_id_fk": { + "name": "issues_claim_holder_agent_id_agents_id_fk", + "tableFrom": "issues", + "tableTo": "agents", + "columnsFrom": [ + "claim_holder_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, "issues_origin_issue_id_issues_id_fk": { "name": "issues_origin_issue_id_issues_id_fk", "tableFrom": "issues", @@ -45342,9 +46955,17 @@ "name": "issues_visibility_check", "value": "\"issues\".\"visibility\" in ('open', 'private')" }, + "issues_scope_check": { + "name": "issues_scope_check", + "value": "\"issues\".\"scope\" in ('board', 'channel', 'agent', 'chat')" + }, "issues_conversation_identity_check": { "name": "issues_conversation_identity_check", "value": "(\n \"issues\".\"conversation_agent_id\" is null and \"issues\".\"conversation_user_id\" is null and \"issues\".\"conversation_state\" is null\n ) or (\n \"issues\".\"conversation_agent_id\" is not null and \"issues\".\"conversation_user_id\" is not null\n and \"issues\".\"assignee_agent_id\" = \"issues\".\"conversation_agent_id\" and \"issues\".\"assignee_agent_id\" is not null\n and \"issues\".\"assignee_user_id\" is null and \"issues\".\"conversation_state\" is not null\n and \"issues\".\"conversation_state\" in ('active', 'waiting')\n and \"issues\".\"status\" not in ('done', 'cancelled')\n )" + }, + "issues_conversation_channel_exclusion_check": { + "name": "issues_conversation_channel_exclusion_check", + "value": "(\"issues\".\"conversation_agent_id\" is null) or (\"issues\".\"channel_id\" is null)" } }, "isRLSEnabled": false @@ -72819,4 +74440,4 @@ "schemas": {}, "tables": {} } -} \ No newline at end of file +} diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index fcab0f0a492..1ccecebecff 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -3571,6 +3571,13 @@ "when": 1796075417353, "tag": "0511_simple_the_hunter", "breakpoints": true + }, + { + "idx": 512, + "version": "7", + "when": 1796072868844, + "tag": "0512_stormy_the_hood", + "breakpoints": true } ] -} \ No newline at end of file +} diff --git a/packages/db/src/schema/agent_api_keys.ts b/packages/db/src/schema/agent_api_keys.ts index 7966f55d9ca..7e26a95557f 100644 --- a/packages/db/src/schema/agent_api_keys.ts +++ b/packages/db/src/schema/agent_api_keys.ts @@ -13,6 +13,7 @@ export const agentApiKeys = pgTable( keyHash: text("key_hash").notNull(), responsibleUserId: text("responsible_user_id"), scopeConfig: jsonb("scope_config").$type(), + expiresAt: timestamp("expires_at", { withTimezone: true }), lastUsedAt: timestamp("last_used_at", { withTimezone: true }), revokedAt: timestamp("revoked_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), diff --git a/packages/db/src/schema/board_api_keys.ts b/packages/db/src/schema/board_api_keys.ts index e786760ff3f..db6f0117d13 100644 --- a/packages/db/src/schema/board_api_keys.ts +++ b/packages/db/src/schema/board_api_keys.ts @@ -1,11 +1,16 @@ -import { pgTable, uuid, text, timestamp, index, uniqueIndex } from "drizzle-orm/pg-core"; +import type { ClientScopes } from "@paperclipai/shared"; +import { pgTable, uuid, text, timestamp, index, jsonb, uniqueIndex } from "drizzle-orm/pg-core"; import { authUsers } from "./auth.js"; +import { companies } from "./companies.js"; export const boardApiKeys = pgTable( "board_api_keys", { id: uuid("id").primaryKey().defaultRandom(), userId: text("user_id").notNull().references(() => authUsers.id, { onDelete: "cascade" }), + companyId: uuid("company_id").references(() => companies.id, { onDelete: "cascade" }), + lockedProfile: text("locked_profile"), + scopes: jsonb("scopes").$type(), name: text("name").notNull(), keyHash: text("key_hash").notNull(), lastUsedAt: timestamp("last_used_at", { withTimezone: true }), @@ -16,5 +21,6 @@ export const boardApiKeys = pgTable( (table) => ({ keyHashIdx: uniqueIndex("board_api_keys_key_hash_idx").on(table.keyHash), userIdx: index("board_api_keys_user_idx").on(table.userId), + companyIdx: index("board_api_keys_company_idx").on(table.companyId).concurrently(), }), ); diff --git a/packages/db/src/schema/channels.ts b/packages/db/src/schema/channels.ts new file mode 100644 index 00000000000..ae462742749 --- /dev/null +++ b/packages/db/src/schema/channels.ts @@ -0,0 +1,106 @@ +import type { ChannelQueueConfig, ChannelVisibility } from "@paperclipai/shared"; +import { sql } from "drizzle-orm"; +import { + check, + index, + jsonb, + pgTable, + text, + timestamp, + uniqueIndex, + uuid, +} from "drizzle-orm/pg-core"; +import { agents } from "./agents.js"; +import { companies } from "./companies.js"; +import { projects } from "./projects.js"; + +export const channels = pgTable( + "channels", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id") + .notNull() + .references(() => companies.id, { onDelete: "cascade" }), + path: text("path").notNull(), + description: text("description"), + visibility: text("visibility") + .$type() + .notNull() + .default("open"), + defaultProjectId: uuid("default_project_id").references(() => projects.id, { + onDelete: "set null", + }), + queueConfig: jsonb("queue_config") + .$type() + .notNull() + .default({}), + createdByAgentId: uuid("created_by_agent_id").references(() => agents.id, { + onDelete: "set null", + }), + createdByUserId: text("created_by_user_id"), + createdByProfile: text("created_by_profile"), + archivedAt: timestamp("archived_at", { withTimezone: true }), + lastActivityAt: timestamp("last_activity_at", { withTimezone: true }) + .notNull() + .defaultNow(), + createdAt: timestamp("created_at", { withTimezone: true }) + .notNull() + .defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }) + .notNull() + .defaultNow(), + }, + (table) => ({ + visibilityCheck: check( + "channels_visibility_check", + sql`${table.visibility} in ('open', 'private')`, + ), + pathCheck: check( + "channels_path_check", + sql`${table.path} ~ '^[a-z0-9][a-z0-9_-]*(/[a-z0-9][a-z0-9_-]*)*$'`, + ), + companyPathUq: uniqueIndex("channels_company_path_uq").on( + table.companyId, + table.path, + ), + companyActivityIdx: index("channels_company_activity_idx").on( + table.companyId, + table.lastActivityAt, + ), + }), +); + +export const channelAccessMembers = pgTable( + "channel_access_members", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id") + .notNull() + .references(() => companies.id, { onDelete: "cascade" }), + channelId: uuid("channel_id") + .notNull() + .references(() => channels.id, { onDelete: "cascade" }), + subjectType: text("subject_type").notNull(), + subjectId: text("subject_id").notNull(), + createdAt: timestamp("created_at", { withTimezone: true }) + .notNull() + .defaultNow(), + }, + (table) => ({ + subjectTypeCheck: check( + "channel_access_members_subject_type_check", + sql`${table.subjectType} in ('user', 'agent')`, + ), + channelSubjectUq: uniqueIndex("channel_access_members_channel_subject_uq").on( + table.channelId, + table.subjectType, + table.subjectId, + ), + subjectLookupIdx: index("channel_access_members_subject_lookup_idx").on( + table.companyId, + table.subjectType, + table.subjectId, + table.channelId, + ), + }), +); diff --git a/packages/db/src/schema/cli_auth_challenges.ts b/packages/db/src/schema/cli_auth_challenges.ts index 5c6335cab67..3fd36378960 100644 --- a/packages/db/src/schema/cli_auth_challenges.ts +++ b/packages/db/src/schema/cli_auth_challenges.ts @@ -1,4 +1,5 @@ import { pgTable, uuid, text, timestamp, index } from "drizzle-orm/pg-core"; +import { agents } from "./agents.js"; import { authUsers } from "./auth.js"; import { companies } from "./companies.js"; import { boardApiKeys } from "./board_api_keys.js"; @@ -11,11 +12,15 @@ export const cliAuthChallenges = pgTable( command: text("command").notNull(), clientName: text("client_name"), requestedAccess: text("requested_access").notNull().default("board"), + challengeKind: text("challenge_kind").$type<"board" | "agent_key">().notNull().default("board"), + requestedAgentName: text("requested_agent_name"), + requestedAgentRole: text("requested_agent_role"), requestedCompanyId: uuid("requested_company_id").references(() => companies.id, { onDelete: "set null" }), pendingKeyHash: text("pending_key_hash").notNull(), pendingKeyName: text("pending_key_name").notNull(), approvedByUserId: text("approved_by_user_id").references(() => authUsers.id, { onDelete: "set null" }), boardApiKeyId: uuid("board_api_key_id").references(() => boardApiKeys.id, { onDelete: "set null" }), + approvedAgentId: uuid("approved_agent_id").references(() => agents.id, { onDelete: "set null" }), approvedAt: timestamp("approved_at", { withTimezone: true }), cancelledAt: timestamp("cancelled_at", { withTimezone: true }), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), diff --git a/packages/db/src/schema/companies.ts b/packages/db/src/schema/companies.ts index 7a32c596f7a..77105d823f7 100644 --- a/packages/db/src/schema/companies.ts +++ b/packages/db/src/schema/companies.ts @@ -1,5 +1,6 @@ -import type { InteractionResolverGovernance } from "@paperclipai/shared"; -import { numeric, pgTable, uuid, text, integer, timestamp, boolean, jsonb, uniqueIndex } from "drizzle-orm/pg-core"; +import type { AgentIdentityPolicy, InteractionResolverGovernance } from "@paperclipai/shared"; +import { sql } from "drizzle-orm"; +import { check, numeric, pgTable, uuid, text, integer, timestamp, boolean, jsonb, uniqueIndex } from "drizzle-orm/pg-core"; export const companies = pgTable( "companies", @@ -39,10 +40,15 @@ export const companies = pgTable( feedbackDataSharingConsentAt: timestamp("feedback_data_sharing_consent_at", { withTimezone: true }), feedbackDataSharingConsentByUserId: text("feedback_data_sharing_consent_by_user_id"), feedbackDataSharingTermsVersion: text("feedback_data_sharing_terms_version"), + agentIdentityPolicy: text("agent_identity_policy").$type(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ issuePrefixUniqueIdx: uniqueIndex("companies_issue_prefix_idx").on(table.issuePrefix), + agentIdentityPolicyCheck: check( + "companies_agent_identity_policy_check", + sql`${table.agentIdentityPolicy} is null or ${table.agentIdentityPolicy} in ('open_local_profiles', 'delegated_profiles', 'strict_agent_keys')`, + ), }), ); diff --git a/packages/db/src/schema/company_schemas.ts b/packages/db/src/schema/company_schemas.ts new file mode 100644 index 00000000000..31d55af5cdd --- /dev/null +++ b/packages/db/src/schema/company_schemas.ts @@ -0,0 +1,46 @@ +import { sql } from "drizzle-orm"; +import { + check, + integer, + jsonb, + pgTable, + text, + timestamp, + uniqueIndex, + uuid, +} from "drizzle-orm/pg-core"; +import { agents } from "./agents.js"; +import { companies } from "./companies.js"; + +export const companySchemas = pgTable( + "company_schemas", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id") + .notNull() + .references(() => companies.id, { onDelete: "cascade" }), + name: text("name").notNull(), + version: integer("version").notNull(), + description: text("description"), + jsonSchema: jsonb("json_schema") + .$type>() + .notNull(), + createdByUserId: text("created_by_user_id"), + createdByAgentId: uuid("created_by_agent_id").references(() => agents.id, { + onDelete: "set null", + }), + createdByProfile: text("created_by_profile"), + createdAt: timestamp("created_at", { withTimezone: true }) + .notNull() + .defaultNow(), + }, + (table) => ({ + versionCheck: check( + "company_schemas_version_check", + sql`${table.version} >= 1`, + ), + companyNameVersionUq: uniqueIndex( + "company_schemas_company_name_version_uq", + ).on(table.companyId, table.name, table.version), + }), +); diff --git a/packages/db/src/schema/headless_board.ts b/packages/db/src/schema/headless_board.ts new file mode 100644 index 00000000000..4e7caea62b6 --- /dev/null +++ b/packages/db/src/schema/headless_board.ts @@ -0,0 +1,150 @@ +import type { BoardEventType, SchemaBlock } from "@paperclipai/shared"; +import { sql } from "drizzle-orm"; +import { + bigint, + bigserial, + boolean, + check, + index, + integer, + jsonb, + pgTable, + text, + timestamp, + uniqueIndex, + uuid, +} from "drizzle-orm/pg-core"; +import { agents } from "./agents.js"; +import { channels } from "./channels.js"; +import { companies } from "./companies.js"; +import { issues } from "./issues.js"; + +export const boardEvents = pgTable( + "board_events", + { + seq: bigserial("seq", { mode: "number" }).primaryKey(), + companyId: uuid("company_id") + .notNull() + .references(() => companies.id, { onDelete: "cascade" }), + eventType: text("event_type").$type().notNull(), + channelId: uuid("channel_id").references(() => channels.id, { + onDelete: "set null", + }), + channelPath: text("channel_path"), + issueId: uuid("issue_id").references(() => issues.id, { + onDelete: "set null", + }), + identifier: text("identifier"), + actorType: text("actor_type") + .$type<"user" | "agent" | "system">() + .notNull() + .default("system"), + actorId: text("actor_id"), + actorName: text("actor_name"), + actorProfile: text("actor_profile"), + payload: jsonb("payload") + .$type>() + .notNull() + .default({}), + createdAt: timestamp("created_at", { withTimezone: true }) + .notNull() + .defaultNow(), + }, + (table) => ({ + companySeqIdx: index("board_events_company_seq_idx").on( + table.companyId, + table.seq, + ), + companyChannelSeqIdx: index("board_events_company_channel_seq_idx").on( + table.companyId, + table.channelPath, + table.seq, + ), + companyIssueSeqIdx: index("board_events_company_issue_seq_idx").on( + table.companyId, + table.issueId, + table.seq, + ), + }), +); + +export const scheduledBoardPosts = pgTable( + "scheduled_board_posts", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id") + .notNull() + .references(() => companies.id, { onDelete: "cascade" }), + target: text("target").notNull(), + channelId: uuid("channel_id").references(() => channels.id, { + onDelete: "cascade", + }), + issueId: uuid("issue_id").references(() => issues.id, { + onDelete: "cascade", + }), + message: text("message").notNull(), + postOnly: boolean("post_only").notNull().default(false), + kvLabels: jsonb("kv_labels") + .$type>() + .notNull() + .default({}), + schemaBlocks: jsonb("schema_blocks").$type().notNull().default([]), + intervalMs: bigint("interval_ms", { mode: "number" }), + untilAt: timestamp("until_at", { withTimezone: true }), + nextRunAt: timestamp("next_run_at", { withTimezone: true }).notNull(), + lastRunAt: timestamp("last_run_at", { withTimezone: true }), + runCount: integer("run_count").notNull().default(0), + status: text("status") + .$type<"scheduled" | "cancelled" | "completed">() + .notNull() + .default("scheduled"), + authorUserId: text("author_user_id"), + authorAgentId: uuid("author_agent_id").references(() => agents.id, { + onDelete: "set null", + }), + authorProfile: text("author_profile"), + createdAt: timestamp("created_at", { withTimezone: true }) + .notNull() + .defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }) + .notNull() + .defaultNow(), + }, + (table) => ({ + statusCheck: check( + "scheduled_board_posts_status_check", + sql`${table.status} in ('scheduled', 'cancelled', 'completed')`, + ), + dueIdx: index("scheduled_board_posts_due_idx") + .on(table.nextRunAt) + .where(sql`${table.status} = 'scheduled'`), + companyIdx: index("scheduled_board_posts_company_idx").on( + table.companyId, + table.status, + table.nextRunAt, + ), + }), +); + +export const issueBatchIdempotencyKeys = pgTable( + "issue_batch_idempotency_keys", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id") + .notNull() + .references(() => companies.id, { onDelete: "cascade" }), + idempotencyKey: text("idempotency_key").notNull(), + requestHash: text("request_hash").notNull(), + responsePayload: jsonb("response_payload") + .$type>() + .notNull(), + createdAt: timestamp("created_at", { withTimezone: true }) + .notNull() + .defaultNow(), + }, + (table) => ({ + companyKeyUq: uniqueIndex( + "issue_batch_idempotency_keys_company_key_uq", + ).on(table.companyId, table.idempotencyKey), + }), +); diff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.ts index caad881194d..4f5288a6def 100644 --- a/packages/db/src/schema/index.ts +++ b/packages/db/src/schema/index.ts @@ -312,3 +312,6 @@ export { type AgentSetupProgressItemStatus, type AgentSetupProgressItemRecord, } from "./agent_setup_progress.js"; +export { channels, channelAccessMembers } from "./channels.js"; +export { companySchemas } from "./company_schemas.js"; +export { boardEvents, scheduledBoardPosts, issueBatchIdempotencyKeys } from "./headless_board.js"; diff --git a/packages/db/src/schema/issue_comments.ts b/packages/db/src/schema/issue_comments.ts index f63c7c8c214..67cfa9dee0c 100644 --- a/packages/db/src/schema/issue_comments.ts +++ b/packages/db/src/schema/issue_comments.ts @@ -3,10 +3,11 @@ import type { IssueCommentDerivedAuthorSource, IssueCommentMetadata, IssueCommentPresentation, + SchemaBlock, SourceTrustMetadata, } from "@paperclipai/shared"; import { sql } from "drizzle-orm"; -import { pgTable, uuid, text, timestamp, index, jsonb, unique, integer } from "drizzle-orm/pg-core"; +import { pgTable, uuid, text, timestamp, index, jsonb, unique, integer, boolean } from "drizzle-orm/pg-core"; import { companies } from "./companies.js"; import { issues } from "./issues.js"; import { agents } from "./agents.js"; @@ -43,6 +44,10 @@ export const issueComments = pgTable( deletedByAgentId: uuid("deleted_by_agent_id").references(() => agents.id, { onDelete: "set null" }), deletedByUserId: text("deleted_by_user_id"), deletedByRunId: uuid("deleted_by_run_id").references(() => heartbeatRuns.id, { onDelete: "set null" }), + actorProfile: text("actor_profile"), + kvLabels: jsonb("kv_labels").$type>().notNull().default({}), + schemaBlocks: jsonb("schema_blocks").$type().notNull().default([]), + noSync: boolean("no_sync").notNull().default(false), sourceTrust: jsonb("source_trust").$type(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), diff --git a/packages/db/src/schema/issues.ts b/packages/db/src/schema/issues.ts index beae1cf3640..db60cc681ec 100644 --- a/packages/db/src/schema/issues.ts +++ b/packages/db/src/schema/issues.ts @@ -21,7 +21,8 @@ import { companies } from "./companies.js"; import { heartbeatRuns } from "./heartbeat_runs.js"; import { projectWorkspaces } from "./project_workspaces.js"; import { executionWorkspaces } from "./execution_workspaces.js"; -import type { IssueReviewPolicy, IssueScope, IssueUnblockDescriptor, SourceTrustMetadata, TaskWorkspaceIntent, TaskWorkspacePendingSelection } from "@paperclipai/shared"; +import { channels } from "./channels.js"; +import type { IssueReviewPolicy, IssueScope, IssueUnblockDescriptor, SchemaBlock, SourceTrustMetadata, TaskWorkspaceIntent, TaskWorkspacePendingSelection } from "@paperclipai/shared"; export const issues = pgTable( "issues", @@ -35,6 +36,7 @@ export const issues = pgTable( conversationSessionGeneration: integer("conversation_session_generation").notNull().default(0), conversationBoundaryCommentId: uuid("conversation_boundary_comment_id"), projectId: uuid("project_id").references(() => projects.id), + channelId: uuid("channel_id").references(() => channels.id, { onDelete: "set null" }), projectWorkspaceId: uuid("project_workspace_id").references(() => projectWorkspaces.id, { onDelete: "set null" }), goalId: uuid("goal_id").references(() => goals.id), parentId: uuid("parent_id").references((): AnyPgColumn => issues.id), @@ -60,7 +62,19 @@ export const issues = pgTable( executionLockedAt: timestamp("execution_locked_at", { withTimezone: true }), createdByAgentId: uuid("created_by_agent_id").references(() => agents.id), createdByUserId: text("created_by_user_id"), + createdByProfile: text("created_by_profile"), responsibleUserId: text("responsible_user_id"), + kvLabels: jsonb("kv_labels").$type>().notNull().default({}), + schemaBlocks: jsonb("schema_blocks").$type().notNull().default([]), + resultSchemaRef: text("result_schema_ref"), + claimEpoch: bigint("claim_epoch", { mode: "number" }).notNull().default(0), + claimTokenHash: text("claim_token_hash"), + claimHolderAgentId: uuid("claim_holder_agent_id").references(() => agents.id, { onDelete: "set null" }), + claimHolderUserId: text("claim_holder_user_id"), + claimHolderProfile: text("claim_holder_profile"), + claimLeasedAt: timestamp("claim_leased_at", { withTimezone: true }), + claimLeaseExpiresAt: timestamp("claim_lease_expires_at", { withTimezone: true }), + claimAttemptCount: integer("claim_attempt_count").notNull().default(0), issueNumber: integer("issue_number"), identifier: text("identifier"), originKind: text("origin_kind").notNull().default("manual"), @@ -225,5 +239,33 @@ export const issues = pgTable( onboardingFirstTaskIdx: uniqueIndex("issues_onboarding_first_task_uq") .on(table.companyId) .where(sql`${table.originKind} = 'onboarding_first_task'`), + conversationChannelExclusionCheck: check( + "issues_conversation_channel_exclusion_check", + sql`(${table.conversationAgentId} is null) or (${table.channelId} is null)`, + ), + channelCreatedIdx: index("issues_company_channel_created_idx") + .on(table.companyId, table.channelId, table.createdAt) + .concurrently(), + kvLabelsGinIdx: index("issues_kv_labels_gin_idx") + .using("gin", table.kvLabels) + .concurrently(), + readyPoolQueueIdx: index("issues_ready_pool_queue_idx") + .on(table.companyId, table.channelId, table.priority, table.createdAt) + .where( + sql`${table.status} = 'todo' + and ${table.assigneeAgentId} is null + and ${table.assigneeUserId} is null + and ${table.hiddenAt} is null + and ${table.conversationAgentId} is null`, + ) + .concurrently(), + activeClaimLeaseDueIdx: index("issues_active_claim_lease_due_idx") + .on(table.claimLeaseExpiresAt) + .where( + sql`${table.status} = 'in_progress' + and ${table.claimLeaseExpiresAt} is not null + and ${table.claimTokenHash} is not null`, + ) + .concurrently(), }), ); diff --git a/packages/shared/package.json b/packages/shared/package.json index 6417ef8baef..0d417d9a3db 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -16,6 +16,8 @@ "exports": { ".": "./src/index.ts", "./telemetry": "./src/telemetry/index.ts", + "./sdk": "./src/sdk/index.ts", + "./headless": "./src/headless/index.ts", "./*": "./src/*.ts" }, "publishConfig": { @@ -29,6 +31,14 @@ "types": "./dist/telemetry/index.d.ts", "import": "./dist/telemetry/index.js" }, + "./sdk": { + "types": "./dist/sdk/index.d.ts", + "import": "./dist/sdk/index.js" + }, + "./headless": { + "types": "./dist/headless/index.d.ts", + "import": "./dist/headless/index.js" + }, "./*": { "types": "./dist/*.d.ts", "import": "./dist/*.js" diff --git a/packages/shared/src/headless/channels.ts b/packages/shared/src/headless/channels.ts new file mode 100644 index 00000000000..9db0d9cd0fe --- /dev/null +++ b/packages/shared/src/headless/channels.ts @@ -0,0 +1,114 @@ +import { z } from "zod"; +import { ISSUE_PRIORITIES } from "../constants.js"; +import { writableKvLabelsRecordSchema } from "./labels.js"; +import { + CHANNEL_PATH_REGEX, + normalizeChannelPath, + splitMessageIntoTitleAndDescription, + type NormalizedChannelPath, +} from "./pure.js"; +import { SCHEMA_REF_REGEX, schemaBlockSchema } from "./schemas.js"; + +export { + CHANNEL_PATH_REGEX, + normalizeChannelPath, + splitMessageIntoTitleAndDescription, + type NormalizedChannelPath, +}; + +export const CHANNEL_VISIBILITIES = ["open", "private"] as const; +export type ChannelVisibility = (typeof CHANNEL_VISIBILITIES)[number]; + +export const CHANNEL_ORDERINGS = ["priority_fifo", "strict_fifo"] as const; +export type ChannelOrdering = (typeof CHANNEL_ORDERINGS)[number]; + +export const channelManagedPoolSchema = z + .object({ + agentId: z.string().uuid(), + maxConcurrency: z.number().int().min(1).max(100), + }) + .strict(); + +export const channelQueueConfigSchema = z + .object({ + defaultLeaseSec: z.number().int().min(30).max(3600).optional(), + maxLeaseSec: z.number().int().min(30).max(86400).optional(), + maxClaimAttempts: z.number().int().min(1).max(100).optional(), + ordering: z.enum(CHANNEL_ORDERINGS).optional(), + allowedRoles: z.array(z.string().min(1)).optional(), + allowedAgentIds: z.array(z.string().uuid()).optional(), + managedPool: channelManagedPoolSchema.optional(), + }) + .strict(); + +export type ChannelQueueConfig = z.infer; + +export const exactChannelPathSchema = z + .string() + .transform((value, ctx) => { + try { + return normalizeChannelPath(value, { allowSubtreePrefix: false }).path; + } catch (err) { + ctx.addIssue({ + code: "custom", + message: err instanceof Error ? err.message : "Invalid channel path", + }); + return z.NEVER; + } + }); + +export interface ChannelView { + id: string; + companyId: string; + path: string; + description: string | null; + visibility: ChannelVisibility; + defaultProjectId: string | null; + queueConfig: ChannelQueueConfig; + threadCount: number; + openTaskCount: number; + readyTaskCount: number; + lastActivityAt: string; + createdAt: string; + updatedAt: string; +} + +export const createChannelInputSchema = z + .object({ + path: exactChannelPathSchema, + description: z.string().max(1000).nullable().optional(), + visibility: z.enum(CHANNEL_VISIBILITIES).optional(), + defaultProjectId: z.string().min(1).nullable().optional(), + queueConfig: channelQueueConfigSchema.optional(), + }) + .strict(); + +export type CreateChannelInput = z.input; + +export const channelPostInputSchema = z + .object({ + channel: exactChannelPathSchema, + title: z.string().max(240).optional(), + text: z.string().optional(), + description: z.string().nullable().optional(), + projectId: z.string().min(1).nullable().optional(), + board: z.boolean().optional(), + priority: z.enum(ISSUE_PRIORITIES).optional(), + labels: writableKvLabelsRecordSchema.optional(), + tagLabels: z.array(z.string().min(1).max(64)).optional(), + blocks: z.array(schemaBlockSchema).optional(), + schema: z + .object({ + ref: z.string().refine((v) => SCHEMA_REF_REGEX.test(v.trim()), { + message: "Invalid schema ref", + }), + data: z.record(z.string(), z.unknown()), + }) + .strict() + .optional(), + idempotencyKey: z.string().min(1).max(255).optional(), + sourceTrust: z.string().min(1).max(64).optional(), + }) + .strict(); + +export type ChannelPostInput = z.input; diff --git a/packages/shared/src/headless/events.ts b/packages/shared/src/headless/events.ts new file mode 100644 index 00000000000..71ece3f5df8 --- /dev/null +++ b/packages/shared/src/headless/events.ts @@ -0,0 +1,48 @@ +import { z } from "zod"; +import { formatEventCursor, parseEventCursor } from "./pure.js"; + +export { formatEventCursor, parseEventCursor }; + +export const BOARD_EVENT_TYPES = [ + "thread.posted", + "comment.posted", + "task.created", + "task.ready", + "task.claimed", + "task.lease_renewed", + "task.lease_released", + "task.lease_expired_requeued", + "task.lease_poison_blocked", + "task.completed", + "task.failed", + "task.blocked", + "task.unblocked", + "labels.changed", + "interaction.created", + "interaction.resolved", + "approval.resolved", +] as const; + +export type BoardEventType = (typeof BOARD_EVENT_TYPES)[number]; + +export const boardEventTypeSchema = z.enum(BOARD_EVENT_TYPES); + +export interface BoardEventActor { + type: "user" | "agent" | "system"; + id?: string | null; + name?: string | null; + profile?: string | null; +} + +export interface BoardEventView { + cursor: string; + seq: number; + type: BoardEventType; + companyId: string; + channel: string | null; + issueId: string | null; + identifier: string | null; + actor: BoardEventActor; + payload: Record; + createdAt: string; +} diff --git a/packages/shared/src/headless/headless.test.ts b/packages/shared/src/headless/headless.test.ts new file mode 100644 index 00000000000..616c41aff5d --- /dev/null +++ b/packages/shared/src/headless/headless.test.ts @@ -0,0 +1,323 @@ +import { describe, expect, it } from "vitest"; +import { + AGENT_IDENTITY_POLICIES, + applyKvLabelMutation, + assertSafeRegexPattern, + BOARD_EVENT_TYPES, + BUILT_IN_COMPANY_SCHEMAS, + canonicalizeJsonSchema, + CHANNEL_PATH_REGEX, + formatEventCursor, + isReservedKvLabelKey, + KV_LABEL_KEY_REGEX, + KvLabelMutationSchema, + matchesLabelFilter, + normalizeChannelPath, + OneLineAskSchema, + OneLineConfirmSchema, + parseDurationMs, + parseEventCursor, + parseLabelFilterExpr, + parseSchemaRef, + SCHEMA_REF_REGEX, + SchedulePostSchema, + splitMessageIntoTitleAndDescription, + TaskClaimRequestSchema, + TaskCompleteSchema, + TaskFailSchema, + TaskRenewSchema, + validateAgainstJsonSchema, + validateAndSortBatchPlan, +} from "./index.js"; + +describe("headless contracts", () => { + it("defines agent identity policies", () => { + expect(AGENT_IDENTITY_POLICIES).toEqual([ + "open_local_profiles", + "delegated_profiles", + "strict_agent_keys", + ]); + }); + + it("normalizes exact and subtree channel paths", () => { + expect(CHANNEL_PATH_REGEX.test("build/auth")).toBe(true); + expect(CHANNEL_PATH_REGEX.test("Build/Auth")).toBe(false); + + expect(normalizeChannelPath("build/auth")).toEqual({ + path: "build/auth", + isSubtreePrefix: false, + }); + expect(normalizeChannelPath(" #Build/Auth/ ")).toEqual({ + path: "build/auth", + isSubtreePrefix: true, + }); + expect(() => + normalizeChannelPath("build/", { allowSubtreePrefix: false }), + ).toThrow(/trailing '\/'/); + expect(() => normalizeChannelPath("build//auth")).toThrow(); + expect(() => normalizeChannelPath("-bad")).toThrow(); + }); + + it("parses and validates kv_labels and CAS mutations", () => { + expect(KV_LABEL_KEY_REGEX.test("paperclip.pr")).toBe(true); + expect(isReservedKvLabelKey("paperclip.pr")).toBe(true); + expect(isReservedKvLabelKey("stage")).toBe(false); + + expect(parseLabelFilterExpr("pr")).toEqual({ kind: "exists", key: "pr" }); + expect(parseLabelFilterExpr("stage=review")).toEqual({ + kind: "equals", + key: "stage", + value: "review", + }); + expect(parseLabelFilterExpr("stage=open|review")).toEqual({ + kind: "in", + key: "stage", + values: ["open", "review"], + }); + expect(() => parseLabelFilterExpr("BadKey=1")).toThrow(); + expect(() => parseLabelFilterExpr("stage=")).toThrow(); + + expect(matchesLabelFilter({ stage: "review" }, [], "stage=open|review")).toBe(true); + expect(matchesLabelFilter({}, ["bug"], "bug")).toBe(true); + + expect( + KvLabelMutationSchema.safeParse({ set: { "paperclip.pr": "1" } }).success, + ).toBe(false); + + const casOk = applyKvLabelMutation( + { triage: "new" }, + { set: { triage: "investigating", reviewer: "fx" }, if: { triage: "new", reviewer: null } }, + ); + expect(casOk).toEqual({ + ok: true, + labels: { triage: "investigating", reviewer: "fx" }, + }); + + const casConflict = applyKvLabelMutation( + { triage: "done", reviewer: "alice" }, + { set: { triage: "investigating" }, if: { triage: "new", reviewer: null } }, + ); + expect(casConflict).toEqual({ + ok: false, + error: "label_conflict", + conflictingKeys: ["triage", "reviewer"], + }); + }); + + it("validates built-in schemas and lightweight JSON Schema subset", () => { + expect(SCHEMA_REF_REGEX.test("security-finding@1")).toBe(true); + expect(parseSchemaRef("security-finding@2")).toEqual({ + name: "security-finding", + version: 2, + ref: "security-finding@2", + }); + expect(() => parseSchemaRef("bad@0")).toThrow(); + + expect(BUILT_IN_COMPANY_SCHEMAS.map((s) => s.ref)).toEqual([ + "git-commit@1", + "pull-request@1", + "test-report@1", + "finding@1", + ]); + + const findingSchema = BUILT_IN_COMPANY_SCHEMAS.find( + (s) => s.ref === "finding@1", + )!.jsonSchema; + expect( + validateAgainstJsonSchema(findingSchema, { + severity: "high", + title: "Unescaped SQL", + line: 42, + }), + ).toEqual({ valid: true, errors: [] }); + + const invalidFinding = validateAgainstJsonSchema(findingSchema, { + severity: "extreme", + title: "", + line: 0, + }); + expect(invalidFinding.valid).toBe(false); + expect(invalidFinding.errors.length).toBeGreaterThanOrEqual(3); + + const strictSchema = { + type: "object", + required: ["items"], + additionalProperties: false, + properties: { + items: { + type: "array", + items: { type: "string", minLength: 2, maxLength: 5, pattern: "^[a-z]+$" }, + }, + score: { type: "number", minimum: 0, maximum: 10 }, + }, + }; + expect( + validateAgainstJsonSchema(strictSchema, { + items: ["ok", "valid"], + score: 5, + }).valid, + ).toBe(true); + expect( + validateAgainstJsonSchema(strictSchema, { + items: ["a", "123456"], + score: 11, + extra: true, + }).errors.length, + ).toBe(5); + + expect(canonicalizeJsonSchema({ b: 1, a: { d: 2, c: 3 } })).toBe( + canonicalizeJsonSchema({ a: { c: 3, d: 2 }, b: 1 }), + ); + }); + + it("topologically sorts batch plans, rejects cycles/duplicates/unknown keys, and resolves projectId", () => { + const validPlan = validateAndSortBatchPlan({ + channel: "build/checkout", + projectId: "web-app", + idempotencyKey: "plan-1", + tasks: [ + { + key: "review", + projectId: null, + title: "Review changes", + needs: ["patch", { key: "audit-api" }, "PAP-10"], + resultSchema: "finding@1", + }, + { + key: "patch", + title: "Patch auth", + labels: { role: "worker" }, + }, + { + key: "audit-api", + projectId: "api-server", + text: "# Audit API\nCheck all callers", + }, + ], + }); + + expect(validPlan.ok).toBe(true); + if (validPlan.ok) { + expect(validPlan.tasks.map((t) => t.key)).toEqual([ + "patch", + "audit-api", + "review", + ]); + expect(validPlan.tasks[0]!.projectId).toBe("web-app"); + expect(validPlan.tasks[1]!.projectId).toBe("api-server"); + expect(validPlan.tasks[1]!.title).toBe("Audit API"); + expect(validPlan.tasks[1]!.description).toBe("# Audit API\nCheck all callers"); + expect(validPlan.tasks[2]!.projectId).toBeNull(); + expect(validPlan.tasks[2]!.localNeeds).toEqual(["patch", "audit-api"]); + expect(validPlan.tasks[2]!.externalNeeds).toEqual(["PAP-10"]); + } + + const dup = validateAndSortBatchPlan({ + tasks: [ + { key: "a", title: "One" }, + { key: "a", title: "Two" }, + ], + }); + expect(dup.ok).toBe(false); + if (!dup.ok) { + expect(dup.code).toBe("duplicate_task_key"); + expect(dup.duplicateKeys).toEqual(["a"]); + } + + const unknown = validateAndSortBatchPlan({ + tasks: [{ key: "a", title: "One", needs: ["missing-key"] }], + }); + expect(unknown.ok).toBe(false); + if (!unknown.ok) { + expect(unknown.code).toBe("unknown_dependency_key"); + } + + const cycle = validateAndSortBatchPlan({ + tasks: [ + { key: "a", title: "A", needs: ["b"] }, + { key: "b", title: "B", needs: ["a"] }, + { key: "c", title: "C" }, + ], + }); + expect(cycle.ok).toBe(false); + if (!cycle.ok) { + expect(cycle.code).toBe("cyclic_dependencies"); + expect(cycle.cycleKeys).toEqual(["a", "b"]); + } + }); + + it("splits single-text messages into title and description per Plan 02 §5.2", () => { + expect(splitMessageIntoTitleAndDescription("web@a1b2c3 is live")).toEqual({ + title: "web@a1b2c3 is live", + description: null, + }); + expect(splitMessageIntoTitleAndDescription("# Deploy summary")).toEqual({ + title: "Deploy summary", + description: null, + }); + expect( + splitMessageIntoTitleAndDescription("## Incident\nDetails on line 2"), + ).toEqual({ + title: "Incident", + description: "## Incident\nDetails on line 2", + }); + + const longLine = "a ".repeat(80).trim(); + const longRes = splitMessageIntoTitleAndDescription(longLine); + expect(longRes.title.length).toBeLessThanOrEqual(120); + expect(longRes.title.endsWith("…")).toBe(true); + expect(longRes.description).toBe(longLine); + + expect( + splitMessageIntoTitleAndDescription(" ", "[security-finding@1]"), + ).toEqual({ + title: "[security-finding@1]", + description: null, + }); + }); + + it("parses durations, event cursors, and lease/interaction schemas", () => { + expect(parseDurationMs("30s")).toBe(30_000); + expect(parseDurationMs("5m")).toBe(300_000); + expect(parseDurationMs("2h")).toBe(7_200_000); + expect(parseDurationMs("7d")).toBe(604_800_000); + expect(parseDurationMs(1250)).toBe(1250); + expect(() => parseDurationMs("forever")).toThrow(); + + expect(formatEventCursor(42)).toBe("evt_42"); + expect(parseEventCursor("evt_42")).toBe(42); + expect(parseEventCursor("bad")).toBeNull(); + expect(BOARD_EVENT_TYPES).toContain("task.completed"); + expect(BOARD_EVENT_TYPES).toContain("interaction.resolved"); + + expect(TaskClaimRequestSchema.safeParse({ ready: true, lease: "5m" }).success).toBe(true); + expect(TaskRenewSchema.safeParse({ lease: "5m" }).success).toBe(true); + expect(TaskCompleteSchema.safeParse({ data: { passed: true } }).success).toBe(true); + expect(TaskFailSchema.safeParse({ reason: "OOM", requeue: true }).success).toBe(true); + expect(OneLineAskSchema.safeParse({ question: "Proceed?", choices: ["yes", "no"] }).success).toBe(true); + expect(OneLineConfirmSchema.safeParse({ prompt: "Drop column?", humanOnly: true }).success).toBe(true); + expect(SchedulePostSchema.safeParse({ target: "deploys", message: "Ping", in: "5m" }).success).toBe(true); + expect(SchedulePostSchema.safeParse({ target: "deploys", message: "Missing timing" }).success).toBe(false); + }); + + it("rejects catastrophic or overly complex regex patterns in JSON schemas", () => { + expect(() => assertSafeRegexPattern("^[a-z0-9_-]+$")).not.toThrow(); + expect(() => assertSafeRegexPattern("^(foo|bar)?$")).not.toThrow(); + expect(() => assertSafeRegexPattern("^(?:ab)+$")).not.toThrow(); + expect(() => assertSafeRegexPattern("^(red|blue)+$")).not.toThrow(); + expect(() => assertSafeRegexPattern("(?foo|bar)*")).not.toThrow(); + expect(() => assertSafeRegexPattern("^(a+)+$")).toThrow(); + expect(() => assertSafeRegexPattern("^(a.|.a)+$")).toThrow(); + expect(() => assertSafeRegexPattern("(a|a)+")).toThrow(); + expect(() => assertSafeRegexPattern("(ab|ac)+")).toThrow(); + expect(() => assertSafeRegexPattern("(|a)+")).toThrow(); + expect(() => assertSafeRegexPattern("(a)\\1+")).toThrow(); + expect(() => assertSafeRegexPattern("(?=a)a")).toThrow(); + + const validation = validateAgainstJsonSchema( + { type: "string", pattern: "^(a+)+$" }, + "aaaaaaaaaaaaaaaaaaaa!", + ); + expect(validation.valid).toBe(false); + }); +}); diff --git a/packages/shared/src/headless/identity.ts b/packages/shared/src/headless/identity.ts new file mode 100644 index 00000000000..aef0e7ee58f --- /dev/null +++ b/packages/shared/src/headless/identity.ts @@ -0,0 +1,46 @@ +import { z } from "zod"; +import { ISSUE_SCOPES, type IssueScope } from "../constants.js"; + +export { ISSUE_SCOPES, type IssueScope }; + +export const AGENT_IDENTITY_POLICIES = [ + "open_local_profiles", + "delegated_profiles", + "strict_agent_keys", +] as const; + +export type AgentIdentityPolicy = (typeof AGENT_IDENTITY_POLICIES)[number]; + +export const agentIdentityPolicySchema = z.enum(AGENT_IDENTITY_POLICIES); + +export const issueScopeSchema = z.enum(ISSUE_SCOPES); + +export const clientScopesSchema = z + .object({ + channels: z.array(z.string().min(1)).optional(), + actions: z.array(z.string().min(1)).optional(), + }) + .catchall(z.unknown()); + +export type ClientScopes = z.infer; + +export interface WhoAmIView { + apiBase: string; + companyId: string; + companyPrefix: string; + companyName: string; + principalType: "local_trusted" | "user" | "agent"; + userId: string | null; + agentId: string | null; + agentName: string | null; + actorProfile: string | null; + agentIdentityPolicy: AgentIdentityPolicy; + scopes: ClientScopes | null; +} + +export interface CompanyResolutionView { + id: string; + name: string; + issuePrefix: string; + agentIdentityPolicy: AgentIdentityPolicy; +} diff --git a/packages/shared/src/headless/index.ts b/packages/shared/src/headless/index.ts new file mode 100644 index 00000000000..011e7b457f6 --- /dev/null +++ b/packages/shared/src/headless/index.ts @@ -0,0 +1,7 @@ +export * from "./identity.js"; +export * from "./channels.js"; +export * from "./labels.js"; +export * from "./schemas.js"; +export * from "./plans.js"; +export * from "./events.js"; +export * from "./leases.js"; diff --git a/packages/shared/src/headless/labels.ts b/packages/shared/src/headless/labels.ts new file mode 100644 index 00000000000..18cb9acceeb --- /dev/null +++ b/packages/shared/src/headless/labels.ts @@ -0,0 +1,183 @@ +import { z } from "zod"; + +export const KV_LABEL_KEY_REGEX = /^[a-z0-9][a-z0-9_.-]{0,63}$/; +export const RESERVED_KV_LABEL_PREFIX = "paperclip."; +export const KV_LABEL_VALUE_MAX_BYTES = 256; + +const CONTROL_CHAR_REGEX = /[\x00-\x1f\x7f]/; +const utf8Encoder = new TextEncoder(); + +export function isReservedKvLabelKey(key: string): boolean { + return key.startsWith(RESERVED_KV_LABEL_PREFIX); +} + +export function isValidKvLabelKey(key: string): boolean { + return KV_LABEL_KEY_REGEX.test(key); +} + +export function isValidKvLabelValue(value: string): boolean { + if (typeof value !== "string" || value.length === 0) return false; + if (CONTROL_CHAR_REGEX.test(value)) return false; + return utf8Encoder.encode(value).length <= KV_LABEL_VALUE_MAX_BYTES; +} + +export const kvLabelKeySchema = z + .string() + .refine(isValidKvLabelKey, { + message: "Label key must match ^[a-z0-9][a-z0-9_.-]{0,63}$", + }); + +export const writableKvLabelKeySchema = kvLabelKeySchema.refine( + (key) => !isReservedKvLabelKey(key), + { + message: "Label keys starting with 'paperclip.' are reserved", + }, +); + +export const kvLabelValueSchema = z + .string() + .refine((val) => !CONTROL_CHAR_REGEX.test(val), { + message: "Label value must not contain control characters", + }) + .refine((val) => val.length > 0, { + message: "Label value must not be empty", + }) + .refine((val) => utf8Encoder.encode(val).length <= KV_LABEL_VALUE_MAX_BYTES, { + message: `Label value must be at most ${KV_LABEL_VALUE_MAX_BYTES} UTF-8 bytes`, + }); + +export const writableKvLabelsRecordSchema = z.record( + writableKvLabelKeySchema, + kvLabelValueSchema, +); + +export const KvLabelMutationSchema = z + .object({ + set: writableKvLabelsRecordSchema.optional(), + unset: z.array(writableKvLabelKeySchema).optional(), + if: z.record(kvLabelKeySchema, kvLabelValueSchema.nullable()).optional(), + }) + .strict(); + +export type KvLabelMutation = z.infer; + +export type LabelFilterExpr = + | { kind: "exists"; key: string } + | { kind: "equals"; key: string; value: string } + | { kind: "in"; key: string; values: string[] }; + +export function parseLabelFilterExpr(expr: string): LabelFilterExpr { + const trimmed = expr.trim(); + if (!trimmed) { + throw new Error("Label filter expression must not be empty"); + } + + const eqIdx = trimmed.indexOf("="); + if (eqIdx === -1) { + if (!isValidKvLabelKey(trimmed)) { + throw new Error( + `Invalid label key "${trimmed}": must match ${KV_LABEL_KEY_REGEX.source}`, + ); + } + return { kind: "exists", key: trimmed }; + } + + const key = trimmed.slice(0, eqIdx).trim(); + const rhs = trimmed.slice(eqIdx + 1).trim(); + + if (!isValidKvLabelKey(key)) { + throw new Error( + `Invalid label key "${key}": must match ${KV_LABEL_KEY_REGEX.source}`, + ); + } + if (!rhs) { + throw new Error(`Invalid label filter "${expr}": missing value after '='`); + } + + if (rhs.includes("|")) { + const rawParts = rhs.split("|").map((part) => part.trim()); + if (rawParts.some((part) => part.length === 0)) { + throw new Error( + `Invalid label filter "${expr}": empty option in '|' list`, + ); + } + const deduped: string[] = []; + for (const part of rawParts) { + if (!isValidKvLabelValue(part)) { + throw new Error(`Invalid label value "${part}" in filter "${expr}"`); + } + if (!deduped.includes(part)) { + deduped.push(part); + } + } + if (deduped.length === 1) { + return { kind: "equals", key, value: deduped[0]! }; + } + return { kind: "in", key, values: deduped }; + } + + if (!isValidKvLabelValue(rhs)) { + throw new Error(`Invalid label value "${rhs}" in filter "${expr}"`); + } + return { kind: "equals", key, value: rhs }; +} + +export function matchesLabelFilter( + kvLabels: Record, + tagLabels: string[] | undefined, + expr: string | LabelFilterExpr, +): boolean { + const parsed = typeof expr === "string" ? parseLabelFilterExpr(expr) : expr; + const current = kvLabels[parsed.key]; + switch (parsed.kind) { + case "exists": + return ( + Object.prototype.hasOwnProperty.call(kvLabels, parsed.key) || + Boolean(tagLabels?.includes(parsed.key)) + ); + case "equals": + return current === parsed.value; + case "in": + return current !== undefined && parsed.values.includes(current); + } +} + +export type ApplyKvLabelMutationResult = + | { ok: true; labels: Record } + | { ok: false; error: "label_conflict"; conflictingKeys: string[] }; + +export function applyKvLabelMutation( + current: Record, + rawMutation: KvLabelMutation, +): ApplyKvLabelMutationResult { + const mutation = KvLabelMutationSchema.parse(rawMutation); + + if (mutation.if) { + const conflictingKeys: string[] = []; + for (const [key, expected] of Object.entries(mutation.if)) { + const actual = Object.prototype.hasOwnProperty.call(current, key) + ? current[key]! + : null; + if (actual !== expected) { + conflictingKeys.push(key); + } + } + if (conflictingKeys.length > 0) { + return { ok: false, error: "label_conflict", conflictingKeys }; + } + } + + const next: Record = { ...current }; + if (mutation.unset) { + for (const key of mutation.unset) { + delete next[key]; + } + } + if (mutation.set) { + for (const [key, value] of Object.entries(mutation.set)) { + next[key] = value; + } + } + + return { ok: true, labels: next }; +} diff --git a/packages/shared/src/headless/leases.ts b/packages/shared/src/headless/leases.ts new file mode 100644 index 00000000000..0615826ad9b --- /dev/null +++ b/packages/shared/src/headless/leases.ts @@ -0,0 +1,268 @@ +import { z } from "zod"; +import type { IssuePriority, IssueStatus } from "../constants.js"; +import type { IssueScope } from "./identity.js"; +import { parseDurationMs } from "./pure.js"; +import { SCHEMA_REF_REGEX, schemaBlockSchema, type SchemaBlock } from "./schemas.js"; + +export { parseDurationMs }; + +export const durationValueSchema = z + .union([z.number().finite().nonnegative(), z.string().min(1)]) + .transform((val, ctx) => { + try { + return parseDurationMs(val); + } catch (err) { + ctx.addIssue({ + code: "custom", + message: err instanceof Error ? err.message : "Invalid duration", + }); + return z.NEVER; + } + }); + +export const TaskClaimRequestSchema = z + .object({ + issueId: z.string().min(1).optional(), + ready: z.boolean().optional(), + channel: z.string().min(1).optional(), + projectId: z.string().min(1).optional(), + labels: z.array(z.string().min(1)).optional(), + leaseSec: z.number().int().min(1).max(86400).optional(), + lease: z.union([z.number().finite().positive(), z.string().min(1)]).optional(), + waitSec: z.number().finite().nonnegative().optional(), + wait: z.union([z.number().finite().nonnegative(), z.string().min(1)]).optional(), + includeUntrusted: z.boolean().optional(), + }) + .strict(); + +export type TaskClaimRequest = z.input; + +export const TaskRenewSchema = z + .object({ + claimToken: z.string().min(1).optional(), + claimEpoch: z.number().int().nonnegative().optional(), + leaseSec: z.number().int().min(1).max(86400).optional(), + lease: z.union([z.number().finite().positive(), z.string().min(1)]).optional(), + }) + .strict(); + +export type TaskRenewInput = z.input; + +export const TaskReleaseSchema = z + .object({ + claimToken: z.string().min(1).optional(), + claimEpoch: z.number().int().nonnegative().optional(), + comment: z.string().optional(), + }) + .strict(); + +export type TaskReleaseInput = z.input; + +export const TaskCompleteSchema = z + .object({ + claimToken: z.string().min(1).optional(), + claimEpoch: z.number().int().nonnegative().optional(), + message: z.string().optional(), + comment: z.string().optional(), + data: z.record(z.string(), z.unknown()).optional(), + blocks: z.array(schemaBlockSchema).optional(), + prUrl: z.string().url().optional(), + resultSchema: z + .string() + .refine((v) => SCHEMA_REF_REGEX.test(v.trim()), { + message: "Invalid resultSchema ref", + }) + .optional(), + }) + .strict(); + +export type TaskCompleteInput = z.input; + +export const TaskFailSchema = z + .object({ + claimToken: z.string().min(1).optional(), + claimEpoch: z.number().int().nonnegative().optional(), + reason: z.string().min(1), + requeue: z.boolean().optional(), + }) + .strict(); + +export type TaskFailInput = z.input; + +export const OneLineAskSchema = z + .object({ + question: z.string().min(1), + choices: z.array(z.string().min(1)).optional(), + humanOnly: z.boolean().optional(), + agent: z.string().min(1).optional(), + continuationPolicy: z + .enum(["none", "wake_assignee", "requeue_on_resolve"]) + .optional(), + idempotencyKey: z.string().min(1).max(255).optional(), + claimToken: z.string().min(1).optional(), + claimEpoch: z.number().int().nonnegative().optional(), + }) + .strict(); + +export type OneLineAskInput = z.input; + +export const OneLineConfirmSchema = z + .object({ + prompt: z.string().min(1), + humanOnly: z.boolean().optional(), + wakeOnAccept: z.boolean().optional(), + continuationPolicy: z + .enum(["none", "wake_assignee", "wake_assignee_on_accept", "requeue_on_resolve"]) + .optional(), + idempotencyKey: z.string().min(1).max(255).optional(), + claimToken: z.string().min(1).optional(), + claimEpoch: z.number().int().nonnegative().optional(), + }) + .strict(); + +export type OneLineConfirmInput = z.input; + +export const SchedulePostSchema = z + .object({ + target: z.string().min(1), + message: z.string().min(1), + in: z.union([z.number().finite().nonnegative(), z.string().min(1)]).optional(), + at: z.string().min(1).optional(), + every: z.union([z.number().finite().positive(), z.string().min(1)]).optional(), + until: z.string().min(1).optional(), + post: z.boolean().optional(), + labels: z.record(z.string(), z.string()).optional(), + blocks: z.array(schemaBlockSchema).optional(), + }) + .strict() + .superRefine((val, ctx) => { + if (val.in === undefined && val.at === undefined && val.every === undefined) { + ctx.addIssue({ + code: "custom", + message: "Schedule requires at least one of 'in', 'at', or 'every'", + }); + } + }); + +export type SchedulePostInput = z.input; + +export interface HeadlessIssueView { + id: string; + companyId: string; + identifier: string; + title: string; + description: string | null; + status: IssueStatus; + scope: IssueScope; + priority: IssuePriority; + channelId: string | null; + channel: string | null; + projectId: string | null; + assigneeAgentId: string | null; + assigneeUserId: string | null; + actorProfile: string | null; + kvLabels: Record; + tagLabels: string[]; + blocks: SchemaBlock[]; + resultSchemaRef: string | null; + blockedByIssueIds: string[]; + isPassivePost: boolean; + claimEpoch: number; + claimHolderProfile: string | null; + claimHolderAgentId: string | null; + claimHolderUserId: string | null; + claimLeaseExpiresAt: string | null; + claimAttemptCount: number; + cursor: string; + createdAt: string; + updatedAt: string; +} + +export interface CommentView { + id: string; + issueId: string; + identifier: string; + body: string; + authorType: "user" | "agent" | "system"; + authorUserId: string | null; + authorAgentId: string | null; + actorProfile: string | null; + kvLabels: Record; + blocks: SchemaBlock[]; + internal: boolean; + cursor: string; + createdAt: string; +} + +export interface ChannelPage { + kind: "channel"; + channel: string; + items: Array< + HeadlessIssueView & { + replyCount: number; + latestReply: CommentView | null; + } + >; + cursor: string; +} + +export interface ThreadDetailView { + kind: "thread"; + issue: HeadlessIssueView; + comments: CommentView[]; + interactions: InteractionView[]; + cursor: string; +} + +export interface TaskClaimView { + issue: HeadlessIssueView; + claimToken: string; + claimEpoch: number; + leaseExpiresAt: string; + cursor: string; +} + +export interface InteractionView { + id: string; + issueId: string; + identifier: string; + kind: "ask_user_questions" | "request_confirmation"; + status: "pending" | "accepted" | "rejected" | "answered" | "cancelled"; + prompt: string; + choices?: string[]; + resolverPolicy: "anyone" | "human_only" | "not_creator"; + continuationPolicy: string; + answer?: string | null; + note?: string | null; + cursor: string; + createdAt: string; + resolvedAt: string | null; +} + +export interface ScheduleView { + id: string; + companyId: string; + target: string; + message: string; + nextRunAt: string; + intervalMs: number | null; + untilAt: string | null; + post: boolean; + status: "scheduled" | "cancelled" | "completed"; + cursor?: string; + createdAt: string; +} + +export interface BatchCreatedTaskItem { + key: string | null; + id: string; + identifier: string; + cursor: string; + issue: HeadlessIssueView; +} + +export interface BatchCreateIssuesResult { + tasks: BatchCreatedTaskItem[]; + cursor: string; + idempotentReplay: boolean; +} diff --git a/packages/shared/src/headless/plans.ts b/packages/shared/src/headless/plans.ts new file mode 100644 index 00000000000..9755160a884 --- /dev/null +++ b/packages/shared/src/headless/plans.ts @@ -0,0 +1,305 @@ +import { z } from "zod"; +import { ISSUE_PRIORITIES } from "../constants.js"; +import { normalizeIssueIdentifier } from "../issue-references.js"; +import { exactChannelPathSchema, splitMessageIntoTitleAndDescription } from "./channels.js"; +import { writableKvLabelsRecordSchema } from "./labels.js"; +import { SCHEMA_REF_REGEX, schemaBlockSchema } from "./schemas.js"; + +const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const PLAN_TASK_KEY_RE = /^[a-z0-9][a-z0-9_.-]{0,63}$/i; + +export const planTaskNeedSchema = z.union([ + z.string().min(1), + z.object({ key: z.string().min(1) }).strict(), +]); + +export const PlanTaskInputSchema = z + .object({ + key: z + .string() + .regex(PLAN_TASK_KEY_RE, "Task key must be alphanumeric with '.', '_', or '-'") + .optional(), + title: z.string().min(1).max(240).optional(), + text: z.string().optional(), + description: z.string().nullable().optional(), + projectId: z.string().min(1).nullable().optional(), + priority: z.enum(ISSUE_PRIORITIES).optional(), + labels: writableKvLabelsRecordSchema.optional(), + tagLabels: z.array(z.string().min(1).max(64)).optional(), + needs: z.array(planTaskNeedSchema).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(), + board: z.boolean().optional(), + blocks: z.array(schemaBlockSchema).optional(), + }) + .strict() + .superRefine((val, ctx) => { + const hasTitle = Boolean(val.title && val.title.trim().length > 0); + const hasText = Boolean(val.text && val.text.trim().length > 0); + const hasDesc = Boolean(val.description && val.description.trim().length > 0); + const hasBlocks = Boolean(val.blocks && val.blocks.length > 0); + if (!hasTitle && !hasText && !hasDesc && !hasBlocks) { + ctx.addIssue({ + code: "custom", + message: "Each task must provide title, text, description, or blocks", + }); + } + }); + +export type PlanTaskInput = z.input; + +export const BatchCreateIssuesSchema = z + .object({ + channel: exactChannelPathSchema.optional(), + projectId: z.string().min(1).nullable().optional(), + board: z.boolean().optional(), + idempotencyKey: z.string().min(1).max(255).optional(), + tasks: z.array(PlanTaskInputSchema).min(1).max(200), + }) + .strict(); + +export type BatchCreateIssuesInput = z.input; + +export interface ResolvedPlanTask { + index: number; + key: string | null; + title: string; + description: string | null; + projectId: string | null | undefined; + priority: (typeof ISSUE_PRIORITIES)[number]; + labels: Record; + tagLabels: string[]; + localNeeds: string[]; + externalNeeds: string[]; + for?: string; + assigneeAgentId?: string | null; + resultSchema?: string; + board?: boolean; + blocks: z.infer[]; +} + +export type BatchPlanValidationErrorCode = + | "validation_error" + | "duplicate_task_key" + | "unknown_dependency_key" + | "cyclic_dependencies"; + +export interface BatchPlanValidationError { + ok: false; + code: BatchPlanValidationErrorCode; + message: string; + duplicateKeys?: string[]; + unknownDependencies?: Array<{ taskKey: string; dependency: string }>; + cycleKeys?: string[]; +} + +export interface BatchPlanValidationSuccess { + ok: true; + channel?: string; + projectId?: string | null; + board?: boolean; + idempotencyKey?: string; + tasks: ResolvedPlanTask[]; +} + +export type BatchPlanValidationResult = + | BatchPlanValidationSuccess + | BatchPlanValidationError; + +function isValidExternalIssueRef(value: string): boolean { + const trimmed = value.trim(); + if (UUID_RE.test(trimmed)) return true; + return normalizeIssueIdentifier(trimmed) !== null; +} + +export function validateAndSortBatchPlan( + rawInput: unknown, +): BatchPlanValidationResult { + const parsedResult = BatchCreateIssuesSchema.safeParse(rawInput); + if (!parsedResult.success) { + return { + ok: false, + code: "validation_error", + message: parsedResult.error.issues + .map((issue) => `${issue.path.join(".") || "$"}: ${issue.message}`) + .join("; "), + }; + } + + const parsed = parsedResult.data; + const keyToNodeIdx = new Map(); + const duplicateKeys: string[] = []; + + for (let i = 0; i < parsed.tasks.length; i += 1) { + const task = parsed.tasks[i]!; + if (task.key) { + if (keyToNodeIdx.has(task.key)) { + if (!duplicateKeys.includes(task.key)) { + duplicateKeys.push(task.key); + } + } else { + keyToNodeIdx.set(task.key, i); + } + } + } + + if (duplicateKeys.length > 0) { + return { + ok: false, + code: "duplicate_task_key", + message: `Duplicate task keys in plan: ${duplicateKeys.join(", ")}`, + duplicateKeys, + }; + } + + const adj: number[][] = Array.from({ length: parsed.tasks.length }, () => []); + const indegree = new Array(parsed.tasks.length).fill(0); + const unknownDependencies: Array<{ taskKey: string; dependency: string }> = []; + const localNeedsPerNode: string[][] = Array.from( + { length: parsed.tasks.length }, + () => [], + ); + const externalNeedsPerNode: string[][] = Array.from( + { length: parsed.tasks.length }, + () => [], + ); + + for (let i = 0; i < parsed.tasks.length; i += 1) { + const task = parsed.tasks[i]!; + const taskLabel = task.key ?? `tasks[${i}]`; + const seenDeps = new Set(); + + for (const rawNeed of task.needs ?? []) { + const dep = typeof rawNeed === "string" ? rawNeed.trim() : rawNeed.key.trim(); + if (seenDeps.has(dep)) continue; + seenDeps.add(dep); + + const targetIdx = keyToNodeIdx.get(dep); + if (targetIdx !== undefined) { + if (targetIdx === i) { + return { + ok: false, + code: "cyclic_dependencies", + message: `Task "${taskLabel}" cannot depend on itself`, + cycleKeys: [taskLabel], + }; + } + adj[targetIdx]!.push(i); + indegree[i] = (indegree[i] ?? 0) + 1; + localNeedsPerNode[i]!.push(dep); + } else if (isValidExternalIssueRef(dep)) { + const normalizedExt = UUID_RE.test(dep) + ? dep.toLowerCase() + : normalizeIssueIdentifier(dep)!; + externalNeedsPerNode[i]!.push(normalizedExt); + } else { + unknownDependencies.push({ taskKey: taskLabel, dependency: dep }); + } + } + } + + if (unknownDependencies.length > 0) { + return { + ok: false, + code: "unknown_dependency_key", + message: `Unknown dependency keys: ${unknownDependencies + .map((d) => `${d.taskKey} -> ${d.dependency}`) + .join(", ")}`, + unknownDependencies, + }; + } + + // Kahn's algorithm preserving original declaration order when ties occur + const readyQueue: number[] = []; + for (let i = 0; i < parsed.tasks.length; i += 1) { + if (indegree[i] === 0) { + readyQueue.push(i); + } + } + + const orderedIndices: number[] = []; + while (readyQueue.length > 0) { + readyQueue.sort((a, b) => a - b); + const current = readyQueue.shift()!; + orderedIndices.push(current); + + for (const neighbor of adj[current]!) { + const nextDegree = (indegree[neighbor] ?? 0) - 1; + indegree[neighbor] = nextDegree; + if (nextDegree === 0) { + readyQueue.push(neighbor); + } + } + } + + if (orderedIndices.length < parsed.tasks.length) { + const cycleKeys: string[] = []; + for (let i = 0; i < parsed.tasks.length; i += 1) { + if ((indegree[i] ?? 0) > 0) { + cycleKeys.push(parsed.tasks[i]!.key ?? `tasks[${i}]`); + } + } + return { + ok: false, + code: "cyclic_dependencies", + message: `Cyclic dependencies detected among tasks: ${cycleKeys.join(", ")}`, + cycleKeys, + }; + } + + const resolvedTasks: ResolvedPlanTask[] = orderedIndices.map((idx) => { + const task = parsed.tasks[idx]!; + const rawBody = task.text ?? task.description ?? ""; + let title: string; + let description: string | null; + + if (task.title && task.title.trim().length > 0) { + title = task.title.trim(); + const bodyTrimmed = rawBody.trim(); + description = bodyTrimmed.length > 0 ? rawBody : null; + } else { + const fallback = task.blocks?.[0] + ? `[${task.blocks[0].schema}@${task.blocks[0].version}]` + : "Untitled task"; + const split = splitMessageIntoTitleAndDescription(rawBody, fallback); + title = split.title; + description = split.description; + } + + const effectiveProjectId = + task.projectId !== undefined ? task.projectId : parsed.projectId; + + return { + index: idx, + key: task.key ?? null, + title, + description, + projectId: effectiveProjectId, + priority: task.priority ?? "medium", + labels: task.labels ?? {}, + tagLabels: task.tagLabels ?? [], + localNeeds: localNeedsPerNode[idx]!, + externalNeeds: externalNeedsPerNode[idx]!, + for: task.for, + assigneeAgentId: task.assigneeAgentId, + resultSchema: task.resultSchema, + board: task.board ?? parsed.board, + blocks: task.blocks ?? [], + }; + }); + + return { + ok: true, + channel: parsed.channel, + projectId: parsed.projectId, + board: parsed.board, + idempotencyKey: parsed.idempotencyKey, + tasks: resolvedTasks, + }; +} diff --git a/packages/shared/src/headless/pure.ts b/packages/shared/src/headless/pure.ts new file mode 100644 index 00000000000..962757460d6 --- /dev/null +++ b/packages/shared/src/headless/pure.ts @@ -0,0 +1,150 @@ +export const CHANNEL_PATH_REGEX = /^[a-z0-9][a-z0-9_-]*(\/[a-z0-9][a-z0-9_-]*)*$/; + +export interface NormalizedChannelPath { + path: string; + isSubtreePrefix: boolean; +} + +export function normalizeChannelPath( + input: string, + opts?: { allowSubtreePrefix?: boolean }, +): NormalizedChannelPath { + const allowSubtreePrefix = opts?.allowSubtreePrefix ?? true; + let trimmed = input.trim(); + if (trimmed.startsWith("#")) { + trimmed = trimmed.slice(1).trim(); + } + trimmed = trimmed.toLowerCase(); + + const isSubtreePrefix = trimmed.endsWith("/"); + if (isSubtreePrefix && !allowSubtreePrefix) { + throw new Error( + `Invalid channel path "${input}": trailing '/' is only allowed for subtree queries`, + ); + } + + const candidate = isSubtreePrefix ? trimmed.slice(0, -1) : trimmed; + if (!CHANNEL_PATH_REGEX.test(candidate)) { + throw new Error( + `Invalid channel path "${input}": segments must be lowercase alphanumeric with '-' or '_' separated by '/'`, + ); + } + + return { path: candidate, isSubtreePrefix }; +} + +const TITLE_MAX_LEN = 120; + +function truncateTitle(raw: string, maxLen = TITLE_MAX_LEN): string { + if (raw.length <= maxLen) return raw; + const slice = raw.slice(0, maxLen - 1); + const lastSpace = slice.lastIndexOf(" "); + if (lastSpace > Math.floor(maxLen * 0.6)) { + return `${slice.slice(0, lastSpace).trimEnd()}…`; + } + return `${slice.trimEnd()}…`; +} + +export function splitMessageIntoTitleAndDescription( + text: string, + fallbackLabel?: string, +): { title: string; description: string | null } { + const normalized = text.replace(/\r\n/g, "\n").trim(); + if (!normalized) { + const fallback = fallbackLabel?.trim() || "Untitled post"; + return { + title: truncateTitle(fallback, TITLE_MAX_LEN), + description: null, + }; + } + + const nonEmptyLines = normalized + .split("\n") + .map((line) => line.trim()) + .filter((line) => line.length > 0); + + const firstRaw = nonEmptyLines[0] ?? normalized; + const withoutHeading = firstRaw.replace(/^#{1,6}\s+/, "").trim(); + const baseLine = withoutHeading.length > 0 ? withoutHeading : firstRaw; + const title = truncateTitle(baseLine, TITLE_MAX_LEN); + + if (nonEmptyLines.length === 1 && baseLine.length <= TITLE_MAX_LEN) { + return { title, description: null }; + } + + return { title, description: normalized }; +} + +export const SCHEMA_NAME_REGEX = /^[a-z0-9][a-z0-9_-]{0,63}$/; +export const SCHEMA_REF_REGEX = /^([a-z0-9][a-z0-9_-]{0,63})@([1-9][0-9]*)$/; + +export interface ParsedSchemaRef { + name: string; + version: number; + ref: string; +} + +export function parseSchemaRef(ref: string): ParsedSchemaRef { + const trimmed = ref.trim(); + const match = SCHEMA_REF_REGEX.exec(trimmed); + if (!match) { + throw new Error( + `Invalid schema reference "${ref}": expected @ (e.g. security-finding@1)`, + ); + } + const name = match[1]!; + const version = Number.parseInt(match[2]!, 10); + if (!Number.isSafeInteger(version) || version < 1) { + throw new Error(`Invalid schema version in "${ref}"`); + } + return { name, version, ref: `${name}@${version}` }; +} + +const DURATION_RE = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i; + +const UNIT_MULTIPLIERS_MS: Record = { + ms: 1, + s: 1_000, + m: 60_000, + h: 3_600_000, + d: 86_400_000, +}; + +export function parseDurationMs(input: string | number): number { + if (typeof input === "number") { + if (!Number.isFinite(input) || input < 0) { + throw new Error(`Invalid duration number: ${input}`); + } + return Math.floor(input); + } + const trimmed = input.trim(); + const match = DURATION_RE.exec(trimmed); + if (!match) { + throw new Error( + `Invalid duration "${input}": expected (e.g. "30s", "5m", "2h", "7d")`, + ); + } + const amount = Number.parseFloat(match[1]!); + const unit = match[2]!.toLowerCase(); + const multiplier = UNIT_MULTIPLIERS_MS[unit]; + if (!Number.isFinite(amount) || amount < 0 || multiplier === undefined) { + throw new Error(`Invalid duration "${input}"`); + } + return Math.floor(amount * multiplier); +} + +const EVENT_CURSOR_RE = /^evt_([0-9]+)$/; + +export function formatEventCursor(seq: number): string { + if (!Number.isSafeInteger(seq) || seq < 0) { + throw new Error(`Invalid event sequence number: ${seq}`); + } + return `evt_${seq}`; +} + +export function parseEventCursor(cursor: string): number | null { + const match = EVENT_CURSOR_RE.exec(cursor.trim()); + if (!match) return null; + const parsed = Number.parseInt(match[1]!, 10); + return Number.isSafeInteger(parsed) ? parsed : null; +} diff --git a/packages/shared/src/headless/schemas.ts b/packages/shared/src/headless/schemas.ts new file mode 100644 index 00000000000..eb0716395a1 --- /dev/null +++ b/packages/shared/src/headless/schemas.ts @@ -0,0 +1,603 @@ +import { z } from "zod"; +import { + SCHEMA_NAME_REGEX, + SCHEMA_REF_REGEX, + parseSchemaRef, + type ParsedSchemaRef, +} from "./pure.js"; + +export { + SCHEMA_NAME_REGEX, + SCHEMA_REF_REGEX, + parseSchemaRef, + type ParsedSchemaRef, +}; + +export type JsonSchemaType = + | "string" + | "number" + | "integer" + | "boolean" + | "object" + | "array" + | "null"; + +export interface JsonSchemaObject { + type?: JsonSchemaType | JsonSchemaType[]; + required?: string[]; + properties?: Record; + additionalProperties?: boolean | JsonSchemaObject; + enum?: unknown[]; + items?: JsonSchemaObject | JsonSchemaObject[]; + minLength?: number; + maxLength?: number; + minimum?: number; + maximum?: number; + pattern?: string; + description?: string; + [key: string]: unknown; +} + +export interface JsonSchemaValidationResult { + valid: boolean; + errors: string[]; +} + +const MAX_SCHEMA_REGEX_LENGTH = 512; +const MAX_SCHEMA_REGEX_INPUT_LENGTH = 16_384; + +function readQuantifierSpan(pattern: string, start: number): number | null { + const ch = pattern[start]; + if (ch === "*" || ch === "+" || ch === "?") { + return pattern[start + 1] === "?" ? 2 : 1; + } + if (ch === "{") { + const rest = pattern.slice(start); + const match = /^\{(\d+)(?:,(\d*))?\}/.exec(rest); + if (match) { + const len = match[0].length; + return pattern[start + len] === "?" ? len + 1 : len; + } + } + return null; +} + +function isDisjointLiteralAlternation(groupContent: string): boolean { + const body = groupContent.replace(/^(?:\?[A-Za-z-]*:|\?<[^>]+>)/, ""); + const parts = body.split("|"); + if (parts.length < 2) return false; + const firstChars = new Set(); + for (const part of parts) { + if (!part || !/^[A-Za-z0-9_-]+$/.test(part)) { + return false; + } + const ch = part[0]!; + if (firstChars.has(ch)) { + return false; + } + firstChars.add(ch); + } + return true; +} + +export function assertSafeRegexPattern(pattern: string): void { + if (typeof pattern !== "string" || pattern.length > MAX_SCHEMA_REGEX_LENGTH) { + throw new Error( + `Schema regex pattern exceeds maximum length of ${MAX_SCHEMA_REGEX_LENGTH} characters`, + ); + } + + // Deterministic single-pass structural scan to reject backtracking bombs before RegExp execution. + const stack: Array<{ + openIndex: number; + hasQuantifier: boolean; + hasAlternation: boolean; + length: number; + }> = [{ openIndex: -1, hasQuantifier: false, hasAlternation: false, length: 0 }]; + let inCharClass = false; + let lastAtomGroupHasQuantifier = false; + let lastAtomGroupHasAlternation = false; + let lastAtomGroupContent = ""; + let lastWasQuantifier = false; + + for (let i = 0; i < pattern.length; i += 1) { + const ch = pattern[i]!; + if (ch === "\\") { + const next = pattern[i + 1]; + if (!next) { + throw new Error("Invalid trailing escape in schema regex pattern"); + } + if (!inCharClass && ((next >= "1" && next <= "9") || next === "k")) { + throw new Error("Backreferences are not permitted in schema regex patterns"); + } + i += 1; + stack[stack.length - 1]!.length += 2; + lastAtomGroupHasQuantifier = false; + lastAtomGroupHasAlternation = false; + lastAtomGroupContent = ""; + lastWasQuantifier = false; + continue; + } + + if (inCharClass) { + if (ch === "]") { + inCharClass = false; + } + stack[stack.length - 1]!.length += 1; + continue; + } + + if (ch === "[") { + inCharClass = true; + lastAtomGroupHasQuantifier = false; + lastAtomGroupHasAlternation = false; + lastAtomGroupContent = ""; + lastWasQuantifier = false; + stack[stack.length - 1]!.length += 1; + continue; + } + + if (ch === "(") { + const openIndex = i; + if (pattern[i + 1] === "?") { + const afterQ = pattern[i + 2]; + const afterLt = pattern[i + 3]; + if ( + afterQ === "=" || + afterQ === "!" || + (afterQ === "<" && (afterLt === "=" || afterLt === "!")) + ) { + throw new Error("Lookahead/lookbehind assertions are not permitted in schema regex patterns"); + } + if (afterQ === "<") { + const closeAngle = pattern.indexOf(">", i + 3); + if (closeAngle !== -1) { + i = closeAngle; + } + } else { + // Non-capturing (?:...) or inline flag group (?ims:...) - skip header so '?' is not treated as quantifier. + const colonIdx = pattern.indexOf(":", i + 2); + const closeParenIdx = pattern.indexOf(")", i + 2); + if (colonIdx !== -1 && (closeParenIdx === -1 || colonIdx < closeParenIdx)) { + i = colonIdx; + } + } + } + stack.push({ openIndex, hasQuantifier: false, hasAlternation: false, length: 0 }); + lastAtomGroupHasQuantifier = false; + lastAtomGroupHasAlternation = false; + lastAtomGroupContent = ""; + lastWasQuantifier = false; + continue; + } + + if (ch === ")") { + if (stack.length > 1) { + const closed = stack.pop()!; + const parent = stack[stack.length - 1]!; + if (closed.hasQuantifier) { + parent.hasQuantifier = true; + } + parent.length += closed.length + 2; + lastAtomGroupHasQuantifier = closed.hasQuantifier; + lastAtomGroupHasAlternation = closed.hasAlternation && closed.length > 0; + lastAtomGroupContent = + closed.openIndex >= 0 ? pattern.slice(closed.openIndex + 1, i) : ""; + } else { + lastAtomGroupHasQuantifier = false; + lastAtomGroupHasAlternation = false; + lastAtomGroupContent = ""; + } + lastWasQuantifier = false; + continue; + } + + if (ch === "|") { + stack[stack.length - 1]!.hasAlternation = true; + lastAtomGroupHasQuantifier = false; + lastAtomGroupHasAlternation = false; + lastAtomGroupContent = ""; + lastWasQuantifier = false; + continue; + } + + const qSpan = readQuantifierSpan(pattern, i); + if (qSpan !== null) { + if (lastWasQuantifier) { + throw new Error("Adjacent quantifiers are not permitted in schema regex patterns"); + } + if (lastAtomGroupHasQuantifier) { + throw new Error( + "Nested quantifiers are not permitted in schema regex patterns", + ); + } + if ( + lastAtomGroupHasAlternation && + ch !== "?" && + !isDisjointLiteralAlternation(lastAtomGroupContent) + ) { + throw new Error( + "Repeated alternation groups are not permitted in schema regex patterns", + ); + } + stack[stack.length - 1]!.hasQuantifier = true; + lastAtomGroupHasQuantifier = false; + lastAtomGroupHasAlternation = false; + lastAtomGroupContent = ""; + lastWasQuantifier = true; + i += qSpan - 1; + continue; + } + + stack[stack.length - 1]!.length += 1; + lastAtomGroupHasQuantifier = false; + lastAtomGroupHasAlternation = false; + lastAtomGroupContent = ""; + lastWasQuantifier = false; + } + + new RegExp(pattern); +} + +function deepEqual(a: unknown, b: unknown): boolean { + if (Object.is(a, b)) return true; + if (typeof a !== typeof b || a === null || b === null) return false; + if (Array.isArray(a) || Array.isArray(b)) { + if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) { + return false; + } + return a.every((item, idx) => deepEqual(item, b[idx])); + } + if (typeof a === "object" && typeof b === "object") { + const aObj = a as Record; + const bObj = b as Record; + const aKeys = Object.keys(aObj); + const bKeys = Object.keys(bObj); + if (aKeys.length !== bKeys.length) return false; + return aKeys.every( + (k) => + Object.prototype.hasOwnProperty.call(bObj, k) && + deepEqual(aObj[k], bObj[k]), + ); + } + return false; +} + +function matchesJsonType(value: unknown, expected: JsonSchemaType): boolean { + switch (expected) { + case "null": + return value === null; + case "boolean": + return typeof value === "boolean"; + case "string": + return typeof value === "string"; + case "number": + return typeof value === "number" && Number.isFinite(value); + case "integer": + return typeof value === "number" && Number.isInteger(value); + case "array": + return Array.isArray(value); + case "object": + return typeof value === "object" && value !== null && !Array.isArray(value); + } +} + +function describeActualType(value: unknown): string { + if (value === null) return "null"; + if (Array.isArray(value)) return "array"; + return typeof value; +} + +function validateNode( + schema: Record, + value: unknown, + path: string, + errors: string[], +): void { + if (schema.type !== undefined) { + const allowedTypes = Array.isArray(schema.type) + ? (schema.type as JsonSchemaType[]) + : [schema.type as JsonSchemaType]; + if (!allowedTypes.some((t) => matchesJsonType(value, t))) { + errors.push( + `${path}: expected type ${allowedTypes.join(" | ")}, got ${describeActualType(value)}`, + ); + return; + } + } + + if (Array.isArray(schema.enum)) { + const matched = schema.enum.some((candidate) => deepEqual(value, candidate)); + if (!matched) { + errors.push( + `${path}: expected one of [${schema.enum.map((v) => JSON.stringify(v)).join(", ")}]`, + ); + } + } + + if (typeof value === "string") { + if (typeof schema.minLength === "number" && value.length < schema.minLength) { + errors.push( + `${path}: string length ${value.length} is less than minLength ${schema.minLength}`, + ); + } + if (typeof schema.maxLength === "number" && value.length > schema.maxLength) { + errors.push( + `${path}: string length ${value.length} exceeds maxLength ${schema.maxLength}`, + ); + } + if (typeof schema.pattern === "string") { + if (value.length > MAX_SCHEMA_REGEX_INPUT_LENGTH) { + errors.push( + `${path}: string length ${value.length} exceeds pattern validation limit ${MAX_SCHEMA_REGEX_INPUT_LENGTH}`, + ); + } else { + try { + assertSafeRegexPattern(schema.pattern); + const re = new RegExp(schema.pattern); + if (!re.test(value)) { + errors.push(`${path}: string does not match pattern ${schema.pattern}`); + } + } catch (err) { + errors.push( + `${path}: invalid or unsafe schema pattern ${schema.pattern}: ${err instanceof Error ? err.message : "invalid pattern"}`, + ); + } + } + } + } + + if (typeof value === "number" && Number.isFinite(value)) { + if (typeof schema.minimum === "number" && value < schema.minimum) { + errors.push(`${path}: ${value} is less than minimum ${schema.minimum}`); + } + if (typeof schema.maximum === "number" && value > schema.maximum) { + errors.push(`${path}: ${value} exceeds maximum ${schema.maximum}`); + } + } + + if (Array.isArray(value) && schema.items !== undefined) { + if (Array.isArray(schema.items)) { + for (let i = 0; i < value.length; i += 1) { + const itemSchema = schema.items[i]; + if (itemSchema && typeof itemSchema === "object") { + validateNode( + itemSchema as Record, + value[i], + `${path}[${i}]`, + errors, + ); + } + } + } else if (typeof schema.items === "object" && schema.items !== null) { + const itemSchema = schema.items as Record; + for (let i = 0; i < value.length; i += 1) { + validateNode(itemSchema, value[i], `${path}[${i}]`, errors); + } + } + } + + if (typeof value === "object" && value !== null && !Array.isArray(value)) { + const obj = value as Record; + const props = + schema.properties && + typeof schema.properties === "object" && + !Array.isArray(schema.properties) + ? (schema.properties as Record>) + : {}; + + if (Array.isArray(schema.required)) { + for (const reqKey of schema.required) { + if ( + typeof reqKey === "string" && + (!Object.prototype.hasOwnProperty.call(obj, reqKey) || + obj[reqKey] === undefined) + ) { + errors.push(`${path}: missing required property "${reqKey}"`); + } + } + } + + for (const [key, propVal] of Object.entries(obj)) { + if (propVal === undefined) continue; + if (Object.prototype.hasOwnProperty.call(props, key)) { + const propSchema = props[key]; + if (propSchema && typeof propSchema === "object") { + validateNode(propSchema, propVal, `${path}.${key}`, errors); + } + } else if (schema.additionalProperties === false) { + errors.push(`${path}.${key}: additional property "${key}" is not allowed`); + } else if ( + typeof schema.additionalProperties === "object" && + schema.additionalProperties !== null + ) { + validateNode( + schema.additionalProperties as Record, + propVal, + `${path}.${key}`, + errors, + ); + } + } + } +} + +export function validateAgainstJsonSchema( + schema: Record, + data: unknown, +): JsonSchemaValidationResult { + const errors: string[] = []; + validateNode(schema, data, "$", errors); + return { valid: errors.length === 0, errors }; +} + +function canonicalizeValue(value: unknown): unknown { + if (Array.isArray(value)) { + return value.map(canonicalizeValue); + } + if (typeof value === "object" && value !== null) { + const sorted: Record = {}; + for (const key of Object.keys(value as Record).sort()) { + const entry = (value as Record)[key]; + if (entry !== undefined) { + sorted[key] = canonicalizeValue(entry); + } + } + return sorted; + } + return value; +} + +export function canonicalizeJsonSchema(schema: Record): string { + return JSON.stringify(canonicalizeValue(schema)); +} + +export const schemaBlockSchema = z + .object({ + schema: z.string().regex(SCHEMA_NAME_REGEX, "Invalid schema name"), + version: z.number().int().positive(), + data: z.record(z.string(), z.unknown()), + }) + .strict(); + +export type SchemaBlock = z.infer; + +export interface CompanySchemaView { + id: string; + companyId: string | null; + name: string; + version: number; + ref: string; + description: string | null; + jsonSchema: JsonSchemaObject; + builtIn: boolean; + createdAt: string; +} + +export const createCompanySchemaInputSchema = z + .object({ + ref: z + .string() + .refine((v) => SCHEMA_REF_REGEX.test(v.trim()), { + message: "Schema ref must match @", + }) + .optional(), + name: z.string().regex(SCHEMA_NAME_REGEX).optional(), + version: z.number().int().positive().optional(), + description: z.string().max(1000).nullable().optional(), + jsonSchema: z.record(z.string(), z.unknown()), + }) + .strict() + .superRefine((val, ctx) => { + if (!val.ref && (!val.name || val.version === undefined)) { + ctx.addIssue({ + code: "custom", + message: "Either ref (e.g. finding@1) or both name and version are required", + }); + } + }); + +export type CreateCompanySchemaInput = z.infer; + +export const BUILT_IN_COMPANY_SCHEMAS: ReadonlyArray<{ + name: string; + version: number; + ref: string; + description: string; + jsonSchema: JsonSchemaObject; +}> = [ + { + name: "git-commit", + version: 1, + ref: "git-commit@1", + description: "Structured git commit reference", + jsonSchema: { + type: "object", + required: ["sha"], + additionalProperties: true, + properties: { + sha: { + type: "string", + pattern: "^[0-9a-fA-F]{7,64}$", + }, + branch: { type: "string", minLength: 1 }, + repo: { type: "string", minLength: 1 }, + message: { type: "string" }, + filesChanged: { type: "integer", minimum: 0 }, + }, + }, + }, + { + name: "pull-request", + version: 1, + ref: "pull-request@1", + description: "Structured pull request reference", + jsonSchema: { + type: "object", + required: ["url"], + additionalProperties: true, + properties: { + url: { type: "string", pattern: "^https?://" }, + number: { type: "integer", minimum: 1 }, + repo: { type: "string", minLength: 1 }, + title: { type: "string" }, + state: { type: "string", enum: ["open", "draft", "merged", "closed"] }, + branch: { type: "string" }, + }, + }, + }, + { + name: "test-report", + version: 1, + ref: "test-report@1", + description: "Structured test execution summary", + jsonSchema: { + type: "object", + required: ["passed"], + additionalProperties: true, + properties: { + passed: { type: "boolean" }, + total: { type: "integer", minimum: 0 }, + failed: { type: "integer", minimum: 0 }, + skipped: { type: "integer", minimum: 0 }, + command: { type: "string" }, + summary: { type: "string" }, + failures: { + type: "array", + items: { + type: "object", + required: ["name"], + additionalProperties: true, + properties: { + name: { type: "string", minLength: 1 }, + message: { type: "string" }, + }, + }, + }, + }, + }, + }, + { + name: "finding", + version: 1, + ref: "finding@1", + description: "Structured code, security, or audit finding", + jsonSchema: { + type: "object", + required: ["severity", "title"], + additionalProperties: true, + properties: { + severity: { + type: "string", + enum: ["critical", "high", "medium", "low", "info"], + }, + title: { type: "string", minLength: 1, maxLength: 300 }, + summary: { type: "string" }, + path: { type: "string" }, + line: { type: "integer", minimum: 1 }, + category: { type: "string" }, + cve: { type: "string" }, + }, + }, + }, +]; diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 159182d5003..dbdd64c5df8 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -3185,3 +3185,4 @@ export * from "./agent-setup-progress.js"; export { antigravitySwarmAvailable, antigravitySwarmWorkModeAllows, isAntigravityAgent, parseLeadingUserCommand, SWARM_REQUEST_MAX_CHARS, type LeadingUserCommand } from "./leading-user-command.js"; export * from "./cloud-inference.js"; export * from "./upstream-failure-codes.js"; +export * from "./headless/index.js"; diff --git a/packages/shared/src/sdk/client.ts b/packages/shared/src/sdk/client.ts new file mode 100644 index 00000000000..497691448c2 --- /dev/null +++ b/packages/shared/src/sdk/client.ts @@ -0,0 +1,1006 @@ +import { parseDurationMs, parseSchemaRef } from "../headless/pure.js"; +import type { + BatchCreateIssuesResult, + BoardEventView, + ChannelPage, + ChannelView, + ClientScopes, + CommentView, + CompanyResolutionView, + CompanySchemaView, + CreateChannelInput, + CreateCompanySchemaInput, + HeadlessIssueView, + InteractionView, + KvLabelMutation, + OneLineAskInput, + OneLineConfirmInput, + PlanTaskInput, + SchemaBlock, + SchedulePostInput, + ScheduleView, + TaskClaimView, + TaskCompleteInput, + ThreadDetailView, + WhoAmIView, +} from "../headless/index.js"; +import { + extractProfileApiKey, + readNodeEnv, + readStoredBoardAuthToken, + readStoredContext, + readStoredProfile, + readTrustedContext, + sameOriginUrl, +} from "./env.js"; +import { parseSseEventStream } from "./sse.js"; +import { + PaperclipError, + type ApproveRejectInput, + type ClaimedTask, + type CreateTaskInput, + type EventStreamFilters, + type EventWaitFilters, + type PaperclipClientOptions, + type PaperclipHandle, + type PostInput, + type ReadFilters, + type ReplyInput, + type TaskClaimOptions, + type TaskListFilters, +} from "./types.js"; + +const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const ISSUE_ID_RE = /^[A-Z][A-Z0-9]*-\d+$/i; + +function isIssueReference(target: string): boolean { + const trimmed = target.trim(); + return UUID_RE.test(trimmed) || ISSUE_ID_RE.test(trimmed); +} + +function appendMultiParam( + params: URLSearchParams, + key: string, + value: string | string[] | undefined, +): void { + if (value === undefined) return; + const values = Array.isArray(value) ? value : [value]; + for (const item of values) { + if (item !== undefined && item !== "") { + params.append(key, item); + } + } +} + +function buildBlocksFromSchemaInput( + blocks?: SchemaBlock[], + schema?: { ref: string; data: Record }, +): SchemaBlock[] | undefined { + const result: SchemaBlock[] = blocks ? [...blocks] : []; + if (schema) { + const parsed = parseSchemaRef(schema.ref); + result.push({ + schema: parsed.name, + version: parsed.version, + data: schema.data, + }); + } + return result.length > 0 ? result : undefined; +} + +interface InternalClientState { + apiBase: string; + apiBaseFromRepoLocal: boolean; + explicitApiKey?: string; + companyArg?: string; + profile: string | null; + scopes?: ClientScopes; + fetchImpl: typeof globalThis.fetch; + homeDir?: string; + cachedCompanyId: string | null; + companyPromise: Promise | null; +} + +async function parseErrorResponse(res: Response): Promise { + const text = await res.text().catch(() => ""); + let parsed: Record | null = null; + if (text) { + try { + const json = JSON.parse(text) as unknown; + if (typeof json === "object" && json !== null) { + parsed = json as Record; + } + } catch { + // non-JSON response + } + } + const nestedDetails = + parsed?.details && typeof parsed.details === "object" && !Array.isArray(parsed.details) + ? (parsed.details as Record) + : null; + const code = + (typeof parsed?.code === "string" && parsed.code) || + (typeof nestedDetails?.code === "string" && nestedDetails.code) || + (typeof parsed?.error === "string" && parsed.error) || + `http_${res.status}`; + const message = + (typeof parsed?.message === "string" && parsed.message) || + (typeof parsed?.error === "string" && parsed.error) || + text || + `Request failed with status ${res.status}`; + const rawNext = Array.isArray(parsed?.next) + ? parsed.next + : Array.isArray(nestedDetails?.next) + ? nestedDetails.next + : undefined; + const next = rawNext?.filter((x): x is string => typeof x === "string"); + + return new PaperclipError({ + status: res.status, + code, + message, + next, + details: parsed ?? undefined, + }); +} + +function createHandle(state: InternalClientState): PaperclipHandle { + const resolveAuthHeaders = (): Record => { + const headers: Record = {}; + const nodeEnv = readNodeEnv(); + const trustedCtx = readTrustedContext(state.homeDir); + const storedBoardAuthToken = state.apiBaseFromRepoLocal + ? undefined + : readStoredBoardAuthToken(state.apiBase, state.homeDir); + + const ambientKey = + nodeEnv.apiKey ?? trustedCtx?.apiKey ?? trustedCtx?.token; + const rawProfileCfg = state.profile + ? readStoredProfile(state.profile, state.homeDir) + : null; + const rawProfileKey = extractProfileApiKey(rawProfileCfg); + const originlessProfileKey = + rawProfileKey && !rawProfileCfg?.apiBase ? rawProfileKey : undefined; + + if ( + state.apiBaseFromRepoLocal && + !state.explicitApiKey && + (ambientKey || originlessProfileKey) + ) { + throw new Error( + `Refusing to send ambient credentials to untrusted repo-local apiBase '${state.apiBase}'. Pass apiBase or apiKey explicitly if you trust this endpoint.`, + ); + } + + let token = + state.explicitApiKey ?? + (state.apiBaseFromRepoLocal ? undefined : (ambientKey ?? storedBoardAuthToken)); + let sendProfileHeader = false; + + if (state.profile) { + const profileOriginOk = rawProfileCfg?.apiBase + ? sameOriginUrl(rawProfileCfg.apiBase, state.apiBase) + : !state.apiBaseFromRepoLocal; + const trustedProfileKey = profileOriginOk ? rawProfileKey : undefined; + if (trustedProfileKey) { + token = state.explicitApiKey ?? trustedProfileKey; + } else { + sendProfileHeader = true; + } + } + + if (token) { + headers.authorization = `Bearer ${token}`; + } + if (sendProfileHeader && state.profile) { + headers["x-paperclip-actor-profile"] = state.profile; + } + if (state.scopes) { + headers["x-paperclip-actor-scopes"] = JSON.stringify(state.scopes); + } + return headers; + }; + + const requestRaw = async ( + path: string, + init: RequestInit = {}, + ): Promise => { + const url = `${state.apiBase}${path.startsWith("/") ? path : `/${path}`}`; + const headers = new Headers(init.headers); + const authHeaders = resolveAuthHeaders(); + for (const [k, v] of Object.entries(authHeaders)) { + if (!headers.has(k)) { + headers.set(k, v); + } + } + if (init.body !== undefined && !headers.has("content-type")) { + headers.set("content-type", "application/json"); + } + + const res = await state.fetchImpl(url, { + ...init, + headers, + }); + if (!res.ok) { + throw await parseErrorResponse(res); + } + return res; + }; + + const requestJson = async ( + path: string, + init: RequestInit = {}, + ): Promise => { + const res = await requestRaw(path, init); + return (await res.json()) as T; + }; + + const resolveCompanyId = async (): Promise => { + if (state.cachedCompanyId) return state.cachedCompanyId; + if (state.companyPromise) return state.companyPromise; + + state.companyPromise = (async () => { + const nodeEnv = readNodeEnv(); + const storedCtx = readStoredContext(state.homeDir); + const companyRef = + state.companyArg ?? + nodeEnv.company ?? + storedCtx?.companyId ?? + storedCtx?.defaultCompanyId; + + if (companyRef && UUID_RE.test(companyRef.trim())) { + state.cachedCompanyId = companyRef.trim().toLowerCase(); + return state.cachedCompanyId; + } + + const qs = companyRef + ? `?company=${encodeURIComponent(companyRef.trim())}` + : ""; + const resolved = await requestJson( + `/api/companies/resolve-default${qs}`, + { method: "GET" }, + ); + state.cachedCompanyId = resolved.id; + return resolved.id; + })(); + + try { + return await state.companyPromise; + } catch (err) { + state.companyPromise = null; + throw err; + } + }; + + const buildClaimedTask = (initial: TaskClaimView): ClaimedTask => { + let currentClaimToken = initial.claimToken; + let currentClaimEpoch = initial.claimEpoch; + let currentLeaseExpiresAt = initial.leaseExpiresAt; + let currentTask = initial.issue; + + const claimed: ClaimedTask = { + get task() { + return currentTask; + }, + get claimToken() { + return currentClaimToken; + }, + get claimEpoch() { + return currentClaimEpoch; + }, + get leaseExpiresAt() { + return currentLeaseExpiresAt; + }, + cursor: initial.cursor, + + async renew(lease) { + const leaseSec = + lease !== undefined + ? Math.max(1, Math.round(parseDurationMs(lease) / 1000)) + : undefined; + const view = await requestJson( + `/api/issues/${encodeURIComponent(currentTask.id)}/claim/renew`, + { + method: "POST", + headers: { "x-paperclip-claim-token": currentClaimToken }, + body: JSON.stringify({ + claimToken: currentClaimToken, + claimEpoch: currentClaimEpoch, + ...(leaseSec !== undefined ? { leaseSec } : {}), + }), + }, + ); + currentTask = view.issue; + currentClaimToken = view.claimToken; + currentClaimEpoch = view.claimEpoch; + currentLeaseExpiresAt = view.leaseExpiresAt; + return view; + }, + + async release(comment) { + return requestJson<{ released: boolean; cursor: string }>( + `/api/issues/${encodeURIComponent(currentTask.id)}/claim/release`, + { + method: "POST", + headers: { "x-paperclip-claim-token": currentClaimToken }, + body: JSON.stringify({ + claimToken: currentClaimToken, + claimEpoch: currentClaimEpoch, + ...(comment !== undefined ? { comment } : {}), + }), + }, + ); + }, + + async complete(opts) { + const payload: TaskCompleteInput = + typeof opts === "string" + ? { message: opts } + : { ...(opts ?? {}) }; + const updated = await requestJson( + `/api/issues/${encodeURIComponent(currentTask.id)}/claim/complete`, + { + method: "POST", + headers: { "x-paperclip-claim-token": currentClaimToken }, + body: JSON.stringify({ + ...payload, + claimToken: currentClaimToken, + claimEpoch: currentClaimEpoch, + }), + }, + ); + currentTask = updated; + return updated; + }, + + async fail(reason, opts) { + const updated = await requestJson( + `/api/issues/${encodeURIComponent(currentTask.id)}/claim/fail`, + { + method: "POST", + headers: { "x-paperclip-claim-token": currentClaimToken }, + body: JSON.stringify({ + claimToken: currentClaimToken, + claimEpoch: currentClaimEpoch, + reason, + ...(opts?.requeue !== undefined ? { requeue: opts.requeue } : {}), + }), + }, + ); + currentTask = updated; + return updated; + }, + + async ask(question, opts) { + return requestJson( + `/api/issues/${encodeURIComponent(currentTask.id)}/ask`, + { + method: "POST", + headers: { "x-paperclip-claim-token": currentClaimToken }, + body: JSON.stringify({ + ...(opts ?? {}), + question, + claimToken: currentClaimToken, + }), + }, + ); + }, + + async confirm(prompt, opts) { + return requestJson( + `/api/issues/${encodeURIComponent(currentTask.id)}/confirm`, + { + method: "POST", + headers: { "x-paperclip-claim-token": currentClaimToken }, + body: JSON.stringify({ + ...(opts ?? {}), + prompt, + claimToken: currentClaimToken, + }), + }, + ); + }, + }; + + return claimed; + }; + + return { + as(profile, opts) { + return createHandle({ + ...state, + profile, + scopes: opts?.scopes, + cachedCompanyId: state.cachedCompanyId, + companyPromise: state.companyPromise, + }); + }, + + async whoami() { + const companyId = await resolveCompanyId(); + return requestJson( + `/api/whoami?companyId=${encodeURIComponent(companyId)}`, + { method: "GET" }, + ); + }, + + channels: { + async list(prefix) { + const companyId = await resolveCompanyId(); + const params = new URLSearchParams(); + if (prefix) params.set("prefix", prefix); + const qs = params.toString(); + const res = await requestJson<{ items: ChannelView[] } | ChannelView[]>( + `/api/companies/${encodeURIComponent(companyId)}/channels${qs ? `?${qs}` : ""}`, + { method: "GET" }, + ); + return Array.isArray(res) ? res : res.items; + }, + + async create(path, opts) { + const companyId = await resolveCompanyId(); + return requestJson( + `/api/companies/${encodeURIComponent(companyId)}/channels`, + { + method: "POST", + body: JSON.stringify({ + ...(opts ?? {}), + path, + }), + }, + ); + }, + + async ensure(path, opts) { + return this.create(path, opts); + }, + }, + + async post(channel, bodyOrOpts, maybeOpts) { + const companyId = await resolveCompanyId(); + const input: PostInput = + typeof bodyOrOpts === "string" + ? { ...(maybeOpts ?? {}), text: bodyOrOpts } + : bodyOrOpts; + const blocks = buildBlocksFromSchemaInput(input.blocks, input.schema); + const { schema: _ignoredSchema, ...rest } = input; + return requestJson( + `/api/companies/${encodeURIComponent(companyId)}/channels/posts`, + { + method: "POST", + body: JSON.stringify({ + ...rest, + channel, + ...(blocks ? { blocks } : {}), + }), + }, + ); + }, + + async reply(id, bodyOrOpts, maybeOpts) { + const input: ReplyInput = + typeof bodyOrOpts === "string" + ? { ...(maybeOpts ?? {}), body: bodyOrOpts } + : bodyOrOpts; + const blocks = buildBlocksFromSchemaInput(input.blocks, input.schema); + const bodyText = input.body ?? input.text ?? ""; + return requestJson( + `/api/issues/${encodeURIComponent(id)}/comments`, + { + method: "POST", + body: JSON.stringify({ + body: bodyText, + ...(input.labels ? { kvLabels: input.labels, labels: input.labels } : {}), + ...(blocks ? { blocks } : {}), + ...(input.after ? { afterCommentId: input.after, after: input.after } : {}), + ...(input.internal !== undefined ? { internal: input.internal } : {}), + ...(input.idempotencyKey + ? { + clientRequestId: input.idempotencyKey, + idempotencyKey: input.idempotencyKey, + } + : {}), + }), + }, + ); + }, + + async read(channelOrId, filters) { + if (isIssueReference(channelOrId)) { + const res = await requestJson( + `/api/issues/${encodeURIComponent(channelOrId)}?view=thread`, + { method: "GET" }, + ); + if ("kind" in res && res.kind === "thread") { + return res; + } + const issue = res as HeadlessIssueView; + const commentsRes = await requestJson< + CommentView[] | { items: CommentView[] } + >(`/api/issues/${encodeURIComponent(channelOrId)}/comments`, { + method: "GET", + }); + const comments = Array.isArray(commentsRes) + ? commentsRes + : commentsRes.items; + return { + kind: "thread", + issue, + comments, + interactions: [], + cursor: issue.cursor, + }; + } + + const companyId = await resolveCompanyId(); + const params = new URLSearchParams(); + params.set("channel", channelOrId); + appendMultiParam(params, "label", filters?.label); + appendMultiParam(params, "status", filters?.status); + if (filters?.after) params.set("after", filters.after); + if (filters?.limit !== undefined) { + params.set("limit", String(filters.limit)); + } + return requestJson( + `/api/companies/${encodeURIComponent(companyId)}/channels/threads?${params.toString()}`, + { method: "GET" }, + ); + }, + + async label(id, mutation) { + return requestJson<{ + id: string; + kvLabels: Record; + cursor: string; + }>(`/api/issues/${encodeURIComponent(id)}/kv-labels`, { + method: "PATCH", + body: JSON.stringify(mutation), + }); + }, + + tasks: { + async create(channelOrId, input, maybeOpts) { + if (isIssueReference(channelOrId)) { + const opts: CreateTaskInput = + typeof input === "string" + ? { ...(maybeOpts ?? {}), text: input } + : { ...(input ?? {}) }; + return requestJson( + `/api/issues/${encodeURIComponent(channelOrId)}`, + { + method: "PATCH", + body: JSON.stringify({ + status: "todo", + ...(opts.priority ? { priority: opts.priority } : {}), + ...(opts.labels ? { kvLabels: opts.labels, labels: opts.labels } : {}), + ...(opts.projectId !== undefined ? { projectId: opts.projectId } : {}), + ...(opts.board ? { scope: "board" } : {}), + ...(opts.assigneeAgentId !== undefined + ? { assigneeAgentId: opts.assigneeAgentId } + : {}), + ...(opts.for ? { for: opts.for } : {}), + ...(opts.resultSchema ? { resultSchema: opts.resultSchema } : {}), + }), + }, + ); + } + + const companyId = await resolveCompanyId(); + const opts: CreateTaskInput = + typeof input === "string" + ? { ...(maybeOpts ?? {}), text: input } + : { ...(input ?? {}) }; + if (opts.needs && opts.needs.length > 0) { + const batch = await requestJson( + `/api/companies/${encodeURIComponent(companyId)}/issues/batch`, + { + method: "POST", + body: JSON.stringify({ + channel: channelOrId, + ...(opts.projectId !== undefined ? { projectId: opts.projectId } : {}), + ...(opts.board !== undefined ? { board: opts.board } : {}), + ...(opts.idempotencyKey ? { idempotencyKey: opts.idempotencyKey } : {}), + tasks: [ + { + ...(opts.title !== undefined ? { title: opts.title } : {}), + ...(opts.text !== undefined ? { text: opts.text } : {}), + ...(opts.description !== undefined ? { description: opts.description } : {}), + ...(opts.priority !== undefined ? { priority: opts.priority } : {}), + ...(opts.labels !== undefined ? { labels: opts.labels } : {}), + ...(opts.tagLabels !== undefined ? { tagLabels: opts.tagLabels } : {}), + ...(opts.for !== undefined ? { for: opts.for } : {}), + ...(opts.assigneeAgentId !== undefined + ? { assigneeAgentId: opts.assigneeAgentId } + : {}), + ...(opts.resultSchema !== undefined ? { resultSchema: opts.resultSchema } : {}), + ...(opts.blocks !== undefined ? { blocks: opts.blocks } : {}), + ...(opts.board !== undefined ? { board: opts.board } : {}), + needs: opts.needs, + }, + ], + }), + }, + ); + return batch.tasks[0]!.issue; + } + return requestJson( + `/api/companies/${encodeURIComponent(companyId)}/channels/posts`, + { + method: "POST", + body: JSON.stringify({ + ...opts, + channel: channelOrId, + status: "todo", + }), + }, + ); + }, + + async createPlan(channel, tasks, opts) { + const companyId = await resolveCompanyId(); + return requestJson( + `/api/companies/${encodeURIComponent(companyId)}/issues/batch`, + { + method: "POST", + body: JSON.stringify({ + channel, + ...(opts?.projectId !== undefined + ? { projectId: opts.projectId } + : {}), + ...(opts?.board !== undefined ? { board: opts.board } : {}), + ...(opts?.idempotencyKey + ? { idempotencyKey: opts.idempotencyKey } + : {}), + tasks, + }), + }, + ); + }, + + async list(filters) { + const companyId = await resolveCompanyId(); + const params = new URLSearchParams(); + params.set("headless", "1"); + if (filters?.channel) params.set("channel", filters.channel); + appendMultiParam(params, "status", filters?.status ?? filters?.state); + appendMultiParam(params, "label", filters?.label); + if (filters?.assignee) params.set("assignee", filters.assignee); + if (filters?.project) params.set("project", filters.project); + if (filters?.ready !== undefined) { + params.set("ready", String(filters.ready)); + } + if (filters?.after) params.set("after", filters.after); + if (filters?.limit !== undefined) { + params.set("limit", String(filters.limit)); + } + const qs = params.toString(); + const res = await requestJson< + { items: HeadlessIssueView[]; cursor?: string } | HeadlessIssueView[] + >( + `/api/companies/${encodeURIComponent(companyId)}/issues${qs ? `?${qs}` : ""}`, + { method: "GET" }, + ); + if (Array.isArray(res)) { + return { + items: res, + cursor: res[res.length - 1]?.cursor ?? "evt_0", + }; + } + return { + items: res.items, + cursor: res.cursor ?? res.items[res.items.length - 1]?.cursor ?? "evt_0", + }; + }, + + async claim(idOrReadyQuery, maybeOpts) { + const companyId = await resolveCompanyId(); + const isId = typeof idOrReadyQuery === "string"; + const opts: TaskClaimOptions = isId + ? { ...(maybeOpts ?? {}) } + : { ...(idOrReadyQuery ?? {}), ready: true }; + + const labels = [ + ...(opts.labels ?? []), + ...(opts.label + ? Array.isArray(opts.label) + ? opts.label + : [opts.label] + : []), + ]; + const leaseSec = + opts.leaseSec ?? + (opts.lease !== undefined + ? Math.max(1, Math.round(parseDurationMs(opts.lease) / 1000)) + : undefined); + const waitSec = + opts.waitSec ?? + (opts.wait !== undefined + ? Math.max(0, parseDurationMs(opts.wait) / 1000) + : undefined); + + const body: Record = { + ...(isId ? { issueId: idOrReadyQuery } : { ready: opts.ready ?? true }), + ...(opts.channel ? { channel: opts.channel } : {}), + ...(opts.projectId ? { projectId: opts.projectId } : {}), + ...(labels.length > 0 ? { labels } : {}), + ...(leaseSec !== undefined ? { leaseSec } : {}), + ...(waitSec !== undefined ? { waitSec } : {}), + ...(opts.includeUntrusted !== undefined + ? { includeUntrusted: opts.includeUntrusted } + : {}), + }; + + const res = await requestRaw( + `/api/companies/${encodeURIComponent(companyId)}/tasks/claim`, + { + method: "POST", + body: JSON.stringify(body), + signal: opts.signal, + }, + ); + if (res.status === 204) { + return null; + } + const claimView = (await res.json()) as TaskClaimView; + return buildClaimedTask(claimView); + }, + }, + + async ask(id, question, opts) { + return requestJson( + `/api/issues/${encodeURIComponent(id)}/ask`, + { + method: "POST", + body: JSON.stringify({ + ...(opts ?? {}), + question, + }), + }, + ); + }, + + async confirm(id, prompt, opts) { + return requestJson( + `/api/issues/${encodeURIComponent(id)}/confirm`, + { + method: "POST", + body: JSON.stringify({ + ...(opts ?? {}), + prompt, + }), + }, + ); + }, + + async approve(id, opts) { + return requestJson( + `/api/issues/${encodeURIComponent(id)}/approve`, + { + method: "POST", + body: JSON.stringify(opts ?? {}), + }, + ); + }, + + async reject(id, opts) { + return requestJson( + `/api/issues/${encodeURIComponent(id)}/reject`, + { + method: "POST", + body: JSON.stringify(opts ?? {}), + }, + ); + }, + + schemas: { + async list() { + const companyId = await resolveCompanyId(); + const res = await requestJson< + CompanySchemaView[] | { items: CompanySchemaView[] } + >(`/api/companies/${encodeURIComponent(companyId)}/schemas`, { + method: "GET", + }); + return Array.isArray(res) ? res : res.items; + }, + + async get(ref) { + const companyId = await resolveCompanyId(); + return requestJson( + `/api/companies/${encodeURIComponent(companyId)}/schemas/${encodeURIComponent(ref)}`, + { method: "GET" }, + ); + }, + + async create(input) { + const companyId = await resolveCompanyId(); + return requestJson<{ schema: CompanySchemaView; created: boolean }>( + `/api/companies/${encodeURIComponent(companyId)}/schemas`, + { + method: "POST", + body: JSON.stringify(input), + }, + ); + }, + }, + + async schedule(target, opts) { + const companyId = await resolveCompanyId(); + return requestJson( + `/api/companies/${encodeURIComponent(companyId)}/schedules`, + { + method: "POST", + body: JSON.stringify({ + ...opts, + target, + }), + }, + ); + }, + + schedules: { + async list(filters) { + const companyId = await resolveCompanyId(); + const params = new URLSearchParams(); + if (filters?.target) params.set("target", filters.target); + const qs = params.toString(); + const res = await requestJson< + ScheduleView[] | { items: ScheduleView[] } + >( + `/api/companies/${encodeURIComponent(companyId)}/schedules${qs ? `?${qs}` : ""}`, + { method: "GET" }, + ); + return Array.isArray(res) ? res : res.items; + }, + + async cancel(id) { + const companyId = await resolveCompanyId(); + return requestJson<{ cancelled: boolean }>( + `/api/companies/${encodeURIComponent(companyId)}/schedules/${encodeURIComponent(id)}`, + { method: "DELETE" }, + ); + }, + }, + + async wait(targetOrFilters, maybeFilters, opts) { + const companyId = await resolveCompanyId(); + let target: string | undefined; + let filters: EventWaitFilters = {}; + + if (typeof targetOrFilters === "string") { + target = targetOrFilters; + filters = maybeFilters ?? {}; + } else if (targetOrFilters && typeof targetOrFilters === "object") { + filters = targetOrFilters; + } else if (maybeFilters && typeof maybeFilters === "object") { + filters = maybeFilters; + } + + const params = new URLSearchParams(); + if (target) { + if (isIssueReference(target)) { + params.set("issueId", target); + } else { + params.set("channel", target); + } + } + if (filters.channel) params.set("channel", filters.channel); + if (filters.issueId) params.set("issueId", filters.issueId); + appendMultiParam(params, "event", filters.event); + appendMultiParam(params, "label", filters.label); + if (filters.mentions) params.set("mentions", filters.mentions); + if (filters.schema) params.set("schema", filters.schema); + if (filters.after) params.set("after", filters.after); + + const timeoutInput = opts?.timeout ?? filters.timeout; + const totalTimeoutMs = + timeoutInput !== undefined ? parseDurationMs(timeoutInput) : 60_000; + const deadline = Date.now() + Math.max(0, totalTimeoutMs); + const SERVER_MAX_WAIT_MS = 120_000; + let currentAfter = filters.after; + + while (true) { + if (opts?.signal?.aborted) { + throw new DOMException("The operation was aborted", "AbortError"); + } + const remainingMs = + totalTimeoutMs <= 0 ? 0 : Math.max(0, deadline - Date.now()); + const hopMs = + totalTimeoutMs <= 0 + ? 0 + : Math.min(Math.max(1, remainingMs), SERVER_MAX_WAIT_MS); + const hopParams = new URLSearchParams(params); + if (currentAfter) { + hopParams.set("after", currentAfter); + } + hopParams.set("timeoutMs", String(hopMs)); + + const res = await requestRaw( + `/api/companies/${encodeURIComponent(companyId)}/events/wait?${hopParams.toString()}`, + { + method: "GET", + signal: opts?.signal, + }, + ); + if (res.status !== 204) { + return (await res.json()) as BoardEventView; + } + const nextCursor = res.headers.get("x-paperclip-cursor")?.trim(); + if (!currentAfter && nextCursor) { + currentAfter = nextCursor; + } + if (totalTimeoutMs <= 0 || Date.now() >= deadline) { + return null; + } + } + }, + + async *events(filters, opts) { + const companyId = await resolveCompanyId(); + const params = new URLSearchParams(); + if (filters?.channel) params.set("channel", filters.channel); + if (filters?.issueId) params.set("issueId", filters.issueId); + appendMultiParam(params, "event", filters?.event); + appendMultiParam(params, "label", filters?.label); + if (filters?.mentions) params.set("mentions", filters.mentions); + if (filters?.schema) params.set("schema", filters.schema); + if (filters?.after) params.set("after", filters.after); + + const res = await requestRaw( + `/api/companies/${encodeURIComponent(companyId)}/events/stream?${params.toString()}`, + { + method: "GET", + headers: { accept: "text/event-stream" }, + signal: opts?.signal, + }, + ); + if (!res.body) { + return; + } + yield* parseSseEventStream(res.body, opts?.signal); + }, + }; +} + +export function paperclip(opts: PaperclipClientOptions = {}): PaperclipHandle { + const nodeEnv = readNodeEnv(); + const storedCtx = readStoredContext(opts.homeDir); + const trustedCtx = readTrustedContext(opts.homeDir); + + const rawApiBase = + opts.apiBase ?? + nodeEnv.apiBase ?? + storedCtx?.apiBase ?? + storedCtx?.apiUrl ?? + "http://127.0.0.1:3100"; + const apiBase = rawApiBase.replace(/\/+$/, ""); + const apiBaseFromRepoLocal = + !opts.apiBase && + !nodeEnv.apiBase && + Boolean(storedCtx?.fromRepoLocal) && + !sameOriginUrl(apiBase, trustedCtx?.apiBase ?? trustedCtx?.apiUrl); + + const profile = + opts.profile !== undefined + ? opts.profile + : nodeEnv.profile ?? storedCtx?.profile ?? null; + + const fetchImpl = opts.fetch ?? globalThis.fetch; + if (typeof fetchImpl !== "function") { + throw new Error( + "globalThis.fetch is unavailable; provide opts.fetch when creating a paperclip() client", + ); + } + + return createHandle({ + apiBase, + apiBaseFromRepoLocal, + explicitApiKey: opts.apiKey, + companyArg: opts.company, + profile, + scopes: opts.scopes, + fetchImpl, + homeDir: opts.homeDir, + cachedCompanyId: null, + companyPromise: null, + }); +} diff --git a/packages/shared/src/sdk/env.ts b/packages/shared/src/sdk/env.ts new file mode 100644 index 00000000000..f651aca6f5f --- /dev/null +++ b/packages/shared/src/sdk/env.ts @@ -0,0 +1,348 @@ +export interface StoredProfileConfig { + apiKey?: string; + agent_api_key?: string; + agentApiKey?: string; + token?: string; + apiBase?: string; + companyId?: string; +} + +export interface StoredContextConfig { + apiBase?: string; + apiUrl?: string; + apiKey?: string; + token?: string; + companyId?: string; + defaultCompanyId?: string; + profile?: string; + fromRepoLocal?: boolean; +} + +export function sameOriginUrl(a?: string, b?: string): boolean { + if (!a || !b) return false; + try { + return new URL(a).origin === new URL(b).origin; + } catch { + return false; + } +} + +interface MultiProfileContextFile { + version?: number; + currentProfile?: string; + profiles?: Record< + string, + { + apiBase?: string; + apiUrl?: string; + companyId?: string; + apiKey?: string; + token?: string; + apiKeyEnvVarName?: string; + } + >; +} + +export interface NodeRuntimeEnv { + apiBase?: string; + apiKey?: string; + company?: string; + profile?: string; +} + +interface NodeFsLike { + existsSync(path: string): boolean; + readFileSync(path: string, encoding: "utf8"): string; +} + +interface NodeOsLike { + homedir(): string; +} + +interface NodePathLike { + join(...parts: string[]): string; + dirname(p: string): string; + resolve(...parts: string[]): string; +} + +export function isNodeRuntime(): boolean { + return ( + typeof process !== "undefined" && + typeof process.versions === "object" && + process.versions !== null && + typeof process.versions.node === "string" + ); +} + +function getNodeBuiltin(name: string): T | null { + if (!isNodeRuntime()) return null; + const proc = process as unknown as { + getBuiltinModule?: (id: string) => unknown; + }; + if (typeof proc.getBuiltinModule !== "function") return null; + try { + return ( + (proc.getBuiltinModule(`node:${name}`) as T | undefined) ?? + (proc.getBuiltinModule(name) as T | undefined) ?? + null + ); + } catch { + return null; + } +} + +function readJsonFileSync(filePath: string): T | null { + const fs = getNodeBuiltin("fs"); + if (!fs) return null; + try { + const raw = fs.readFileSync(filePath, "utf8"); + const parsed = JSON.parse(raw) as unknown; + return typeof parsed === "object" && parsed !== null ? (parsed as T) : null; + } catch { + return null; + } +} + +function normalizeContextRecord( + raw: (StoredContextConfig & MultiProfileContextFile & { company?: string }) | null, + opts: { allowCredentials?: boolean } = {}, +): StoredContextConfig | null { + if (!raw) return null; + const allowCreds = opts.allowCredentials !== false; + if (raw.profiles && typeof raw.profiles === "object") { + const activeName = + (typeof raw.currentProfile === "string" && raw.currentProfile.trim()) || + "default"; + const entry = + raw.profiles[activeName] ?? + raw.profiles.default ?? + Object.values(raw.profiles)[0]; + if (entry && typeof entry === "object") { + const envKey = + allowCreds && typeof entry.apiKeyEnvVarName === "string" && isNodeRuntime() + ? process.env?.[entry.apiKeyEnvVarName]?.trim() || undefined + : undefined; + return { + apiBase: entry.apiBase ?? entry.apiUrl, + apiKey: allowCreds ? (entry.apiKey ?? entry.token ?? envKey ?? raw.apiKey) : undefined, + companyId: entry.companyId ?? raw.companyId, + }; + } + } + return { + apiBase: raw.apiBase ?? raw.apiUrl, + apiUrl: raw.apiUrl, + apiKey: allowCreds ? raw.apiKey : undefined, + token: allowCreds ? raw.token : undefined, + companyId: raw.companyId ?? raw.company, + defaultCompanyId: raw.defaultCompanyId, + profile: raw.profile, + }; +} + +function findRepoLocalContext( + fs: NodeFsLike, + path: NodePathLike, +): StoredContextConfig | null { + if (typeof process.cwd !== "function") return null; + let dir = path.resolve(process.cwd()); + let dotFileFallback: StoredContextConfig | null = null; + for (let depth = 0; depth < 12; depth++) { + const localCtx = normalizeContextRecord( + readJsonFileSync(path.join(dir, ".paperclip", "context.json")), + { allowCredentials: false }, + ); + if (localCtx && (localCtx.apiBase || localCtx.companyId)) { + return { ...localCtx, fromRepoLocal: true }; + } + if (!dotFileFallback) { + const dotFile = normalizeContextRecord( + readJsonFileSync(path.join(dir, ".paperclip.json")), + { allowCredentials: false }, + ); + if (dotFile && (dotFile.apiBase || dotFile.companyId)) { + dotFileFallback = { ...dotFile, fromRepoLocal: true }; + } + } + if (fs.existsSync(path.join(dir, ".git"))) { + break; + } + const parent = path.dirname(dir); + if (parent === dir) break; + dir = parent; + } + return dotFileFallback; +} + +export function readTrustedContext(homeDirOverride?: string): StoredContextConfig | null { + if (!isNodeRuntime()) return null; + const fs = getNodeBuiltin("fs"); + const os = getNodeBuiltin("os"); + const path = getNodeBuiltin("path"); + if (!fs || !os || !path) return null; + + if (homeDirOverride !== undefined) { + if (!homeDirOverride) return null; + return normalizeContextRecord( + readJsonFileSync(path.join(homeDirOverride, ".paperclip", "context.json")), + ); + } + + const envContextPath = process.env?.PAPERCLIP_CONTEXT?.trim(); + if (envContextPath) { + const fromEnvPath = normalizeContextRecord(readJsonFileSync(envContextPath)); + if (fromEnvPath) return fromEnvPath; + } + + const home = os.homedir(); + if (!home) return null; + return normalizeContextRecord( + readJsonFileSync(path.join(home, ".paperclip", "context.json")), + ); +} + +interface StoredBoardAuthFile { + credentials?: Record< + string, + { + apiBase?: unknown; + token?: unknown; + } + >; +} + +function normalizeStoreApiBase(apiBase: string): string { + return apiBase.trim().replace(/\/+$/, ""); +} + +export function readStoredBoardAuthToken( + apiBase: string, + homeDirOverride?: string, +): string | undefined { + if (!isNodeRuntime() || !apiBase.trim()) return undefined; + const os = getNodeBuiltin("os"); + const path = getNodeBuiltin("path"); + if (!os || !path) return undefined; + + let authPath: string | null = null; + if (homeDirOverride !== undefined) { + if (!homeDirOverride) return undefined; + authPath = path.join(homeDirOverride, ".paperclip", "auth.json"); + } else { + const envAuthStore = process.env?.PAPERCLIP_AUTH_STORE?.trim(); + if (envAuthStore) { + authPath = path.resolve(envAuthStore); + } else { + const envHome = process.env?.PAPERCLIP_HOME?.trim(); + if (envHome) { + authPath = path.join(path.resolve(envHome), "auth.json"); + } else { + const home = os.homedir(); + if (!home) return undefined; + authPath = path.join(home, ".paperclip", "auth.json"); + } + } + } + + const parsed = readJsonFileSync(authPath); + const credentials = parsed?.credentials; + if (!credentials || typeof credentials !== "object") return undefined; + + const targetBase = normalizeStoreApiBase(apiBase); + for (const [key, entry] of Object.entries(credentials)) { + if (!entry || typeof entry !== "object") continue; + const token = typeof entry.token === "string" && entry.token.trim() ? entry.token.trim() : undefined; + if (!token) continue; + const entryBase = + typeof entry.apiBase === "string" && entry.apiBase.trim() + ? normalizeStoreApiBase(entry.apiBase) + : normalizeStoreApiBase(key); + if (entryBase === targetBase) { + return token; + } + } + return undefined; +} + +export function readStoredContext(homeDirOverride?: string): StoredContextConfig | null { + if (!isNodeRuntime()) return null; + const fs = getNodeBuiltin("fs"); + const os = getNodeBuiltin("os"); + const path = getNodeBuiltin("path"); + if (!fs || !os || !path) return null; + + if (homeDirOverride !== undefined) { + return readTrustedContext(homeDirOverride); + } + + const envHome = process.env?.PAPERCLIP_HOME?.trim(); + if (!envHome) { + const repoLocal = findRepoLocalContext(fs, path); + if (repoLocal) return repoLocal; + } + + return readTrustedContext(); +} + +export function readStoredProfile( + profile: string, + homeDirOverride?: string, +): StoredProfileConfig | null { + if (!isNodeRuntime() || !profile) return null; + const fs = getNodeBuiltin("fs"); + const os = getNodeBuiltin("os"); + const path = getNodeBuiltin("path"); + if (!fs || !os || !path) return null; + const safeName = profile.replace(/[^a-zA-Z0-9._-]/g, ""); + if (!safeName) return null; + if (homeDirOverride !== undefined) { + if (!homeDirOverride) return null; + return readJsonFileSync( + path.join(homeDirOverride, ".paperclip", "profiles", `${safeName}.json`), + ); + } + const envHome = process.env?.PAPERCLIP_HOME?.trim(); + if (envHome) { + const fromEnvHome = readJsonFileSync( + path.join(envHome, "profiles", `${safeName}.json`), + ); + if (fromEnvHome) return fromEnvHome; + } + + let dir = path.resolve(process.cwd()); + for (let depth = 0; depth < 12; depth++) { + if (fs.existsSync(path.join(dir, ".paperclip", "context.json"))) { + const localProfile = readJsonFileSync( + path.join(dir, ".paperclip", "profiles", `${safeName}.json`), + ); + if (localProfile) return localProfile; + break; + } + if (fs.existsSync(path.join(dir, ".git"))) break; + const parent = path.dirname(dir); + if (parent === dir) break; + dir = parent; + } + + return readJsonFileSync( + path.join(os.homedir(), ".paperclip", "profiles", `${safeName}.json`), + ); +} + +export function extractProfileApiKey( + cfg: StoredProfileConfig | null, +): string | undefined { + if (!cfg) return undefined; + return cfg.agent_api_key ?? cfg.agentApiKey ?? cfg.apiKey ?? cfg.token; +} + +export function readNodeEnv(): NodeRuntimeEnv { + if (!isNodeRuntime()) return {}; + const env = process.env ?? {}; + return { + apiBase: env.PAPERCLIP_API_URL || undefined, + apiKey: env.PAPERCLIP_API_KEY || undefined, + company: env.PAPERCLIP_COMPANY_ID || undefined, + profile: env.PAPERCLIP_PROFILE || undefined, + }; +} diff --git a/packages/shared/src/sdk/index.ts b/packages/shared/src/sdk/index.ts new file mode 100644 index 00000000000..dedd01673f6 --- /dev/null +++ b/packages/shared/src/sdk/index.ts @@ -0,0 +1,23 @@ +export { paperclip } from "./client.js"; +export { + PaperclipError, + type ApproveRejectInput, + type ClaimedTask, + type CreateTaskInput, + type EventStreamFilters, + type EventWaitFilters, + type PaperclipClientOptions, + type PaperclipErrorInit, + type PaperclipHandle, + type PostInput, + type ReadFilters, + type ReplyInput, + type TaskClaimOptions, + type TaskListFilters, +} from "./types.js"; +export { + createInMemoryPaperclipBackend, + type InMemoryBackendOptions, + type InMemoryPaperclipBackend, +} from "./memory-backend.js"; +export * from "../headless/index.js"; diff --git a/packages/shared/src/sdk/lite.ts b/packages/shared/src/sdk/lite.ts new file mode 100644 index 00000000000..d4bbb9c4a95 --- /dev/null +++ b/packages/shared/src/sdk/lite.ts @@ -0,0 +1,73 @@ +export { paperclip } from "./client.js"; +export { + PaperclipError, + type ApproveRejectInput, + type ClaimedTask, + type CreateTaskInput, + type EventStreamFilters, + type EventWaitFilters, + type PaperclipClientOptions, + type PaperclipErrorInit, + type PaperclipHandle, + type PostInput, + type ReadFilters, + type ReplyInput, + type TaskClaimOptions, + type TaskListFilters, +} from "./types.js"; +export { parseSseEventStream } from "./sse.js"; +export { + CHANNEL_PATH_REGEX, + formatEventCursor, + normalizeChannelPath, + parseDurationMs, + parseEventCursor, + parseSchemaRef, + SCHEMA_NAME_REGEX, + SCHEMA_REF_REGEX, + splitMessageIntoTitleAndDescription, + type NormalizedChannelPath, + type ParsedSchemaRef, +} from "../headless/pure.js"; +export type { + AgentIdentityPolicy, + BatchCreatedTaskItem, + BatchCreateIssuesResult, + BoardEventActor, + BoardEventType, + BoardEventView, + ChannelOrdering, + ChannelPage, + ChannelPostInput, + ChannelQueueConfig, + ChannelView, + ChannelVisibility, + ClientScopes, + CommentView, + CompanyResolutionView, + CompanySchemaView, + CreateChannelInput, + CreateCompanySchemaInput, + HeadlessIssueView, + InteractionView, + IssueScope, + JsonSchemaObject, + JsonSchemaType, + JsonSchemaValidationResult, + KvLabelMutation, + LabelFilterExpr, + OneLineAskInput, + OneLineConfirmInput, + PlanTaskInput, + SchemaBlock, + SchedulePostInput, + ScheduleView, + TaskClaimRequest, + TaskClaimView, + TaskCompleteInput, + TaskFailInput, + TaskReleaseInput, + TaskRenewInput, + ThreadDetailView, + WhoAmIView, +} from "../headless/index.js"; diff --git a/packages/shared/src/sdk/memory-backend.ts b/packages/shared/src/sdk/memory-backend.ts new file mode 100644 index 00000000000..35d8403191d --- /dev/null +++ b/packages/shared/src/sdk/memory-backend.ts @@ -0,0 +1,2529 @@ +import { + applyKvLabelMutation, + BUILT_IN_COMPANY_SCHEMAS, + canonicalizeJsonSchema, + CHANNEL_VISIBILITIES, + channelPostInputSchema, + createChannelInputSchema, + createCompanySchemaInputSchema, + formatEventCursor, + KvLabelMutationSchema, + matchesLabelFilter, + normalizeChannelPath, + OneLineAskSchema, + OneLineConfirmSchema, + parseDurationMs, + parseEventCursor, + parseSchemaRef, + SchedulePostSchema, + SCHEMA_REF_REGEX, + splitMessageIntoTitleAndDescription, + TaskClaimRequestSchema, + TaskCompleteSchema, + TaskFailSchema, + TaskReleaseSchema, + TaskRenewSchema, + validateAgainstJsonSchema, + validateAndSortBatchPlan, + type AgentIdentityPolicy, + type BatchCreatedTaskItem, + type BatchCreateIssuesResult, + type BoardEventActor, + type BoardEventType, + type BoardEventView, + type ChannelPage, + type ChannelView, + type ClientScopes, + type CommentView, + type CompanyResolutionView, + type CompanySchemaView, + type HeadlessIssueView, + type InteractionView, + type IssueScope, + type SchemaBlock, + type ScheduleView, + type TaskClaimView, + type ThreadDetailView, + type WhoAmIView, +} from "../headless/index.js"; +import type { IssuePriority, IssueStatus } from "../constants.js"; + +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 interface InMemoryBackendOptions { + companyId?: string; + companyName?: string; + companyPrefix?: string; + agentIdentityPolicy?: AgentIdentityPolicy; + initialTimeMs?: number; +} + +interface StoredAgent { + id: string; + name: string; + role: string; + apiKey: string; +} + +interface StoredBoardToken { + token: string; + userId: string; + lockedProfile?: string; + scopes?: ClientScopes; +} + +interface StoredProject { + id: string; + slug: string; + name: string; +} + +interface StoredIssue extends HeadlessIssueView { + claimToken: string | null; + sourceTrust: string; +} + +interface StoredBatchIdempotency { + payloadHash: string; + result: BatchCreateIssuesResult; +} + +interface StoredChannel extends ChannelView { + members: Set; +} + +interface ResolvedActor { + principalType: "local_trusted" | "user" | "agent"; + userId: string | null; + agentId: string | null; + agentName: string | null; + actorProfile: string | null; + scopes: ClientScopes | null; +} + +const PRIORITY_RANK: Record = { + critical: 0, + high: 1, + medium: 2, + low: 3, +}; + +export interface InMemoryPaperclipBackend { + fetch: typeof globalThis.fetch; + companyId: string; + companyPrefix: string; + advanceTime(ms: number): number; + nowMs(): number; + expireLeases(): BoardEventView[]; + setPolicy(policy: AgentIdentityPolicy): void; + seedAgent(input: { + id?: string; + name: string; + role?: string; + apiKey: string; + }): StoredAgent; + seedBoardToken(input: StoredBoardToken): void; + seedProject(input: { id?: string; slug: string; name?: string }): StoredProject; + getState(): { + channels: ChannelView[]; + issues: HeadlessIssueView[]; + events: BoardEventView[]; + }; +} + +function makeUuid(counter: number): string { + const hex = counter.toString(16).padStart(12, "0"); + return `00000000-0000-4000-8000-${hex}`; +} + +function jsonResponse( + body: unknown, + status = 200, +): Response { + if (status === 204) { + return new Response(null, { status: 204 }); + } + return new Response(JSON.stringify(body), { + status, + headers: { "content-type": "application/json" }, + }); +} + +function errorResponse( + status: number, + error: string, + message: string, + extra?: Record, +): Response { + return jsonResponse({ error, message, ...(extra ?? {}) }, status); +} + +function channelMatchesPattern(channelPath: string, pattern: string): boolean { + if (pattern === "*" || pattern === channelPath) return true; + if (pattern.endsWith("/*")) { + const prefix = pattern.slice(0, -2); + return channelPath === prefix || channelPath.startsWith(`${prefix}/`); + } + if (pattern.endsWith("/")) { + const prefix = pattern.slice(0, -1); + return channelPath === prefix || channelPath.startsWith(`${prefix}/`); + } + return false; +} + +export function createInMemoryPaperclipBackend( + opts: InMemoryBackendOptions = {}, +): InMemoryPaperclipBackend { + let uuidSeq = 1; + let issueNumSeq = 0; + let eventSeq = 0; + let currentNowMs = opts.initialTimeMs ?? 1_770_000_000_000; + + const companyId = opts.companyId ?? makeUuid(uuidSeq++); + const companyName = opts.companyName ?? "Default"; + const companyPrefix = (opts.companyPrefix ?? "PAP").toUpperCase(); + let agentIdentityPolicy: AgentIdentityPolicy = + opts.agentIdentityPolicy ?? "open_local_profiles"; + + const agents = new Map(); + const boardTokens = new Map(); + const projects = new Map(); + const channels = new Map(); + const issues = new Map(); + const issueByIdentifier = new Map(); + const commentsByIssue = new Map(); + const interactionsByIssue = new Map(); + const schemasByRef = new Map(); + const schedules = new Map(); + const batchIdempotency = new Map(); + const postIdempotency = new Map(); + const commentIdempotency = new Map(); + const events: BoardEventView[] = []; + const listeners = new Set<(event: BoardEventView) => void>(); + + const nowIso = () => new Date(currentNowMs).toISOString(); + + for (const builtIn of BUILT_IN_COMPANY_SCHEMAS) { + schemasByRef.set(builtIn.ref, { + id: makeUuid(uuidSeq++), + companyId: null, + name: builtIn.name, + version: builtIn.version, + ref: builtIn.ref, + description: builtIn.description, + jsonSchema: builtIn.jsonSchema, + builtIn: true, + createdAt: nowIso(), + }); + } + + const publicIssueView = (issue: StoredIssue): HeadlessIssueView => { + const { claimToken: _hidden, sourceTrust: _trust, ...view } = issue; + return { + ...view, + kvLabels: { ...view.kvLabels }, + tagLabels: [...view.tagLabels], + blocks: [...view.blocks], + blockedByIssueIds: [...view.blockedByIssueIds], + }; + }; + + const emitEvent = ( + type: BoardEventType, + actor: ResolvedActor, + data: { + channel?: string | null; + issueId?: string | null; + identifier?: string | null; + payload?: Record; + }, + ): BoardEventView => { + eventSeq += 1; + const evt: BoardEventView = { + cursor: formatEventCursor(eventSeq), + seq: eventSeq, + type, + companyId, + channel: data.channel ?? null, + issueId: data.issueId ?? null, + identifier: data.identifier ?? null, + actor: { + type: actor.agentId ? "agent" : actor.userId ? "user" : "system", + id: actor.agentId ?? actor.userId, + name: actor.agentName, + profile: actor.actorProfile, + }, + payload: data.payload ?? {}, + createdAt: nowIso(), + }; + events.push(evt); + for (const listener of [...listeners]) { + listener(evt); + } + return evt; + }; + + const findIssue = (idOrIdentifier: string): StoredIssue | null => { + const trimmed = idOrIdentifier.trim(); + if (issues.has(trimmed)) return issues.get(trimmed)!; + const byId = issueByIdentifier.get(trimmed.toUpperCase()); + if (byId && issues.has(byId)) return issues.get(byId)!; + return null; + }; + + const findProject = (idOrSlug: string): StoredProject | null => { + const trimmed = idOrSlug.trim(); + for (const proj of projects.values()) { + if (proj.id === trimmed || proj.slug === trimmed) { + return proj; + } + } + return null; + }; + + const authenticate = ( + headers: Headers, + ): { ok: true; actor: ResolvedActor } | { ok: false; response: Response } => { + const authHeader = headers.get("authorization"); + const bearer = authHeader?.startsWith("Bearer ") + ? authHeader.slice(7).trim() + : null; + const requestedProfile = headers.get("x-paperclip-actor-profile")?.trim() || null; + const rawScopes = headers.get("x-paperclip-actor-scopes"); + let headerScopes: ClientScopes | null = null; + if (rawScopes) { + try { + headerScopes = JSON.parse(rawScopes) as ClientScopes; + } catch { + return { + ok: false, + response: errorResponse(400, "invalid_scopes", "Malformed X-Paperclip-Actor-Scopes header"), + }; + } + } + + if (bearer) { + for (const agent of agents.values()) { + if (agent.apiKey === bearer) { + return { + ok: true, + actor: { + principalType: "agent", + userId: null, + agentId: agent.id, + agentName: agent.name, + actorProfile: requestedProfile ?? agent.name, + scopes: headerScopes, + }, + }; + } + } + + const boardToken = boardTokens.get(bearer); + if (!boardToken) { + return { + ok: false, + response: errorResponse(401, "unauthorized", "Invalid bearer token"), + }; + } + + const effectiveProfile = boardToken.lockedProfile ?? requestedProfile; + if (effectiveProfile) { + const lower = effectiveProfile.toLowerCase(); + for (const agent of agents.values()) { + if (agent.name.toLowerCase() === lower) { + return { + ok: false, + response: errorResponse( + 409, + "profile_matches_registered_agent", + `Profile "${effectiveProfile}" matches registered agent @${agent.name}`, + { + next: [ + `pc agent connect ${agent.name}`, + `Pick a distinct profile name with --as`, + ], + }, + ), + }; + } + } + if (agentIdentityPolicy === "strict_agent_keys") { + return { + ok: false, + response: errorResponse( + 403, + "agent_key_required", + `Company policy strict_agent_keys requires a dedicated agent API key for profile "${effectiveProfile}"`, + { next: [`pc agent connect ${effectiveProfile}`] }, + ), + }; + } + } + + return { + ok: true, + actor: { + principalType: "user", + userId: boardToken.userId, + agentId: null, + agentName: null, + actorProfile: effectiveProfile, + scopes: boardToken.scopes ?? headerScopes, + }, + }; + } + + // No bearer token + if (agentIdentityPolicy !== "open_local_profiles") { + return { + ok: false, + response: errorResponse( + 401, + "unauthorized", + `Policy ${agentIdentityPolicy} rejects unauthenticated requests`, + { next: ["pc auth login"] }, + ), + }; + } + + if (requestedProfile) { + const lower = requestedProfile.toLowerCase(); + for (const agent of agents.values()) { + if (agent.name.toLowerCase() === lower) { + return { + ok: false, + response: errorResponse( + 409, + "profile_matches_registered_agent", + `Profile "${requestedProfile}" matches registered agent @${agent.name}`, + ), + }; + } + } + } + + return { + ok: true, + actor: { + principalType: "local_trusted", + userId: "local-board", + agentId: null, + agentName: null, + actorProfile: requestedProfile, + scopes: headerScopes, + }, + }; + }; + + const checkScopes = ( + actor: ResolvedActor, + action: string, + channelPath?: string | null, + ): Response | null => { + const scopes = actor.scopes; + if (!scopes) return null; + if (Array.isArray(scopes.actions) && !scopes.actions.includes(action)) { + return errorResponse( + 403, + "scope_denied", + `Token scopes do not allow action "${action}"`, + ); + } + if ( + channelPath && + Array.isArray(scopes.channels) && + !scopes.channels.some((pat) => channelMatchesPattern(channelPath, pat)) + ) { + return errorResponse( + 403, + "scope_denied", + `Token scopes do not allow channel "${channelPath}"`, + ); + } + return null; + }; + + const ensureChannel = ( + rawPath: string, + actor: ResolvedActor, + optsArg?: { + description?: string | null; + visibility?: "open" | "private"; + defaultProjectId?: string | null; + queueConfig?: ChannelView["queueConfig"]; + }, + ): StoredChannel => { + const { path } = normalizeChannelPath(rawPath, { allowSubtreePrefix: false }); + const existing = channels.get(path); + if (existing) { + existing.lastActivityAt = nowIso(); + existing.updatedAt = nowIso(); + if (optsArg?.description !== undefined) existing.description = optsArg.description; + if (optsArg?.visibility !== undefined) existing.visibility = optsArg.visibility; + if (optsArg?.defaultProjectId !== undefined) { + existing.defaultProjectId = optsArg.defaultProjectId; + } + if (optsArg?.queueConfig !== undefined) existing.queueConfig = optsArg.queueConfig; + return existing; + } + + // Inherit private visibility if any ancestor path is private + let inheritedPrivate = false; + const parts = path.split("/"); + for (let i = 1; i < parts.length; i += 1) { + const parentPath = parts.slice(0, i).join("/"); + const parent = channels.get(parentPath); + if (parent?.visibility === "private") { + inheritedPrivate = true; + break; + } + } + + const visibility = + optsArg?.visibility ?? (inheritedPrivate ? "private" : "open"); + const ts = nowIso(); + const created: StoredChannel = { + id: makeUuid(uuidSeq++), + companyId, + path, + description: optsArg?.description ?? null, + visibility: CHANNEL_VISIBILITIES.includes(visibility) ? visibility : "open", + defaultProjectId: optsArg?.defaultProjectId ?? null, + queueConfig: optsArg?.queueConfig ?? {}, + threadCount: 0, + openTaskCount: 0, + readyTaskCount: 0, + lastActivityAt: ts, + createdAt: ts, + updatedAt: ts, + members: new Set( + [actor.userId, actor.agentId].filter((v): v is string => Boolean(v)), + ), + }; + channels.set(path, created); + return created; + }; + + const validateBlocks = (blocks: SchemaBlock[] | undefined): Response | null => { + if (!blocks || blocks.length === 0) return null; + for (const block of blocks) { + const ref = `${block.schema}@${block.version}`; + const schemaEntry = schemasByRef.get(ref); + if (!schemaEntry) { + return errorResponse( + 404, + "schema_not_found", + `Schema "${ref}" is not registered`, + ); + } + const check = validateAgainstJsonSchema(schemaEntry.jsonSchema, block.data); + if (!check.valid) { + return errorResponse( + 400, + "invalid_schema_block", + `Block ${ref} failed schema validation: ${check.errors.join("; ")}`, + { errors: check.errors, schema: ref }, + ); + } + } + return null; + }; + + const isTaskBlocked = (issue: StoredIssue): boolean => { + if (issue.blockedByIssueIds.length === 0) return false; + return issue.blockedByIssueIds.some((blockerId) => { + const blocker = issues.get(blockerId); + return blocker ? blocker.status !== "done" : true; + }); + }; + + const isTaskReadyInPool = (issue: StoredIssue): boolean => { + if (issue.scope === "chat") return false; + if (issue.status !== "todo") return false; + if (issue.assigneeAgentId !== null || issue.assigneeUserId !== null) { + return false; + } + if (issue.claimToken !== null || issue.claimLeaseExpiresAt !== null) { + return false; + } + if (isTaskBlocked(issue)) return false; + return true; + }; + + const refreshChannelCounts = (ch: StoredChannel): void => { + let threads = 0; + let openTasks = 0; + let readyTasks = 0; + for (const issue of issues.values()) { + if (issue.channelId !== ch.id) continue; + threads += 1; + if (issue.status !== "done" && issue.status !== "cancelled") { + openTasks += 1; + } + if (isTaskReadyInPool(issue)) { + readyTasks += 1; + } + } + ch.threadCount = threads; + ch.openTaskCount = openTasks; + ch.readyTaskCount = readyTasks; + }; + + const unblockDependents = (completedIssue: StoredIssue, actor: ResolvedActor): void => { + for (const candidate of issues.values()) { + if (!candidate.blockedByIssueIds.includes(completedIssue.id)) continue; + if (!isTaskBlocked(candidate) && candidate.status === "todo") { + candidate.cursor = formatEventCursor(eventSeq + 1); + emitEvent("task.unblocked", actor, { + channel: candidate.channel, + issueId: candidate.id, + identifier: candidate.identifier, + payload: { unblockedBy: completedIssue.identifier }, + }); + if (isTaskReadyInPool(candidate)) { + candidate.cursor = formatEventCursor(eventSeq + 1); + emitEvent("task.ready", actor, { + channel: candidate.channel, + issueId: candidate.id, + identifier: candidate.identifier, + payload: {}, + }); + } + } + } + }; + + const expireLeases = (): BoardEventView[] => { + const emitted: BoardEventView[] = []; + const sysActor: ResolvedActor = { + principalType: "local_trusted", + userId: null, + agentId: null, + agentName: "lease-reconciler", + actorProfile: null, + scopes: null, + }; + + for (const issue of issues.values()) { + if (issue.status !== "in_progress" || !issue.claimLeaseExpiresAt) continue; + const expMs = Date.parse(issue.claimLeaseExpiresAt); + if (Number.isFinite(expMs) && expMs <= currentNowMs) { + const ch = issue.channel ? channels.get(issue.channel) : undefined; + const maxAttempts = ch?.queueConfig.maxClaimAttempts ?? 3; + issue.claimEpoch += 1; + issue.claimToken = null; + issue.claimHolderAgentId = null; + issue.claimHolderUserId = null; + issue.claimHolderProfile = null; + issue.claimLeaseExpiresAt = null; + issue.updatedAt = nowIso(); + + if (issue.claimAttemptCount >= maxAttempts) { + issue.status = "blocked"; + const evt = emitEvent("task.lease_poison_blocked", sysActor, { + channel: issue.channel, + issueId: issue.id, + identifier: issue.identifier, + payload: { attemptCount: issue.claimAttemptCount, maxAttempts }, + }); + issue.cursor = evt.cursor; + emitted.push(evt); + } else { + issue.status = "todo"; + const evtExpired = emitEvent("task.lease_expired_requeued", sysActor, { + channel: issue.channel, + issueId: issue.id, + identifier: issue.identifier, + payload: { attemptCount: issue.claimAttemptCount }, + }); + const evtReady = emitEvent("task.ready", sysActor, { + channel: issue.channel, + issueId: issue.id, + identifier: issue.identifier, + payload: { requeued: true }, + }); + issue.cursor = evtReady.cursor; + emitted.push(evtExpired, evtReady); + } + } + } + return emitted; + }; + + const matchesEventFilters = ( + evt: BoardEventView, + params: URLSearchParams, + ): boolean => { + const issueIdParam = params.get("issueId"); + if (issueIdParam) { + const target = findIssue(issueIdParam); + if (target) { + if (evt.issueId !== target.id) return false; + } else if (evt.issueId !== issueIdParam && evt.identifier !== issueIdParam.toUpperCase()) { + return false; + } + } + + const channelParam = params.get("channel"); + if (channelParam) { + const norm = normalizeChannelPath(channelParam, { allowSubtreePrefix: true }); + if (!evt.channel) return false; + if (norm.isSubtreePrefix) { + if (evt.channel !== norm.path && !evt.channel.startsWith(`${norm.path}/`)) { + return false; + } + } else if (evt.channel !== norm.path) { + return false; + } + } + + const eventTypes = params.getAll("event"); + if (eventTypes.length > 0 && !eventTypes.includes(evt.type)) { + return false; + } + + const labelFilters = params.getAll("label"); + if (labelFilters.length > 0) { + const issue = evt.issueId ? issues.get(evt.issueId) : undefined; + if (!issue) return false; + if ( + !labelFilters.every((expr) => + matchesLabelFilter(issue.kvLabels, issue.tagLabels, expr), + ) + ) { + return false; + } + } + + const schemaParam = params.get("schema"); + if (schemaParam) { + const issue = evt.issueId ? issues.get(evt.issueId) : undefined; + const issueMatch = issue?.blocks.some( + (b) => `${b.schema}@${b.version}` === schemaParam, + ); + const payloadBlocks = Array.isArray(evt.payload?.blocks) + ? (evt.payload.blocks as SchemaBlock[]) + : []; + const payloadMatch = payloadBlocks.some( + (b) => `${b.schema}@${b.version}` === schemaParam, + ); + if (!issueMatch && !payloadMatch) return false; + } + + return true; + }; + + const checkClaimMutationAuth = ( + issue: StoredIssue, + actor: ResolvedActor, + claimTokenHeader: string | null, + bodyToken: string | undefined, + bodyEpoch: number | undefined, + ): Response | null => { + expireLeases(); + if (issue.status !== "in_progress") { + return errorResponse( + 409, + "claim_lost", + "Task is no longer in progress", + { claimEpoch: issue.claimEpoch, status: issue.status }, + ); + } + const token = claimTokenHeader ?? bodyToken ?? null; + if (!token || !issue.claimToken || token !== issue.claimToken) { + return errorResponse( + 409, + "claim_lost", + "Task claim token is invalid, expired, or superseded", + { claimEpoch: issue.claimEpoch }, + ); + } + if (bodyEpoch !== undefined && bodyEpoch !== issue.claimEpoch) { + return errorResponse( + 409, + "claim_lost", + "Task claim epoch has changed", + { claimEpoch: issue.claimEpoch }, + ); + } + if ( + agentIdentityPolicy === "delegated_profiles" && + actor.actorProfile && + issue.claimHolderProfile && + actor.actorProfile !== issue.claimHolderProfile + ) { + return errorResponse( + 403, + "profile_mismatch", + `Claim is held by profile "${issue.claimHolderProfile}", not "${actor.actorProfile}"`, + ); + } + return null; + }; + + const fetchHandler: typeof globalThis.fetch = async (input, init) => { + const reqUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + const url = new URL(reqUrl, "http://127.0.0.1:3100"); + const method = (init?.method ?? "GET").toUpperCase(); + const headers = new Headers(init?.headers); + const pathname = url.pathname; + + let bodyJson: unknown = undefined; + if (typeof init?.body === "string" && init.body.length > 0) { + try { + bodyJson = JSON.parse(init.body); + } catch { + return errorResponse(400, "invalid_json", "Invalid JSON request body"); + } + } + + const auth = authenticate(headers); + if (!auth.ok) return auth.response; + const actor = auth.actor; + + // 1. Resolve default company + if (method === "GET" && pathname === "/api/companies/resolve-default") { + const requested = url.searchParams.get("company")?.trim(); + if (requested) { + if ( + requested.toLowerCase() !== companyId && + requested.toUpperCase() !== companyPrefix + ) { + return errorResponse( + 404, + "company_not_found", + `Company "${requested}" not found`, + ); + } + } + const res: CompanyResolutionView = { + id: companyId, + name: companyName, + issuePrefix: companyPrefix, + agentIdentityPolicy, + }; + return jsonResponse(res); + } + + // 2. WhoAmI + if (method === "GET" && pathname === "/api/whoami") { + const res: WhoAmIView = { + apiBase: url.origin, + companyId, + companyPrefix, + companyName, + principalType: actor.principalType, + userId: actor.userId, + agentId: actor.agentId, + agentName: actor.agentName, + actorProfile: actor.actorProfile, + agentIdentityPolicy, + scopes: actor.scopes, + }; + return jsonResponse(res); + } + + // 3. Channels list & create + const channelsMatch = /^\/api\/companies\/([^/]+)\/channels$/.exec(pathname); + if (channelsMatch) { + if (channelsMatch[1] !== companyId) { + return errorResponse(404, "company_not_found", "Company not found"); + } + if (method === "GET") { + const scopeErr = checkScopes(actor, "read"); + if (scopeErr) return scopeErr; + const prefixParam = url.searchParams.get("prefix"); + const prefixNorm = prefixParam + ? normalizeChannelPath(prefixParam, { allowSubtreePrefix: true }) + : null; + const items: ChannelView[] = []; + for (const ch of channels.values()) { + if (prefixNorm) { + if ( + ch.path !== prefixNorm.path && + !ch.path.startsWith(`${prefixNorm.path}/`) + ) { + continue; + } + } + refreshChannelCounts(ch); + const { members: _m, ...view } = ch; + items.push(view); + } + items.sort((a, b) => a.path.localeCompare(b.path)); + return jsonResponse({ items }); + } + if (method === "POST") { + const parsed = createChannelInputSchema.safeParse(bodyJson); + if (!parsed.success) { + return errorResponse(400, "validation_error", parsed.error.message); + } + const scopeErr = checkScopes(actor, "post", parsed.data.path); + if (scopeErr) return scopeErr; + const ch = ensureChannel(parsed.data.path, actor, parsed.data); + refreshChannelCounts(ch); + const { members: _m, ...view } = ch; + return jsonResponse(view, 201); + } + } + + // 4. Channel threads list + const threadsMatch = /^\/api\/companies\/([^/]+)\/channels\/threads$/.exec(pathname); + if (threadsMatch && method === "GET") { + if (threadsMatch[1] !== companyId) { + return errorResponse(404, "company_not_found", "Company not found"); + } + const rawChannel = url.searchParams.get("channel") ?? "general"; + const norm = normalizeChannelPath(rawChannel, { allowSubtreePrefix: true }); + const scopeErr = checkScopes(actor, "read", norm.path); + if (scopeErr) return scopeErr; + + const labelFilters = url.searchParams.getAll("label"); + const statusFilters = url.searchParams.getAll("status"); + const afterCursor = url.searchParams.get("after"); + const afterSeq = afterCursor ? parseEventCursor(afterCursor) : null; + const limit = Number.parseInt(url.searchParams.get("limit") ?? "50", 10); + + const matchedIssues: ChannelPage["items"] = []; + for (const issue of issues.values()) { + if (!issue.channel) continue; + if (norm.isSubtreePrefix) { + if ( + issue.channel !== norm.path && + !issue.channel.startsWith(`${norm.path}/`) + ) { + continue; + } + } else if (issue.channel !== norm.path) { + continue; + } + if (statusFilters.length > 0 && !statusFilters.includes(issue.status)) { + continue; + } + if ( + labelFilters.length > 0 && + !labelFilters.every((expr) => + matchesLabelFilter(issue.kvLabels, issue.tagLabels, expr), + ) + ) { + continue; + } + if (afterSeq !== null) { + const issueSeq = parseEventCursor(issue.cursor) ?? 0; + if (issueSeq <= afterSeq) continue; + } + const comments = commentsByIssue.get(issue.id) ?? []; + matchedIssues.push({ + ...publicIssueView(issue), + replyCount: comments.length, + latestReply: comments.length > 0 ? comments[comments.length - 1]! : null, + }); + } + + const sliced = matchedIssues.slice(0, Math.max(1, limit)); + const page: ChannelPage = { + kind: "channel", + channel: norm.isSubtreePrefix ? `${norm.path}/` : norm.path, + items: sliced, + cursor: formatEventCursor(eventSeq), + }; + return jsonResponse(page); + } + + // 5. Channel posts (and tasks.create in channel) + const postsMatch = /^\/api\/companies\/([^/]+)\/channels\/posts$/.exec(pathname); + if (postsMatch && method === "POST") { + if (postsMatch[1] !== companyId) { + return errorResponse(404, "company_not_found", "Company not found"); + } + const rawBody = (bodyJson ?? {}) as Record; + const requestedStatus: IssueStatus = + rawBody.status === "todo" ? "todo" : "backlog"; + const resultSchemaRef = + typeof rawBody.resultSchema === "string" ? rawBody.resultSchema : undefined; + if (resultSchemaRef && !SCHEMA_REF_REGEX.test(resultSchemaRef.trim())) { + return errorResponse(400, "invalid_schema_ref", `Invalid resultSchema "${resultSchemaRef}"`); + } + + const { + status: _s, + resultSchema: _rs, + for: _for, + assigneeAgentId: rawAssigneeAgentId, + ...restForPostSchema + } = rawBody; + const parsed = channelPostInputSchema.safeParse(restForPostSchema); + if (!parsed.success) { + return errorResponse(400, "validation_error", parsed.error.message); + } + + const scopeErr = checkScopes( + actor, + requestedStatus === "todo" ? "create_task" : "post", + parsed.data.channel, + ); + if (scopeErr) return scopeErr; + + if (parsed.data.idempotencyKey && postIdempotency.has(parsed.data.idempotencyKey)) { + const existingId = postIdempotency.get(parsed.data.idempotencyKey)!; + const existingIssue = issues.get(existingId)!; + return jsonResponse(publicIssueView(existingIssue), 200); + } + + const combinedBlocks: SchemaBlock[] = [...(parsed.data.blocks ?? [])]; + if (parsed.data.schema) { + const sRef = parseSchemaRef(parsed.data.schema.ref); + combinedBlocks.push({ + schema: sRef.name, + version: sRef.version, + data: parsed.data.schema.data, + }); + } + const blockErr = validateBlocks(combinedBlocks); + if (blockErr) return blockErr; + + const ch = ensureChannel(parsed.data.channel, actor); + const rawText = parsed.data.text ?? parsed.data.description ?? ""; + let title: string; + let description: string | null; + if (parsed.data.title && parsed.data.title.trim()) { + title = parsed.data.title.trim(); + description = rawText.trim() ? rawText : null; + } else { + const fallback = combinedBlocks[0] + ? `[${combinedBlocks[0].schema}@${combinedBlocks[0].version}]` + : "Untitled post"; + const split = splitMessageIntoTitleAndDescription(rawText, fallback); + title = split.title; + description = split.description; + } + + let resolvedProjectId: string | null = ch.defaultProjectId; + if (parsed.data.projectId !== undefined) { + if (parsed.data.projectId === null) { + resolvedProjectId = null; + } else { + const proj = findProject(parsed.data.projectId); + resolvedProjectId = proj ? proj.id : parsed.data.projectId; + } + } + + issueNumSeq += 1; + const id = makeUuid(uuidSeq++); + const identifier = `${companyPrefix}-${issueNumSeq}`; + const ts = nowIso(); + const scope: IssueScope = parsed.data.board ? "board" : "channel"; + const assigneeAgentId = + typeof rawAssigneeAgentId === "string" ? rawAssigneeAgentId : null; + + const stored: StoredIssue = { + id, + companyId, + identifier, + title, + description, + status: requestedStatus, + scope, + priority: parsed.data.priority ?? "medium", + channelId: ch.id, + channel: ch.path, + projectId: resolvedProjectId, + assigneeAgentId, + assigneeUserId: null, + actorProfile: actor.actorProfile, + kvLabels: { ...(parsed.data.labels ?? {}) }, + tagLabels: [...(parsed.data.tagLabels ?? [])], + blocks: combinedBlocks, + resultSchemaRef: resultSchemaRef ?? null, + blockedByIssueIds: [], + isPassivePost: requestedStatus === "backlog" && assigneeAgentId === null, + claimEpoch: 0, + claimHolderProfile: null, + claimHolderAgentId: null, + claimHolderUserId: null, + claimLeaseExpiresAt: null, + claimAttemptCount: 0, + cursor: "evt_0", + createdAt: ts, + updatedAt: ts, + claimToken: null, + sourceTrust: parsed.data.sourceTrust ?? "trusted", + }; + + issues.set(id, stored); + issueByIdentifier.set(identifier, id); + if (parsed.data.idempotencyKey) { + postIdempotency.set(parsed.data.idempotencyKey, id); + } + + const primaryEvent = emitEvent( + requestedStatus === "todo" ? "task.created" : "thread.posted", + actor, + { + channel: ch.path, + issueId: id, + identifier, + payload: { + blocks: combinedBlocks, + labels: stored.kvLabels, + }, + }, + ); + stored.cursor = primaryEvent.cursor; + if (requestedStatus === "todo" && isTaskReadyInPool(stored)) { + const readyEvt = emitEvent("task.ready", actor, { + channel: ch.path, + issueId: id, + identifier, + payload: {}, + }); + stored.cursor = readyEvt.cursor; + } + + return jsonResponse(publicIssueView(stored), 201); + } + + // 6. Batch task DAG plan + const batchMatch = /^\/api\/companies\/([^/]+)\/issues\/batch$/.exec(pathname); + if (batchMatch && method === "POST") { + if (batchMatch[1] !== companyId) { + return errorResponse(404, "company_not_found", "Company not found"); + } + + const sortedResult = validateAndSortBatchPlan(bodyJson); + if (!sortedResult.ok) { + return errorResponse(400, sortedResult.code, sortedResult.message, { + duplicateKeys: sortedResult.duplicateKeys, + unknownDependencies: sortedResult.unknownDependencies, + cycleKeys: sortedResult.cycleKeys, + }); + } + + const scopeErr = checkScopes( + actor, + "create_task", + sortedResult.channel ?? null, + ); + if (scopeErr) return scopeErr; + + if (sortedResult.idempotencyKey) { + const payloadHash = JSON.stringify(bodyJson); + const existing = batchIdempotency.get(sortedResult.idempotencyKey); + if (existing) { + if (existing.payloadHash !== payloadHash) { + return errorResponse( + 409, + "duplicate_idempotency_key", + `Idempotency key "${sortedResult.idempotencyKey}" already used with a different payload`, + ); + } + return jsonResponse({ ...existing.result, idempotentReplay: true }, 200); + } + } + + // Resolve projectIds upfront before mutating + const resolvedTaskProjectIds = new Map(); + const ch = sortedResult.channel + ? ensureChannel(sortedResult.channel, actor) + : null; + + for (const task of sortedResult.tasks) { + if (task.projectId === null) { + resolvedTaskProjectIds.set(task.index, null); + } else if (task.projectId !== undefined) { + const proj = findProject(task.projectId); + if (!proj && projects.size > 0 && !UUID_RE.test(task.projectId)) { + return errorResponse( + 404, + "project_not_found", + `Project "${task.projectId}" not found`, + ); + } + resolvedTaskProjectIds.set(task.index, proj ? proj.id : task.projectId); + } else { + resolvedTaskProjectIds.set(task.index, ch?.defaultProjectId ?? null); + } + } + + const createdByKey = new Map(); + const createdItems: BatchCreatedTaskItem[] = []; + + for (const task of sortedResult.tasks) { + const blockErr = validateBlocks(task.blocks); + if (blockErr) return blockErr; + + const blockedByIssueIds: string[] = []; + for (const depKey of task.localNeeds) { + const depIssue = createdByKey.get(depKey); + if (depIssue) blockedByIssueIds.push(depIssue.id); + } + for (const extRef of task.externalNeeds) { + const extIssue = findIssue(extRef); + if (!extIssue) { + return errorResponse( + 404, + "issue_not_found", + `External dependency "${extRef}" not found`, + ); + } + blockedByIssueIds.push(extIssue.id); + } + + issueNumSeq += 1; + const id = makeUuid(uuidSeq++); + const identifier = `${companyPrefix}-${issueNumSeq}`; + const ts = nowIso(); + const scope: IssueScope = task.board ? "board" : ch ? "channel" : "board"; + + const stored: StoredIssue = { + id, + companyId, + identifier, + title: task.title, + description: task.description, + status: "todo", + scope, + priority: task.priority, + channelId: ch?.id ?? null, + channel: ch?.path ?? null, + projectId: resolvedTaskProjectIds.get(task.index) ?? null, + assigneeAgentId: task.assigneeAgentId ?? null, + assigneeUserId: null, + actorProfile: actor.actorProfile, + kvLabels: { ...task.labels }, + tagLabels: [...task.tagLabels], + blocks: [...task.blocks], + resultSchemaRef: task.resultSchema ?? null, + blockedByIssueIds, + isPassivePost: false, + claimEpoch: 0, + claimHolderProfile: null, + claimHolderAgentId: null, + claimHolderUserId: null, + claimLeaseExpiresAt: null, + claimAttemptCount: 0, + cursor: "evt_0", + createdAt: ts, + updatedAt: ts, + claimToken: null, + sourceTrust: "trusted", + }; + + issues.set(id, stored); + issueByIdentifier.set(identifier, id); + if (task.key) createdByKey.set(task.key, stored); + + const evt = emitEvent("task.created", actor, { + channel: stored.channel, + issueId: id, + identifier, + payload: { key: task.key, blockedByIssueIds }, + }); + stored.cursor = evt.cursor; + if (isTaskReadyInPool(stored)) { + const readyEvt = emitEvent("task.ready", actor, { + channel: stored.channel, + issueId: id, + identifier, + payload: {}, + }); + stored.cursor = readyEvt.cursor; + } + + createdItems.push({ + key: task.key, + id, + identifier, + cursor: stored.cursor, + issue: publicIssueView(stored), + }); + } + + const result: BatchCreateIssuesResult = { + tasks: createdItems, + cursor: formatEventCursor(eventSeq), + idempotentReplay: false, + }; + if (sortedResult.idempotencyKey) { + batchIdempotency.set(sortedResult.idempotencyKey, { + payloadHash: JSON.stringify(bodyJson), + result, + }); + } + return jsonResponse(result, 201); + } + + // 7. Issues list + const issuesListMatch = /^\/api\/companies\/([^/]+)\/issues$/.exec(pathname); + if (issuesListMatch && method === "GET") { + if (issuesListMatch[1] !== companyId) { + return errorResponse(404, "company_not_found", "Company not found"); + } + const scopeErr = checkScopes(actor, "read"); + if (scopeErr) return scopeErr; + + const channelParam = url.searchParams.get("channel"); + const channelNorm = channelParam + ? normalizeChannelPath(channelParam, { allowSubtreePrefix: true }) + : null; + const statusFilters = url.searchParams.getAll("status"); + const labelFilters = url.searchParams.getAll("label"); + const projectFilter = url.searchParams.get("project"); + const readyFilter = url.searchParams.get("ready") === "true"; + + const items: HeadlessIssueView[] = []; + for (const issue of issues.values()) { + if (channelNorm) { + if (!issue.channel) continue; + if (channelNorm.isSubtreePrefix) { + if ( + issue.channel !== channelNorm.path && + !issue.channel.startsWith(`${channelNorm.path}/`) + ) { + continue; + } + } else if (issue.channel !== channelNorm.path) { + continue; + } + } + if (statusFilters.length > 0 && !statusFilters.includes(issue.status)) { + continue; + } + if ( + labelFilters.length > 0 && + !labelFilters.every((expr) => + matchesLabelFilter(issue.kvLabels, issue.tagLabels, expr), + ) + ) { + continue; + } + if (projectFilter) { + const proj = findProject(projectFilter); + const expectedId = proj ? proj.id : projectFilter; + if (issue.projectId !== expectedId) continue; + } + if (readyFilter && !isTaskReadyInPool(issue)) { + continue; + } + items.push(publicIssueView(issue)); + } + return jsonResponse({ items, cursor: formatEventCursor(eventSeq) }); + } + + // 8. Issue detail / patch + const singleIssueMatch = /^\/api\/issues\/([^/]+)$/.exec(pathname); + if (singleIssueMatch) { + const issue = findIssue(decodeURIComponent(singleIssueMatch[1]!)); + if (!issue) { + return errorResponse(404, "issue_not_found", "Issue not found"); + } + if (method === "GET") { + const scopeErr = checkScopes(actor, "read", issue.channel); + if (scopeErr) return scopeErr; + const detail: ThreadDetailView = { + kind: "thread", + issue: publicIssueView(issue), + comments: [...(commentsByIssue.get(issue.id) ?? [])], + interactions: [...(interactionsByIssue.get(issue.id) ?? [])], + cursor: formatEventCursor(eventSeq), + }; + return jsonResponse(detail); + } + if (method === "PATCH") { + const scopeErr = checkScopes(actor, "create_task", issue.channel); + if (scopeErr) return scopeErr; + const patch = (bodyJson ?? {}) as Record; + const prevStatus = issue.status; + if (typeof patch.status === "string") { + issue.status = patch.status as IssueStatus; + if (issue.status !== "in_progress" && issue.claimToken !== null) { + issue.claimToken = null; + issue.claimHolderAgentId = null; + issue.claimHolderUserId = null; + issue.claimHolderProfile = null; + issue.claimLeaseExpiresAt = null; + } + } + if (typeof patch.priority === "string") { + issue.priority = patch.priority as IssuePriority; + } + if (typeof patch.scope === "string") { + issue.scope = patch.scope as IssueScope; + } + if (patch.projectId !== undefined) { + if (patch.projectId === null) { + issue.projectId = null; + } else if (typeof patch.projectId === "string") { + const proj = findProject(patch.projectId); + issue.projectId = proj ? proj.id : patch.projectId; + } + } + if (patch.labels && typeof patch.labels === "object") { + Object.assign(issue.kvLabels, patch.labels); + } + if (typeof patch.resultSchema === "string") { + issue.resultSchemaRef = patch.resultSchema; + } + if (patch.assigneeAgentId !== undefined) { + issue.assigneeAgentId = + typeof patch.assigneeAgentId === "string" ? patch.assigneeAgentId : null; + } + issue.isPassivePost = + issue.status === "backlog" && + issue.assigneeAgentId === null && + issue.assigneeUserId === null; + issue.updatedAt = nowIso(); + if (prevStatus === "backlog" && issue.status === "todo" && isTaskReadyInPool(issue)) { + const evt = emitEvent("task.ready", actor, { + channel: issue.channel, + issueId: issue.id, + identifier: issue.identifier, + payload: { promotedFromBacklog: true }, + }); + issue.cursor = evt.cursor; + } + return jsonResponse(publicIssueView(issue)); + } + } + + // 9. Comments (reply) + const commentsMatch = /^\/api\/issues\/([^/]+)\/comments$/.exec(pathname); + if (commentsMatch) { + const issue = findIssue(decodeURIComponent(commentsMatch[1]!)); + if (!issue) { + return errorResponse(404, "issue_not_found", "Issue not found"); + } + if (method === "GET") { + return jsonResponse({ items: commentsByIssue.get(issue.id) ?? [] }); + } + if (method === "POST") { + const scopeErr = checkScopes(actor, "post", issue.channel); + if (scopeErr) return scopeErr; + const body = (bodyJson ?? {}) as Record; + const idempKey = + typeof body.idempotencyKey === "string" + ? body.idempotencyKey + : typeof body.clientRequestId === "string" + ? body.clientRequestId + : undefined; + if (idempKey && commentIdempotency.has(idempKey)) { + return jsonResponse(commentIdempotency.get(idempKey)!, 200); + } + + const existingComments = commentsByIssue.get(issue.id) ?? []; + const afterId = + typeof body.afterCommentId === "string" + ? body.afterCommentId + : typeof body.after === "string" + ? body.after + : undefined; + if (afterId) { + const latest = + existingComments.length > 0 + ? existingComments[existingComments.length - 1]!.id + : null; + if (latest !== afterId) { + return errorResponse( + 409, + "newer_message", + "Newer comments have been posted since the provided cursor", + { latestCommentId: latest }, + ); + } + } + + const blocks = Array.isArray(body.blocks) + ? (body.blocks as SchemaBlock[]) + : undefined; + const blockErr = validateBlocks(blocks); + if (blockErr) return blockErr; + + const kvLabels = + body.kvLabels && typeof body.kvLabels === "object" + ? (body.kvLabels as Record) + : {}; + + const comment: CommentView = { + id: makeUuid(uuidSeq++), + issueId: issue.id, + identifier: issue.identifier, + body: typeof body.body === "string" ? body.body : "", + authorType: actor.agentId ? "agent" : "user", + authorUserId: actor.userId, + authorAgentId: actor.agentId, + actorProfile: actor.actorProfile, + kvLabels, + blocks: blocks ?? [], + internal: Boolean(body.internal), + cursor: "evt_0", + createdAt: nowIso(), + }; + existingComments.push(comment); + commentsByIssue.set(issue.id, existingComments); + + const evt = emitEvent("comment.posted", actor, { + channel: issue.channel, + issueId: issue.id, + identifier: issue.identifier, + payload: { commentId: comment.id, blocks: comment.blocks }, + }); + comment.cursor = evt.cursor; + issue.cursor = evt.cursor; + issue.updatedAt = nowIso(); + if (idempKey) { + commentIdempotency.set(idempKey, comment); + } + return jsonResponse(comment, 201); + } + } + + // 10. CAS kv-labels + const kvLabelsMatch = /^\/api\/issues\/([^/]+)\/kv-labels$/.exec(pathname); + if (kvLabelsMatch && method === "PATCH") { + const issue = findIssue(decodeURIComponent(kvLabelsMatch[1]!)); + if (!issue) { + return errorResponse(404, "issue_not_found", "Issue not found"); + } + const scopeErr = checkScopes(actor, "label", issue.channel); + if (scopeErr) return scopeErr; + + // Check reserved label prefix explicitly to return 400 reserved_label + const rawMut = (bodyJson ?? {}) as Record; + for (const field of ["set", "unset"] as const) { + const val = rawMut[field]; + const keys = + field === "set" && val && typeof val === "object" + ? Object.keys(val) + : field === "unset" && Array.isArray(val) + ? val.filter((k): k is string => typeof k === "string") + : []; + if (keys.some((k) => k.startsWith("paperclip."))) { + return errorResponse( + 400, + "reserved_label", + "Label keys starting with 'paperclip.' are reserved for server metadata", + ); + } + } + + const parsed = KvLabelMutationSchema.safeParse(bodyJson); + if (!parsed.success) { + return errorResponse(400, "validation_error", parsed.error.message); + } + + const applied = applyKvLabelMutation(issue.kvLabels, parsed.data); + if (!applied.ok) { + return errorResponse( + 409, + "label_conflict", + `Compare-and-swap failed on keys: ${applied.conflictingKeys.join(", ")}`, + { conflictingKeys: applied.conflictingKeys }, + ); + } + + issue.kvLabels = applied.labels; + issue.updatedAt = nowIso(); + const evt = emitEvent("labels.changed", actor, { + channel: issue.channel, + issueId: issue.id, + identifier: issue.identifier, + payload: { kvLabels: issue.kvLabels }, + }); + issue.cursor = evt.cursor; + return jsonResponse({ + id: issue.id, + kvLabels: { ...issue.kvLabels }, + cursor: evt.cursor, + }); + } + + // 11. Claim task (specific or ready pool pop) + const claimMatch = /^\/api\/companies\/([^/]+)\/tasks\/claim$/.exec(pathname); + if (claimMatch && method === "POST") { + if (claimMatch[1] !== companyId) { + return errorResponse(404, "company_not_found", "Company not found"); + } + expireLeases(); + const parsed = TaskClaimRequestSchema.safeParse(bodyJson ?? {}); + if (!parsed.success) { + return errorResponse(400, "validation_error", parsed.error.message); + } + + const reqData = parsed.data; + const scopeErr = checkScopes(actor, "claim", reqData.channel ?? null); + if (scopeErr) return scopeErr; + + const tryClaim = (): { claim?: TaskClaimView; error?: Response } => { + expireLeases(); + let target: StoredIssue | null = null; + + if (reqData.issueId) { + const found = findIssue(reqData.issueId); + if (!found) { + return { + error: errorResponse( + 404, + "issue_not_found", + `Task "${reqData.issueId}" not found`, + ), + }; + } + if (found.status === "done" || found.status === "cancelled") { + return { + error: errorResponse(409, "task_finished", "Task is already finished"), + }; + } + if (found.status === "blocked") { + return { + error: errorResponse(409, "task_blocked", "Task is blocked"), + }; + } + if (found.assigneeAgentId || found.assigneeUserId) { + if (found.assigneeAgentId !== actor.agentId) { + return { + error: errorResponse( + 409, + "task_assigned", + "Task is assigned to another actor", + ), + }; + } + } + if (found.claimToken !== null || found.status === "in_progress") { + return { + error: errorResponse(409, "task_claimed", "Task is already claimed"), + }; + } + if (isTaskBlocked(found)) { + return { + error: errorResponse( + 409, + "task_waiting", + "Task has unresolved blockers", + ), + }; + } + if (found.status !== "todo") { + return { + error: errorResponse( + 409, + "task_not_ready", + `Task status is "${found.status}", expected "todo"`, + ), + }; + } + target = found; + } else { + const channelNorm = reqData.channel + ? normalizeChannelPath(reqData.channel, { allowSubtreePrefix: true }) + : null; + const projectMatchId = reqData.projectId + ? findProject(reqData.projectId)?.id ?? reqData.projectId + : null; + const labelFilters = reqData.labels ?? []; + + const candidates: StoredIssue[] = []; + for (const issue of issues.values()) { + if (!isTaskReadyInPool(issue)) continue; + if (!reqData.includeUntrusted && issue.sourceTrust !== "trusted") { + continue; + } + if (channelNorm) { + if (!issue.channel) continue; + if (channelNorm.isSubtreePrefix) { + if ( + issue.channel !== channelNorm.path && + !issue.channel.startsWith(`${channelNorm.path}/`) + ) { + continue; + } + } else if (issue.channel !== channelNorm.path) { + continue; + } + } + if (projectMatchId && issue.projectId !== projectMatchId) continue; + if ( + labelFilters.length > 0 && + !labelFilters.every((expr) => + matchesLabelFilter(issue.kvLabels, issue.tagLabels, expr), + ) + ) { + continue; + } + candidates.push(issue); + } + + const chObj = + channelNorm && !channelNorm.isSubtreePrefix + ? channels.get(channelNorm.path) + : undefined; + const ordering = chObj?.queueConfig.ordering ?? "priority_fifo"; + candidates.sort((a, b) => { + if (ordering === "priority_fifo") { + const pDiff = PRIORITY_RANK[a.priority] - PRIORITY_RANK[b.priority]; + if (pDiff !== 0) return pDiff; + } + const tDiff = a.createdAt.localeCompare(b.createdAt); + if (tDiff !== 0) return tDiff; + return a.id.localeCompare(b.id); + }); + + target = candidates[0] ?? null; + } + + if (!target) { + return {}; + } + + const ch = target.channel ? channels.get(target.channel) : undefined; + const defaultLeaseSec = ch?.queueConfig.defaultLeaseSec ?? 300; + const requestedLeaseSec = + reqData.leaseSec ?? + (reqData.lease !== undefined + ? Math.max(1, Math.round(parseDurationMs(reqData.lease) / 1000)) + : defaultLeaseSec); + const maxLeaseSec = ch?.queueConfig.maxLeaseSec ?? 3600; + const leaseSec = Math.min(requestedLeaseSec, maxLeaseSec); + + const claimToken = `clm_${makeUuid(uuidSeq++)}`; + target.status = "in_progress"; + target.claimEpoch += 1; + target.claimToken = claimToken; + target.claimHolderAgentId = actor.agentId; + target.claimHolderUserId = actor.userId; + target.claimHolderProfile = actor.actorProfile; + target.claimLeaseExpiresAt = new Date( + currentNowMs + leaseSec * 1000, + ).toISOString(); + target.claimAttemptCount += 1; + target.updatedAt = nowIso(); + + const evt = emitEvent("task.claimed", actor, { + channel: target.channel, + issueId: target.id, + identifier: target.identifier, + payload: { + claimEpoch: target.claimEpoch, + leaseExpiresAt: target.claimLeaseExpiresAt, + }, + }); + target.cursor = evt.cursor; + + return { + claim: { + issue: publicIssueView(target), + claimToken, + claimEpoch: target.claimEpoch, + leaseExpiresAt: target.claimLeaseExpiresAt, + cursor: evt.cursor, + }, + }; + }; + + const first = tryClaim(); + if (first.error) return first.error; + if (first.claim) return jsonResponse(first.claim, 200); + + const waitMs = + reqData.waitSec !== undefined + ? Math.max(0, reqData.waitSec * 1000) + : reqData.wait !== undefined + ? parseDurationMs(reqData.wait) + : 0; + if (waitMs <= 0) { + return jsonResponse(null, 204); + } + + return new Promise((resolve) => { + let settled = false; + const cleanup = () => { + listeners.delete(onEvent); + clearTimeout(timer); + init?.signal?.removeEventListener("abort", onAbort); + }; + const onAbort = () => { + if (settled) return; + settled = true; + cleanup(); + resolve(jsonResponse(null, 204)); + }; + const onEvent = (evt: BoardEventView) => { + if (settled) return; + if ( + evt.type !== "task.ready" && + evt.type !== "task.created" && + evt.type !== "task.unblocked" + ) { + return; + } + const attempt = tryClaim(); + if (attempt.claim) { + settled = true; + cleanup(); + resolve(jsonResponse(attempt.claim, 200)); + } + }; + const timer = setTimeout(() => { + if (settled) return; + settled = true; + cleanup(); + resolve(jsonResponse(null, 204)); + }, waitMs); + + if (init?.signal?.aborted) { + onAbort(); + return; + } + init?.signal?.addEventListener("abort", onAbort, { once: true }); + listeners.add(onEvent); + }); + } + + // 12. Renew / Release / Complete / Fail claim + const claimActionMatch = /^\/api\/issues\/([^/]+)\/claim\/(renew|release|complete|fail)$/.exec( + pathname, + ); + if (claimActionMatch && method === "POST") { + const issue = findIssue(decodeURIComponent(claimActionMatch[1]!)); + if (!issue) { + return errorResponse(404, "issue_not_found", "Issue not found"); + } + const action = claimActionMatch[2]!; + const claimTokenHeader = headers.get("x-paperclip-claim-token"); + + if (action === "renew") { + const parsed = TaskRenewSchema.safeParse(bodyJson ?? {}); + if (!parsed.success) { + return errorResponse(400, "validation_error", parsed.error.message); + } + const authErr = checkClaimMutationAuth( + issue, + actor, + claimTokenHeader, + parsed.data.claimToken, + parsed.data.claimEpoch, + ); + if (authErr) return authErr; + + const ch = issue.channel ? channels.get(issue.channel) : undefined; + const maxLeaseSec = ch?.queueConfig.maxLeaseSec ?? 3600; + const leaseSec = Math.min( + parsed.data.leaseSec ?? + (parsed.data.lease !== undefined + ? Math.max(1, Math.round(parseDurationMs(parsed.data.lease) / 1000)) + : ch?.queueConfig.defaultLeaseSec ?? 300), + maxLeaseSec, + ); + issue.claimLeaseExpiresAt = new Date( + currentNowMs + leaseSec * 1000, + ).toISOString(); + issue.updatedAt = nowIso(); + const evt = emitEvent("task.lease_renewed", actor, { + channel: issue.channel, + issueId: issue.id, + identifier: issue.identifier, + payload: { leaseExpiresAt: issue.claimLeaseExpiresAt }, + }); + issue.cursor = evt.cursor; + return jsonResponse({ + issue: publicIssueView(issue), + claimToken: issue.claimToken!, + claimEpoch: issue.claimEpoch, + leaseExpiresAt: issue.claimLeaseExpiresAt, + cursor: evt.cursor, + } satisfies TaskClaimView); + } + + if (action === "release") { + const parsed = TaskReleaseSchema.safeParse(bodyJson ?? {}); + if (!parsed.success) { + return errorResponse(400, "validation_error", parsed.error.message); + } + const authErr = checkClaimMutationAuth( + issue, + actor, + claimTokenHeader, + parsed.data.claimToken, + parsed.data.claimEpoch, + ); + if (authErr) return authErr; + + issue.status = "todo"; + issue.claimEpoch += 1; + issue.claimToken = null; + issue.claimHolderAgentId = null; + issue.claimHolderUserId = null; + issue.claimHolderProfile = null; + issue.claimLeaseExpiresAt = null; + issue.updatedAt = nowIso(); + emitEvent("task.lease_released", actor, { + channel: issue.channel, + issueId: issue.id, + identifier: issue.identifier, + payload: { comment: parsed.data.comment ?? null }, + }); + const readyEvt = emitEvent("task.ready", actor, { + channel: issue.channel, + issueId: issue.id, + identifier: issue.identifier, + payload: {}, + }); + issue.cursor = readyEvt.cursor; + return jsonResponse({ released: true, cursor: readyEvt.cursor }); + } + + if (action === "complete") { + const parsed = TaskCompleteSchema.safeParse(bodyJson ?? {}); + if (!parsed.success) { + return errorResponse(400, "validation_error", parsed.error.message); + } + const authErr = checkClaimMutationAuth( + issue, + actor, + claimTokenHeader, + parsed.data.claimToken, + parsed.data.claimEpoch, + ); + if (authErr) return authErr; + + if ( + issue.resultSchemaRef && + parsed.data.resultSchema && + parsed.data.resultSchema !== issue.resultSchemaRef + ) { + return errorResponse( + 409, + "result_schema_mismatch", + `Task requires saved result schema "${issue.resultSchemaRef}", not "${parsed.data.resultSchema}"`, + ); + } + + const completionBlocks: SchemaBlock[] = [...(parsed.data.blocks ?? [])]; + if (parsed.data.data && issue.resultSchemaRef) { + const refParsed = parseSchemaRef(issue.resultSchemaRef); + completionBlocks.push({ + schema: refParsed.name, + version: refParsed.version, + data: parsed.data.data, + }); + } else if (parsed.data.data && parsed.data.resultSchema) { + const refParsed = parseSchemaRef(parsed.data.resultSchema); + completionBlocks.push({ + schema: refParsed.name, + version: refParsed.version, + data: parsed.data.data, + }); + } + + if (issue.resultSchemaRef) { + const expected = parseSchemaRef(issue.resultSchemaRef); + const matchingBlock = completionBlocks.find( + (b) => b.schema === expected.name && b.version === expected.version, + ); + if (!matchingBlock) { + return errorResponse( + 422, + "missing_or_invalid_result_schema", + `Task requires completion data matching schema "${issue.resultSchemaRef}"`, + ); + } + const schemaEntry = schemasByRef.get(issue.resultSchemaRef); + if (!schemaEntry) { + return errorResponse( + 422, + "missing_or_invalid_result_schema", + `Schema "${issue.resultSchemaRef}" is not registered`, + ); + } + const check = validateAgainstJsonSchema( + schemaEntry.jsonSchema, + matchingBlock.data, + ); + if (!check.valid) { + return errorResponse( + 422, + "missing_or_invalid_result_schema", + `Result data failed schema ${issue.resultSchemaRef}: ${check.errors.join("; ")}`, + { errors: check.errors }, + ); + } + } + + const blockErr = validateBlocks(completionBlocks); + if (blockErr) return blockErr; + + if (parsed.data.prUrl) { + issue.kvLabels["paperclip.pr"] = parsed.data.prUrl; + } + if (completionBlocks.length > 0) { + issue.blocks.push(...completionBlocks); + } + + const note = parsed.data.message ?? parsed.data.comment; + if (note || completionBlocks.length > 0) { + const list = commentsByIssue.get(issue.id) ?? []; + list.push({ + id: makeUuid(uuidSeq++), + issueId: issue.id, + identifier: issue.identifier, + body: note ?? `Completed (${issue.resultSchemaRef ?? "done"})`, + authorType: actor.agentId ? "agent" : "user", + authorUserId: actor.userId, + authorAgentId: actor.agentId, + actorProfile: actor.actorProfile, + kvLabels: {}, + blocks: completionBlocks, + internal: false, + cursor: formatEventCursor(eventSeq + 1), + createdAt: nowIso(), + }); + commentsByIssue.set(issue.id, list); + } + + issue.status = "done"; + issue.claimEpoch += 1; + issue.claimToken = null; + issue.claimHolderAgentId = null; + issue.claimHolderUserId = null; + issue.claimHolderProfile = null; + issue.claimLeaseExpiresAt = null; + issue.updatedAt = nowIso(); + + const evt = emitEvent("task.completed", actor, { + channel: issue.channel, + issueId: issue.id, + identifier: issue.identifier, + payload: { blocks: completionBlocks, prUrl: parsed.data.prUrl ?? null }, + }); + issue.cursor = evt.cursor; + unblockDependents(issue, actor); + return jsonResponse(publicIssueView(issue)); + } + + if (action === "fail") { + const parsed = TaskFailSchema.safeParse(bodyJson ?? {}); + if (!parsed.success) { + return errorResponse(400, "validation_error", parsed.error.message); + } + const authErr = checkClaimMutationAuth( + issue, + actor, + claimTokenHeader, + parsed.data.claimToken, + parsed.data.claimEpoch, + ); + if (authErr) return authErr; + + const ch = issue.channel ? channels.get(issue.channel) : undefined; + const maxAttempts = ch?.queueConfig.maxClaimAttempts ?? 3; + const shouldRequeue = + Boolean(parsed.data.requeue) && issue.claimAttemptCount < maxAttempts; + + issue.status = shouldRequeue ? "todo" : "blocked"; + issue.claimEpoch += 1; + issue.claimToken = null; + issue.claimHolderAgentId = null; + issue.claimHolderUserId = null; + issue.claimHolderProfile = null; + issue.claimLeaseExpiresAt = null; + issue.updatedAt = nowIso(); + + const failEvt = emitEvent("task.failed", actor, { + channel: issue.channel, + issueId: issue.id, + identifier: issue.identifier, + payload: { reason: parsed.data.reason, requeued: shouldRequeue }, + }); + if (shouldRequeue) { + const readyEvt = emitEvent("task.ready", actor, { + channel: issue.channel, + issueId: issue.id, + identifier: issue.identifier, + payload: { requeued: true }, + }); + issue.cursor = readyEvt.cursor; + } else { + const blockedEvt = emitEvent("task.blocked", actor, { + channel: issue.channel, + issueId: issue.id, + identifier: issue.identifier, + payload: { reason: parsed.data.reason }, + }); + issue.cursor = blockedEvt.cursor; + } + void failEvt; + return jsonResponse(publicIssueView(issue)); + } + } + + // 13. Ask / Confirm / Approve / Reject + const interactionMatch = /^\/api\/issues\/([^/]+)\/(ask|confirm|approve|reject)$/.exec( + pathname, + ); + if (interactionMatch && method === "POST") { + const issue = findIssue(decodeURIComponent(interactionMatch[1]!)); + if (!issue) { + return errorResponse(404, "issue_not_found", "Issue not found"); + } + const action = interactionMatch[2]!; + const list = interactionsByIssue.get(issue.id) ?? []; + + if (action === "ask") { + const parsed = OneLineAskSchema.safeParse(bodyJson ?? {}); + if (!parsed.success) { + return errorResponse(400, "validation_error", parsed.error.message); + } + const hadPoolLease = issue.claimToken !== null && issue.assigneeAgentId === null; + if (hadPoolLease) { + issue.claimEpoch += 1; + issue.claimToken = null; + issue.claimHolderAgentId = null; + issue.claimHolderUserId = null; + issue.claimHolderProfile = null; + issue.claimLeaseExpiresAt = null; + } + issue.status = "in_review"; + issue.updatedAt = nowIso(); + const interaction: InteractionView = { + id: makeUuid(uuidSeq++), + issueId: issue.id, + identifier: issue.identifier, + kind: "ask_user_questions", + status: "pending", + prompt: parsed.data.question, + choices: parsed.data.choices, + resolverPolicy: parsed.data.humanOnly ? "human_only" : "anyone", + continuationPolicy: + parsed.data.continuationPolicy ?? + (hadPoolLease || issue.assigneeAgentId === null + ? "requeue_on_resolve" + : "wake_assignee"), + cursor: "evt_0", + createdAt: nowIso(), + resolvedAt: null, + }; + list.push(interaction); + interactionsByIssue.set(issue.id, list); + const evt = emitEvent("interaction.created", actor, { + channel: issue.channel, + issueId: issue.id, + identifier: issue.identifier, + payload: { interactionId: interaction.id, kind: interaction.kind }, + }); + interaction.cursor = evt.cursor; + issue.cursor = evt.cursor; + return jsonResponse(interaction, 201); + } + + if (action === "confirm") { + const parsed = OneLineConfirmSchema.safeParse(bodyJson ?? {}); + if (!parsed.success) { + return errorResponse(400, "validation_error", parsed.error.message); + } + const hadPoolLease = issue.claimToken !== null && issue.assigneeAgentId === null; + if (hadPoolLease) { + issue.claimEpoch += 1; + issue.claimToken = null; + issue.claimHolderAgentId = null; + issue.claimHolderUserId = null; + issue.claimHolderProfile = null; + issue.claimLeaseExpiresAt = null; + } + issue.status = "in_review"; + issue.updatedAt = nowIso(); + const interaction: InteractionView = { + id: makeUuid(uuidSeq++), + issueId: issue.id, + identifier: issue.identifier, + kind: "request_confirmation", + status: "pending", + prompt: parsed.data.prompt, + resolverPolicy: parsed.data.humanOnly ? "human_only" : "anyone", + continuationPolicy: + parsed.data.continuationPolicy ?? + (hadPoolLease || issue.assigneeAgentId === null + ? "requeue_on_resolve" + : parsed.data.wakeOnAccept + ? "wake_assignee_on_accept" + : "wake_assignee"), + cursor: "evt_0", + createdAt: nowIso(), + resolvedAt: null, + }; + list.push(interaction); + interactionsByIssue.set(issue.id, list); + const evt = emitEvent("interaction.created", actor, { + channel: issue.channel, + issueId: issue.id, + identifier: issue.identifier, + payload: { interactionId: interaction.id, kind: interaction.kind }, + }); + interaction.cursor = evt.cursor; + issue.cursor = evt.cursor; + return jsonResponse(interaction, 201); + } + + if (action === "approve" || action === "reject") { + const body = (bodyJson ?? {}) as { + note?: string; + reason?: string; + interactionId?: string; + }; + const pending = [...list] + .reverse() + .find( + (item) => + item.status === "pending" && + (!body.interactionId || item.id === body.interactionId), + ); + if (!pending) { + return errorResponse( + 404, + "interaction_not_found", + "No pending interaction found on this issue", + ); + } + if (pending.resolverPolicy === "human_only" && actor.agentId !== null) { + return errorResponse( + 403, + "human_only_interaction", + "Only a human user may resolve this interaction", + ); + } + pending.status = action === "approve" ? "accepted" : "rejected"; + pending.note = body.note ?? body.reason ?? null; + pending.resolvedAt = nowIso(); + + const resEvt = emitEvent("interaction.resolved", actor, { + channel: issue.channel, + issueId: issue.id, + identifier: issue.identifier, + payload: { interactionId: pending.id, status: pending.status }, + }); + pending.cursor = resEvt.cursor; + issue.cursor = resEvt.cursor; + + if (pending.continuationPolicy === "requeue_on_resolve" && action === "approve") { + issue.status = "todo"; + const readyEvt = emitEvent("task.ready", actor, { + channel: issue.channel, + issueId: issue.id, + identifier: issue.identifier, + payload: { resolvedInteractionId: pending.id }, + }); + issue.cursor = readyEvt.cursor; + } else if (action === "reject") { + issue.status = "blocked"; + } + issue.updatedAt = nowIso(); + return jsonResponse(pending); + } + } + + // 14. Schemas list / get / create + const schemasMatch = /^\/api\/companies\/([^/]+)\/schemas(?:\/([^/]+))?$/.exec( + pathname, + ); + if (schemasMatch) { + if (schemasMatch[1] !== companyId) { + return errorResponse(404, "company_not_found", "Company not found"); + } + const refParam = schemasMatch[2] + ? decodeURIComponent(schemasMatch[2]) + : undefined; + if (method === "GET" && refParam) { + const schema = schemasByRef.get(refParam); + if (!schema) { + return errorResponse(404, "schema_not_found", `Schema "${refParam}" not found`); + } + return jsonResponse(schema); + } + if (method === "GET") { + return jsonResponse({ items: [...schemasByRef.values()] }); + } + if (method === "POST") { + const parsed = createCompanySchemaInputSchema.safeParse(bodyJson); + if (!parsed.success) { + return errorResponse(400, "validation_error", parsed.error.message); + } + const { name, version, ref } = parsed.data.ref + ? parseSchemaRef(parsed.data.ref) + : parseSchemaRef(`${parsed.data.name!}@${parsed.data.version!}`); + + const existing = schemasByRef.get(ref); + if (existing) { + if ( + canonicalizeJsonSchema(existing.jsonSchema) === + canonicalizeJsonSchema(parsed.data.jsonSchema) + ) { + return jsonResponse({ schema: existing, created: false }, 200); + } + return errorResponse( + 409, + "schema_immutable", + `Schema "${ref}" already exists with a different definition; register ${name}@${version + 1} instead`, + ); + } + + const created: CompanySchemaView = { + id: makeUuid(uuidSeq++), + companyId, + name, + version, + ref, + description: parsed.data.description ?? null, + jsonSchema: parsed.data.jsonSchema, + builtIn: false, + createdAt: nowIso(), + }; + schemasByRef.set(ref, created); + return jsonResponse({ schema: created, created: true }, 201); + } + } + + // 15. Schedules + const schedulesMatch = /^\/api\/companies\/([^/]+)\/schedules(?:\/([^/]+))?$/.exec( + pathname, + ); + if (schedulesMatch) { + if (schedulesMatch[1] !== companyId) { + return errorResponse(404, "company_not_found", "Company not found"); + } + const schedId = schedulesMatch[2] + ? decodeURIComponent(schedulesMatch[2]) + : undefined; + + if (method === "GET") { + const target = url.searchParams.get("target"); + const items = [...schedules.values()].filter( + (s) => !target || s.target === target, + ); + return jsonResponse({ items }); + } + if (method === "POST") { + const parsed = SchedulePostSchema.safeParse(bodyJson); + if (!parsed.success) { + return errorResponse(400, "validation_error", parsed.error.message); + } + const delayMs = + parsed.data.in !== undefined + ? parseDurationMs(parsed.data.in) + : parsed.data.every !== undefined + ? parseDurationMs(parsed.data.every) + : 0; + const nextRunAt = parsed.data.at + ? new Date(parsed.data.at).toISOString() + : new Date(currentNowMs + delayMs).toISOString(); + const intervalMs = + parsed.data.every !== undefined + ? parseDurationMs(parsed.data.every) + : null; + const created: ScheduleView = { + id: makeUuid(uuidSeq++), + companyId, + target: parsed.data.target, + message: parsed.data.message, + nextRunAt, + intervalMs, + untilAt: parsed.data.until ?? null, + post: Boolean(parsed.data.post), + status: "scheduled", + createdAt: nowIso(), + }; + schedules.set(created.id, created); + return jsonResponse(created, 201); + } + if (method === "DELETE" && schedId) { + const existing = schedules.get(schedId); + if (!existing) { + return errorResponse(404, "schedule_not_found", "Schedule not found"); + } + existing.status = "cancelled"; + return jsonResponse({ cancelled: true }); + } + } + + // 16. Event Wait (long-poll with cursor replay) + const waitMatch = /^\/api\/companies\/([^/]+)\/events\/wait$/.exec(pathname); + if (waitMatch && method === "GET") { + if (waitMatch[1] !== companyId) { + return errorResponse(404, "company_not_found", "Company not found"); + } + const afterRaw = url.searchParams.get("after"); + const afterSeq = afterRaw ? parseEventCursor(afterRaw) ?? 0 : eventSeq; + const timeoutMs = Number.parseInt( + url.searchParams.get("timeoutMs") ?? "30000", + 10, + ); + + for (const evt of events) { + if (evt.seq > afterSeq && matchesEventFilters(evt, url.searchParams)) { + return jsonResponse(evt, 200); + } + } + + if (timeoutMs <= 0) { + return jsonResponse(null, 204); + } + + return new Promise((resolve) => { + let settled = false; + const cleanup = () => { + listeners.delete(onEvent); + clearTimeout(timer); + init?.signal?.removeEventListener("abort", onAbort); + }; + const onAbort = () => { + if (settled) return; + settled = true; + cleanup(); + resolve(jsonResponse(null, 204)); + }; + const onEvent = (evt: BoardEventView) => { + if (settled) return; + if (evt.seq > afterSeq && matchesEventFilters(evt, url.searchParams)) { + settled = true; + cleanup(); + resolve(jsonResponse(evt, 200)); + } + }; + const timer = setTimeout(() => { + if (settled) return; + settled = true; + cleanup(); + resolve(jsonResponse(null, 204)); + }, timeoutMs); + + if (init?.signal?.aborted) { + onAbort(); + return; + } + init?.signal?.addEventListener("abort", onAbort, { once: true }); + listeners.add(onEvent); + }); + } + + // 17. Event Stream (SSE) + const streamMatch = /^\/api\/companies\/([^/]+)\/events\/stream$/.exec( + pathname, + ); + if (streamMatch && method === "GET") { + if (streamMatch[1] !== companyId) { + return errorResponse(404, "company_not_found", "Company not found"); + } + const afterRaw = url.searchParams.get("after"); + const afterSeq = afterRaw ? parseEventCursor(afterRaw) ?? 0 : eventSeq; + const encoder = new TextEncoder(); + + let listenerRef: ((evt: BoardEventView) => void) | null = null; + const stream = new ReadableStream({ + start(controller) { + const pushEvent = (evt: BoardEventView) => { + const chunk = `id: ${evt.cursor}\nevent: ${evt.type}\ndata: ${JSON.stringify(evt)}\n\n`; + controller.enqueue(encoder.encode(chunk)); + }; + + for (const evt of events) { + if (evt.seq > afterSeq && matchesEventFilters(evt, url.searchParams)) { + pushEvent(evt); + } + } + + listenerRef = (evt: BoardEventView) => { + if (evt.seq > afterSeq && matchesEventFilters(evt, url.searchParams)) { + pushEvent(evt); + } + }; + listeners.add(listenerRef); + + if (init?.signal) { + const onAbort = () => { + if (listenerRef) { + listeners.delete(listenerRef); + listenerRef = null; + } + try { + controller.close(); + } catch { + // already closed + } + }; + if (init.signal.aborted) { + onAbort(); + } else { + init.signal.addEventListener("abort", onAbort, { once: true }); + } + } + }, + cancel() { + if (listenerRef) { + listeners.delete(listenerRef); + listenerRef = null; + } + }, + }); + + return new Response(stream, { + status: 200, + headers: { + "content-type": "text/event-stream", + "cache-control": "no-cache", + }, + }); + } + + return errorResponse( + 404, + "not_found", + `No in-memory handler for ${method} ${pathname}`, + ); + }; + + return { + fetch: fetchHandler, + companyId, + companyPrefix, + advanceTime(ms: number) { + currentNowMs += ms; + expireLeases(); + return currentNowMs; + }, + nowMs() { + return currentNowMs; + }, + expireLeases, + setPolicy(policy: AgentIdentityPolicy) { + agentIdentityPolicy = policy; + }, + seedAgent(input) { + const stored: StoredAgent = { + id: input.id ?? makeUuid(uuidSeq++), + name: input.name, + role: input.role ?? "general", + apiKey: input.apiKey, + }; + agents.set(stored.id, stored); + return stored; + }, + seedBoardToken(input) { + boardTokens.set(input.token, input); + }, + seedProject(input) { + const stored: StoredProject = { + id: input.id ?? makeUuid(uuidSeq++), + slug: input.slug, + name: input.name ?? input.slug, + }; + projects.set(stored.id, stored); + return stored; + }, + getState() { + return { + channels: [...channels.values()].map(({ members: _m, ...c }) => ({ ...c })), + issues: [...issues.values()].map(publicIssueView), + events: [...events], + }; + }, + }; +} diff --git a/packages/shared/src/sdk/sdk.test.ts b/packages/shared/src/sdk/sdk.test.ts new file mode 100644 index 00000000000..4421224d612 --- /dev/null +++ b/packages/shared/src/sdk/sdk.test.ts @@ -0,0 +1,732 @@ +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { + createInMemoryPaperclipBackend, + paperclip, + PaperclipError, +} from "./index.js"; + +describe("@paperclipai/sdk", () => { + it("resolves default company lazily and supports prefix or UUID", async () => { + const mem = createInMemoryPaperclipBackend({ companyPrefix: "PAP" }); + + const byDefault = paperclip({ fetch: mem.fetch }); + const me = await byDefault.whoami(); + expect(me.companyId).toBe(mem.companyId); + expect(me.companyPrefix).toBe("PAP"); + + const byPrefix = paperclip({ fetch: mem.fetch, company: "PAP" }); + expect((await byPrefix.whoami()).companyId).toBe(mem.companyId); + + const byUuid = paperclip({ fetch: mem.fetch, company: mem.companyId }); + expect((await byUuid.whoami()).companyId).toBe(mem.companyId); + }); + + it("resolves Node ~/.paperclip context and profile keys automatically", async () => { + const homeDir = mkdtempSync(join(tmpdir(), "paperclip-sdk-home-")); + try { + mkdirSync(join(homeDir, ".paperclip", "profiles"), { recursive: true }); + const mem = createInMemoryPaperclipBackend({ + agentIdentityPolicy: "strict_agent_keys", + }); + mem.seedAgent({ name: "scanner", role: "security", apiKey: "pcp_scanner_secret" }); + mem.seedBoardToken({ token: "brd_human", userId: "user-dotta" }); + + writeFileSync( + join(homeDir, ".paperclip", "context.json"), + JSON.stringify({ companyId: mem.companyId, apiKey: "brd_human" }), + ); + writeFileSync( + join(homeDir, ".paperclip", "profiles", "scanner.json"), + JSON.stringify({ agent_api_key: "pcp_scanner_secret" }), + ); + + const client = paperclip({ fetch: mem.fetch, homeDir }); + // Human token with --as adhoc is rejected under strict_agent_keys + await expect(client.as("adhoc").whoami()).rejects.toMatchObject({ + name: "PaperclipError", + status: 403, + code: "agent_key_required", + }); + + // Switching to .as("scanner") automatically loads ~/.paperclip/profiles/scanner.json + const scannerWho = await client.as("scanner").whoami(); + expect(scannerWho.principalType).toBe("agent"); + expect(scannerWho.agentName).toBe("scanner"); + } finally { + rmSync(homeDir, { recursive: true, force: true }); + } + }); + + it("enforces delegated_profiles, registered agent collision, and scopes", async () => { + const mem = createInMemoryPaperclipBackend({ + agentIdentityPolicy: "delegated_profiles", + }); + mem.seedAgent({ name: "ceo", apiKey: "pcp_ceo_key" }); + mem.seedBoardToken({ token: "brd_dotta", userId: "user-dotta" }); + + const anon = paperclip({ fetch: mem.fetch, company: mem.companyId }); + await expect(anon.whoami()).rejects.toMatchObject({ + status: 401, + code: "unauthorized", + }); + + const dotta = paperclip({ + fetch: mem.fetch, + company: mem.companyId, + apiKey: "brd_dotta", + }); + + // Impersonating registered @ceo without key fails closed with 409 + await expect(dotta.as("ceo").whoami()).rejects.toMatchObject({ + status: 409, + code: "profile_matches_registered_agent", + }); + + // Ephemeral profile runs with X-Paperclip-Actor-Profile + const helper = dotta.as("worker-1"); + const who = await helper.whoami(); + expect(who.principalType).toBe("user"); + expect(who.actorProfile).toBe("worker-1"); + + // Scoped handle restricts channels + const scoped = dotta.as("build-bot", { + scopes: { channels: ["build/*"], actions: ["read", "post"] }, + }); + const post = await scoped.post("build/auth", "CI passed"); + expect(post.channel).toBe("build/auth"); + await expect(scoped.post("deploys/prod", "No access")).rejects.toMatchObject({ + status: 403, + code: "scope_denied", + }); + }); + + it("supports lazy channels, passive posts, replies with --after guard, and subtree reads", async () => { + const mem = createInMemoryPaperclipBackend(); + const board = paperclip({ fetch: mem.fetch }).as("lead"); + + const post1 = await board.post("build/auth", "Initial auth note", { + labels: { env: "dev" }, + }); + expect(post1.isPassivePost).toBe(true); + expect(post1.status).toBe("backlog"); + expect(post1.description).toBeNull(); + + await board.post("build/ui", "UI lint clean"); + await board.post("deploys/prod", "Prod green"); + + const buildSubtree = await board.read("build/"); + expect(buildSubtree.kind).toBe("channel"); + if (buildSubtree.kind === "channel") { + expect(buildSubtree.items.map((i) => i.channel)).toEqual([ + "build/auth", + "build/ui", + ]); + } + + const r1 = await board.reply(post1.identifier, "First reply"); + const r2 = await board.reply(post1.identifier, "Second reply", { after: r1.id }); + expect(r2.body).toBe("Second reply"); + + // Stale --after returns 409 newer_message + await expect( + board.reply(post1.identifier, "Stale reply", { after: r1.id }), + ).rejects.toMatchObject({ status: 409, code: "newer_message" }); + + // Promote passive post to queued task preserving ID and history + const promoted = await board.tasks.create(post1.identifier, { + priority: "high", + labels: { role: "worker" }, + }); + expect(promoted.id).toBe(post1.id); + expect(promoted.status).toBe("todo"); + + const detail = await board.read(post1.identifier); + expect(detail.kind).toBe("thread"); + if (detail.kind === "thread") { + expect(detail.comments).toHaveLength(2); + } + }); + + it("handles CAS label updates and conflicts", async () => { + const mem = createInMemoryPaperclipBackend(); + const board = paperclip({ fetch: mem.fetch }); + + const task = await board.tasks.create("triage", { + title: "Investigate spike", + labels: { stage: "new" }, + }); + + const updated = await board.label(task.identifier, { + set: { stage: "investigating", owner: "agent-a" }, + if: { stage: "new", owner: null }, + }); + expect(updated.kvLabels).toEqual({ stage: "investigating", owner: "agent-a" }); + + await expect( + board.label(task.identifier, { + set: { stage: "investigating", owner: "agent-b" }, + if: { stage: "new" }, + }), + ).rejects.toMatchObject({ + status: 409, + code: "label_conflict", + }); + + await expect( + board.label(task.identifier, { set: { "paperclip.pr": "123" } }), + ).rejects.toMatchObject({ status: 400, code: "reserved_label" }); + }); + + it("enforces schema immutability, block validation, and task resultSchema", async () => { + const mem = createInMemoryPaperclipBackend(); + const board = paperclip({ fetch: mem.fetch }); + + const list = await board.schemas.list(); + expect(list.some((s) => s.ref === "test-report@1")).toBe(true); + + const def = { + type: "object", + required: ["passed"], + properties: { passed: { type: "boolean" } }, + }; + const first = await board.schemas.create({ + ref: "audit-verdict@1", + jsonSchema: def, + }); + expect(first.created).toBe(true); + + const idempotent = await board.schemas.create({ + ref: "audit-verdict@1", + jsonSchema: { properties: { passed: { type: "boolean" } }, required: ["passed"], type: "object" }, + }); + expect(idempotent.created).toBe(false); + + await expect( + board.schemas.create({ + ref: "audit-verdict@1", + jsonSchema: { type: "object", required: ["passed", "extra"] }, + }), + ).rejects.toMatchObject({ status: 409, code: "schema_immutable" }); + + // Invalid block rejected on post + await expect( + board.post("security/findings", "Bad finding", { + schema: { ref: "finding@1", data: { severity: "bogus" } }, + }), + ).rejects.toMatchObject({ status: 400, code: "invalid_schema_block" }); + + // Task with resultSchema requires valid data on complete() + const task = await board.tasks.create("security/audit", { + title: "Audit auth", + resultSchema: "audit-verdict@1", + }); + const claim = await board.tasks.claim(task.identifier); + expect(claim).not.toBeNull(); + + await expect(claim!.complete("Missing data")).rejects.toMatchObject({ + status: 422, + code: "missing_or_invalid_result_schema", + }); + + const done = await claim!.complete({ + message: "Audit passed", + data: { passed: true }, + }); + expect(done.status).toBe("done"); + expect(done.blocks[0]?.data).toEqual({ passed: true }); + }); + + it("creates DAG plans, handles dependencies, lease expiry/claim_lost, and asks", async () => { + const mem = createInMemoryPaperclipBackend(); + const web = mem.seedProject({ slug: "web-app", name: "Web App" }); + const api = mem.seedProject({ slug: "api-server", name: "API Server" }); + + const lead = paperclip({ fetch: mem.fetch }).as("lead"); + const plan = await lead.tasks.createPlan( + "build/auth", + [ + { + key: "review", + projectId: null, + title: "Review patch", + needs: ["patch"], + labels: { role: "reviewer" }, + }, + { + key: "patch", + title: "Patch token check", + labels: { role: "worker" }, + }, + { + key: "audit", + projectId: "api-server", + title: "Audit API", + labels: { role: "worker" }, + }, + ], + { projectId: "web-app", idempotencyKey: "auth-plan-1" }, + ); + + expect(plan.tasks.map((t) => t.key)).toEqual(["patch", "review", "audit"]); + const patchItem = plan.tasks.find((t) => t.key === "patch")!; + const auditItem = plan.tasks.find((t) => t.key === "audit")!; + const reviewItem = plan.tasks.find((t) => t.key === "review")!; + expect(patchItem.issue.projectId).toBe(web.id); + expect(auditItem.issue.projectId).toBe(api.id); + expect(reviewItem.issue.projectId).toBeNull(); + + // Idempotent replay vs mismatch + const replay = await lead.tasks.createPlan( + "build/auth", + [ + { + key: "review", + projectId: null, + title: "Review patch", + needs: ["patch"], + labels: { role: "reviewer" }, + }, + { + key: "patch", + title: "Patch token check", + labels: { role: "worker" }, + }, + { + key: "audit", + projectId: "api-server", + title: "Audit API", + labels: { role: "worker" }, + }, + ], + { projectId: "web-app", idempotencyKey: "auth-plan-1" }, + ); + expect(replay.idempotentReplay).toBe(true); + + await expect( + lead.tasks.createPlan( + "build/auth", + [{ key: "different", title: "Different payload" }], + { idempotencyKey: "auth-plan-1" }, + ), + ).rejects.toMatchObject({ + status: 409, + code: "duplicate_idempotency_key", + }); + + const w1 = paperclip({ fetch: mem.fetch }).as("worker-1"); + // Reviewer cannot claim review yet because "patch" is not done + expect( + await w1.tasks.claim({ channel: "build/auth", label: "role=reviewer" }), + ).toBeNull(); + + // Worker 1 claims patch with 60s lease, then advances past expiry -> claim_lost + const c1 = await w1.tasks.claim({ + channel: "build/auth", + label: "role=worker", + lease: "60s", + }); + expect(c1).not.toBeNull(); + expect(c1!.task.identifier).toBe(patchItem.identifier); + + // Renew works before expiry + const renewed = await c1!.renew("2m"); + expect(renewed.claimEpoch).toBe(c1!.claimEpoch); + + // Advance clock past 2m lease -> lease expires & requeues + mem.advanceTime(125_000); + await expect(c1!.renew("1m")).rejects.toMatchObject({ + status: 409, + code: "claim_lost", + }); + + // Worker 2 claims the requeued patch task & asks a human question (releases lease) + const w2 = paperclip({ fetch: mem.fetch }).as("worker-2"); + const c2 = await w2.tasks.claim(patchItem.identifier); + expect(c2).not.toBeNull(); + expect(c2!.claimEpoch).toBeGreaterThan(c1!.claimEpoch); + + const interaction = await c2!.confirm("Drop legacy column?", { + humanOnly: true, + }); + expect(interaction.status).toBe("pending"); + expect(interaction.continuationPolicy).toBe("requeue_on_resolve"); + + // Lead approves -> task returns to todo and worker claims + completes -> unblocks review! + await lead.approve(c2!.task.identifier, { note: "Ship it" }); + const c3 = await w2.tasks.claim(c2!.task.identifier); + expect(c3).not.toBeNull(); + await c3!.complete("Patched"); + + // Review is now unblocked! + const revClaim = await w1.tasks.claim({ + channel: "build/auth", + label: "role=reviewer", + }); + expect(revClaim?.task.identifier).toBe(reviewItem.identifier); + }); + + it("supports wait() cursor replay, schedules, and SSE events() streaming", async () => { + const mem = createInMemoryPaperclipBackend(); + const board = paperclip({ fetch: mem.fetch }).as("lead"); + + const task = await board.tasks.create("qa/smoke", { title: "Run smoke suite" }); + const createdCursor = task.cursor; + + // Complete task before calling wait() -> cursor replay returns immediately! + const claimed = await board.tasks.claim(task.identifier); + await claimed!.complete("All green"); + + const replayed = await board.wait(task.identifier, { + event: ["task.completed", "task.failed"], + after: createdCursor, + timeout: "1s", + }); + expect(replayed?.type).toBe("task.completed"); + expect(replayed?.identifier).toBe(task.identifier); + + // Schedules + const sched = await board.schedule("deploys", { + message: "Check canary", + in: "5m", + post: true, + }); + expect(sched.status).toBe("scheduled"); + expect((await board.schedules.list()).length).toBe(1); + expect((await board.schedules.cancel(sched.id)).cancelled).toBe(true); + + // SSE stream replays from cursor and receives live events + const ac = new AbortController(); + const received: string[] = []; + const streamTask = (async () => { + for await (const evt of board.events( + { channel: "deploys/", after: createdCursor }, + { signal: ac.signal }, + )) { + received.push(evt.type); + if (received.length >= 2) { + ac.abort(); + break; + } + } + })(); + + await board.post("deploys/prod", "Live SSE check 1"); + await board.post("deploys/staging", "Live SSE check 2"); + await streamTask; + expect(received).toEqual(["thread.posted", "thread.posted"]); + + // Verify PaperclipError instance + try { + await board.read("PAP-99999"); + expect.fail("Expected PaperclipError"); + } catch (err) { + expect(err).toBeInstanceOf(PaperclipError); + expect((err as PaperclipError).status).toBe(404); + } + }); + + it("delegates tasks.create with needs to /issues/batch and prioritizes explicit profile key + v2 context", async () => { + const homeDir = mkdtempSync(join(tmpdir(), "paperclip-sdk-v2-")); + const prevApiKey = process.env.PAPERCLIP_API_KEY; + const prevCustomEnv = process.env.PAPERCLIP_TEST_V2_KEY; + try { + mkdirSync(join(homeDir, ".paperclip", "profiles"), { recursive: true }); + const mem = createInMemoryPaperclipBackend({ + agentIdentityPolicy: "delegated_profiles", + }); + mem.seedAgent({ name: "worker-a", role: "engineer", apiKey: "pcp_worker_a" }); + mem.seedBoardToken({ token: "brd_env_token", userId: "user-dotta" }); + mem.seedBoardToken({ token: "brd_v2_token", userId: "user-v2" }); + + process.env.PAPERCLIP_TEST_V2_KEY = "brd_v2_token"; + writeFileSync( + join(homeDir, ".paperclip", "context.json"), + JSON.stringify({ + version: 2, + currentProfile: "default", + profiles: { + default: { + companyId: mem.companyId, + apiKeyEnvVarName: "PAPERCLIP_TEST_V2_KEY", + }, + }, + }), + ); + writeFileSync( + join(homeDir, ".paperclip", "profiles", "worker-a.json"), + JSON.stringify({ agent_api_key: "pcp_worker_a" }), + ); + + // v2 context picks up apiKeyEnvVarName automatically when env PAPERCLIP_API_KEY is unset + delete process.env.PAPERCLIP_API_KEY; + const v2Client = paperclip({ fetch: mem.fetch, homeDir }); + const v2Who = await v2Client.whoami(); + expect(v2Who.companyId).toBe(mem.companyId); + expect(v2Who.userId).toBe("user-v2"); + + // Even with ambient PAPERCLIP_API_KEY set, explicit .as("worker-a") prefers profile key + process.env.PAPERCLIP_API_KEY = "brd_env_token"; + const workerClient = paperclip({ fetch: mem.fetch, homeDir, company: mem.companyId }).as("worker-a"); + const workerWho = await workerClient.whoami(); + expect(workerWho.principalType).toBe("agent"); + expect(workerWho.agentName).toBe("worker-a"); + + // tasks.create with needs delegates via batch endpoint and wires blockedByIssueIds + const first = await workerClient.tasks.create("eng", { title: "First step" }); + const second = await workerClient.tasks.create("eng", { + title: "Second step", + needs: [first.identifier], + }); + expect(second.blockedByIssueIds).toEqual([first.id]); + + // wait(undefined, filters) forwards filter query params + const done = await workerClient.tasks.create("eng", { title: "Filter wait target" }); + const doneClaim = await workerClient.tasks.claim(done.identifier); + await doneClaim!.complete("Done"); + const filteredWait = await workerClient.wait(undefined, { + event: "task.completed", + issueId: done.identifier, + after: done.cursor, + timeout: "500ms", + }); + expect(filteredWait?.type).toBe("task.completed"); + expect(filteredWait?.identifier).toBe(done.identifier); + } finally { + if (prevApiKey === undefined) delete process.env.PAPERCLIP_API_KEY; + else process.env.PAPERCLIP_API_KEY = prevApiKey; + if (prevCustomEnv === undefined) delete process.env.PAPERCLIP_TEST_V2_KEY; + else process.env.PAPERCLIP_TEST_V2_KEY = prevCustomEnv; + rmSync(homeDir, { recursive: true, force: true }); + } + }); + + it("ignores repo-local .paperclip/context.json credentials and refuses sending ambient keys to untrusted repo endpoints", async () => { + const repoDir = mkdtempSync(join(tmpdir(), "paperclip-sdk-untrusted-")); + const prevCwd = process.cwd(); + const prevApiKey = process.env.PAPERCLIP_API_KEY; + const prevApiUrl = process.env.PAPERCLIP_API_URL; + const prevContext = process.env.PAPERCLIP_CONTEXT; + const prevHome = process.env.PAPERCLIP_HOME; + const prevCompany = process.env.PAPERCLIP_COMPANY_ID; + const prevProfile = process.env.PAPERCLIP_PROFILE; + const prevSecret = process.env.TEST_VICTIM_SECRET; + + try { + delete process.env.PAPERCLIP_HOME; + delete process.env.PAPERCLIP_API_URL; + delete process.env.PAPERCLIP_COMPANY_ID; + delete process.env.PAPERCLIP_PROFILE; + process.env.TEST_VICTIM_SECRET = "victim-aws-secret"; + process.env.PAPERCLIP_API_KEY = "brd_victim_ambient"; + const trustedCtxPath = join(repoDir, "trusted-context.json"); + writeFileSync( + trustedCtxPath, + JSON.stringify({ + version: 2, + currentProfile: "default", + profiles: { default: { apiBase: "http://127.0.0.1:49991", companyId: "trusted-co" } }, + }), + ); + process.env.PAPERCLIP_CONTEXT = trustedCtxPath; + + mkdirSync(join(repoDir, ".paperclip"), { recursive: true }); + writeFileSync( + join(repoDir, ".paperclip", "context.json"), + JSON.stringify({ + version: 2, + currentProfile: "default", + profiles: { + default: { + apiBase: "http://127.0.0.1:49999", + companyId: "attacker-co", + apiKey: "attacker-inline", + apiKeyEnvVarName: "TEST_VICTIM_SECRET", + }, + }, + }), + ); + process.chdir(repoDir); + + const seenAuthHeaders: Array = []; + const sdkClient = paperclip({ + fetch: async (_input, init) => { + seenAuthHeaders.push(new Headers(init?.headers).get("authorization")); + return new Response(JSON.stringify({ id: "attacker-co", name: "X", issuePrefix: "X", agentIdentityPolicy: "open_local_profiles", apiBase: "http://127.0.0.1:49999", created: false }), { + status: 200, + headers: { "content-type": "application/json" }, + }); + }, + }); + + // With PAPERCLIP_API_KEY present, SDK refuses sending ambient key to untrusted repo-local .paperclip/context.json apiBase + await expect(sdkClient.whoami()).rejects.toThrow(/untrusted repo-local apiBase/i); + expect(seenAuthHeaders).toEqual([]); + + // Even without PAPERCLIP_API_KEY, repo-local apiKeyEnvVarName / inline apiKey is ignored + delete process.env.PAPERCLIP_API_KEY; + const anonClient = paperclip({ + fetch: async (_input, init) => { + seenAuthHeaders.push(new Headers(init?.headers).get("authorization")); + return new Response( + JSON.stringify({ + companyId: "attacker-co", + companyName: "X", + companyPrefix: "X", + principalType: "local_trusted", + userId: null, + agentId: null, + agentName: null, + actorProfile: null, + agentIdentityPolicy: "open_local_profiles", + scopes: null, + }), + { status: 200, headers: { "content-type": "application/json" } }, + ); + }, + }); + await anonClient.whoami(); + expect(seenAuthHeaders).toEqual([null, null]); + } finally { + process.chdir(prevCwd); + if (prevApiKey === undefined) delete process.env.PAPERCLIP_API_KEY; + else process.env.PAPERCLIP_API_KEY = prevApiKey; + if (prevApiUrl === undefined) delete process.env.PAPERCLIP_API_URL; + else process.env.PAPERCLIP_API_URL = prevApiUrl; + if (prevContext === undefined) delete process.env.PAPERCLIP_CONTEXT; + else process.env.PAPERCLIP_CONTEXT = prevContext; + if (prevHome === undefined) delete process.env.PAPERCLIP_HOME; + else process.env.PAPERCLIP_HOME = prevHome; + if (prevCompany === undefined) delete process.env.PAPERCLIP_COMPANY_ID; + else process.env.PAPERCLIP_COMPANY_ID = prevCompany; + if (prevProfile === undefined) delete process.env.PAPERCLIP_PROFILE; + else process.env.PAPERCLIP_PROFILE = prevProfile; + if (prevSecret === undefined) delete process.env.TEST_VICTIM_SECRET; + else process.env.TEST_VICTIM_SECRET = prevSecret; + rmSync(repoDir, { recursive: true, force: true }); + } + }); + + it("carries server-resolved cursor across 204 wait hops when after is omitted", async () => { + const seenAfterParams: Array = []; + let callCount = 0; + const client = paperclip({ + apiBase: "http://127.0.0.1:49991", + company: "00000000-0000-4000-8000-000000000001", + fetch: async (input) => { + const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url); + seenAfterParams.push(url.searchParams.get("after")); + callCount += 1; + if (callCount === 1) { + return new Response(null, { + status: 204, + headers: { "x-paperclip-cursor": "evt_17" }, + }); + } + return new Response( + JSON.stringify({ + id: "evt-row-18", + cursor: "evt_18", + seq: 18, + companyId: "00000000-0000-4000-8000-000000000001", + type: "thread.posted", + channel: "deploys", + channelId: "ch-1", + issueId: "iss-1", + identifier: "PAP-18", + actor: { type: "user", userId: "u-1", agentId: null, name: null, profile: null }, + payload: {}, + createdAt: "2026-01-01T00:00:00.000Z", + }), + { status: 200, headers: { "content-type": "application/json" } }, + ); + }, + }); + + const event = await client.wait("deploys", { timeout: "50ms" }); + expect(event?.cursor).toBe("evt_18"); + expect(seenAfterParams).toEqual([null, "evt_17"]); + }); + + it("loads fallback board credential from auth.json for matching apiBase unless apiBase came from repo-local config", async () => { + const homeDir = mkdtempSync(join(tmpdir(), "paperclip-sdk-authjson-")); + const repoDir = mkdtempSync(join(tmpdir(), "paperclip-sdk-authrepo-")); + const prevHome = process.env.PAPERCLIP_HOME; + const prevAuthStore = process.env.PAPERCLIP_AUTH_STORE; + const prevCtx = process.env.PAPERCLIP_CONTEXT; + const prevKey = process.env.PAPERCLIP_API_KEY; + const prevUrl = process.env.PAPERCLIP_API_URL; + const prevCwd = process.cwd(); + try { + delete process.env.PAPERCLIP_HOME; + delete process.env.PAPERCLIP_AUTH_STORE; + delete process.env.PAPERCLIP_CONTEXT; + delete process.env.PAPERCLIP_API_KEY; + delete process.env.PAPERCLIP_API_URL; + + mkdirSync(join(homeDir, ".paperclip"), { recursive: true }); + const mem = createInMemoryPaperclipBackend({ + agentIdentityPolicy: "delegated_profiles", + }); + mem.seedBoardToken({ token: "brd_from_auth_json", userId: "user-auth-json" }); + + writeFileSync( + join(homeDir, ".paperclip", "auth.json"), + JSON.stringify({ + version: 1, + credentials: { + "http://127.0.0.1:49992": { + apiBase: "http://127.0.0.1:49992", + token: "brd_from_auth_json", + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }, + }, + }), + ); + + // Direct apiBase uses ~/.paperclip/auth.json fallback + const authed = paperclip({ + apiBase: "http://127.0.0.1:49992/", + company: mem.companyId, + homeDir, + fetch: mem.fetch, + }); + const who = await authed.as("worker-auth").whoami(); + expect(who.principalType).toBe("user"); + expect(who.userId).toBe("user-auth-json"); + expect(who.actorProfile).toBe("worker-auth"); + + // Repo-local apiBase refuses to send stored auth.json token silently + mkdirSync(join(repoDir, ".git")); + writeFileSync( + join(repoDir, ".paperclip.json"), + JSON.stringify({ apiBase: "http://127.0.0.1:49992", companyId: mem.companyId }), + ); + process.chdir(repoDir); + process.env.PAPERCLIP_AUTH_STORE = join(homeDir, ".paperclip", "auth.json"); + + const untrustedRepoClient = paperclip({ fetch: mem.fetch }); + await expect(untrustedRepoClient.whoami()).rejects.toMatchObject({ + status: 401, + code: "unauthorized", + }); + } finally { + process.chdir(prevCwd); + if (prevHome === undefined) delete process.env.PAPERCLIP_HOME; + else process.env.PAPERCLIP_HOME = prevHome; + if (prevAuthStore === undefined) delete process.env.PAPERCLIP_AUTH_STORE; + else process.env.PAPERCLIP_AUTH_STORE = prevAuthStore; + if (prevCtx === undefined) delete process.env.PAPERCLIP_CONTEXT; + else process.env.PAPERCLIP_CONTEXT = prevCtx; + if (prevKey === undefined) delete process.env.PAPERCLIP_API_KEY; + else process.env.PAPERCLIP_API_KEY = prevKey; + if (prevUrl === undefined) delete process.env.PAPERCLIP_API_URL; + else process.env.PAPERCLIP_API_URL = prevUrl; + rmSync(homeDir, { recursive: true, force: true }); + rmSync(repoDir, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/shared/src/sdk/sse.ts b/packages/shared/src/sdk/sse.ts new file mode 100644 index 00000000000..cb1284b6acd --- /dev/null +++ b/packages/shared/src/sdk/sse.ts @@ -0,0 +1,83 @@ +import type { BoardEventView } from "../headless/index.js"; + +function parseSseBlock(block: string): BoardEventView | null { + const lines = block.split(/\r?\n/); + const dataLines: string[] = []; + + for (const line of lines) { + if (!line || line.startsWith(":")) continue; + if (line.startsWith("data:")) { + const value = line.slice(5); + dataLines.push(value.startsWith(" ") ? value.slice(1) : value); + } + } + + if (dataLines.length === 0) return null; + const payloadText = dataLines.join("\n").trim(); + if (!payloadText) return null; + return JSON.parse(payloadText) as BoardEventView; +} + +export async function* parseSseEventStream( + body: ReadableStream, + signal?: AbortSignal, +): AsyncGenerator { + const reader = body.getReader(); + const decoder = new TextDecoder(); + let buffer = ""; + + const onAbort = () => { + void reader.cancel().catch(() => {}); + }; + if (signal) { + if (signal.aborted) { + onAbort(); + return; + } + signal.addEventListener("abort", onAbort, { once: true }); + } + + try { + while (true) { + const { value, done } = await reader.read(); + if (done) break; + buffer += decoder.decode(value, { stream: true }); + + while (true) { + const crlfIdx = buffer.indexOf("\r\n\r\n"); + const lfIdx = buffer.indexOf("\n\n"); + let sepIdx = -1; + let sepLen = 0; + + if (crlfIdx !== -1 && (lfIdx === -1 || crlfIdx < lfIdx)) { + sepIdx = crlfIdx; + sepLen = 4; + } else if (lfIdx !== -1) { + sepIdx = lfIdx; + sepLen = 2; + } + + if (sepIdx === -1) break; + const block = buffer.slice(0, sepIdx); + buffer = buffer.slice(sepIdx + sepLen); + const parsed = parseSseBlock(block); + if (parsed) yield parsed; + } + } + + buffer += decoder.decode(); + if (buffer.trim()) { + const parsed = parseSseBlock(buffer); + if (parsed) yield parsed; + } + } finally { + if (signal) { + signal.removeEventListener("abort", onAbort); + } + try { + reader.releaseLock(); + } catch { + // reader may already be released or cancelled + } + } +} diff --git a/packages/shared/src/sdk/types.ts b/packages/shared/src/sdk/types.ts new file mode 100644 index 00000000000..d7212ea5913 --- /dev/null +++ b/packages/shared/src/sdk/types.ts @@ -0,0 +1,275 @@ +import type { IssuePriority, IssueStatus } from "../constants.js"; +import type { + BoardEventType, + BoardEventView, + BatchCreateIssuesResult, + ChannelPage, + ChannelPostInput, + ChannelView, + ClientScopes, + CommentView, + CompanySchemaView, + CreateChannelInput, + CreateCompanySchemaInput, + HeadlessIssueView, + InteractionView, + KvLabelMutation, + OneLineAskInput, + OneLineConfirmInput, + PlanTaskInput, + SchemaBlock, + SchedulePostInput, + ScheduleView, + TaskClaimView, + TaskCompleteInput, + ThreadDetailView, + WhoAmIView, +} from "../headless/index.js"; + +export interface PaperclipErrorInit { + status: number; + code: string; + message: string; + next?: string[]; + details?: Record; +} + +export class PaperclipError extends Error { + readonly status: number; + readonly code: string; + readonly next?: string[]; + readonly details?: Record; + + constructor(init: PaperclipErrorInit) { + super(init.message); + this.name = "PaperclipError"; + this.status = init.status; + this.code = init.code; + if (init.next !== undefined) { + this.next = init.next; + } + if (init.details !== undefined) { + this.details = init.details; + } + } +} + +export interface PaperclipClientOptions { + apiBase?: string; + apiKey?: string; + company?: string; + profile?: string | null; + scopes?: ClientScopes; + fetch?: typeof globalThis.fetch; + homeDir?: string; +} + +export type PostInput = Omit; + +export interface ReplyInput { + body?: string; + text?: string; + labels?: Record; + blocks?: SchemaBlock[]; + schema?: { ref: string; data: Record }; + after?: string; + internal?: boolean; + idempotencyKey?: string; +} + +export interface ReadFilters { + label?: string | string[]; + status?: IssueStatus | IssueStatus[]; + after?: string; + limit?: number; +} + +export interface CreateTaskInput { + title?: string; + text?: string; + description?: string | null; + projectId?: string | null; + board?: boolean; + priority?: IssuePriority; + labels?: Record; + tagLabels?: string[]; + for?: string; + assigneeAgentId?: string | null; + resultSchema?: string; + needs?: Array; + blocks?: SchemaBlock[]; + idempotencyKey?: string; + sourceTrust?: string; +} + +export interface TaskListFilters { + channel?: string; + state?: IssueStatus | IssueStatus[]; + status?: IssueStatus | IssueStatus[]; + label?: string | string[]; + assignee?: string; + project?: string; + ready?: boolean; + after?: string; + limit?: number; +} + +export interface TaskClaimOptions { + ready?: boolean; + channel?: string; + projectId?: string; + label?: string | string[]; + labels?: string[]; + lease?: string | number; + leaseSec?: number; + wait?: string | number; + waitSec?: number; + includeUntrusted?: boolean; + signal?: AbortSignal; +} + +export interface EventWaitFilters { + channel?: string; + issueId?: string; + event?: BoardEventType | BoardEventType[]; + label?: string | string[]; + mentions?: string; + schema?: string; + after?: string; + timeout?: string | number; +} + +export interface EventStreamFilters { + channel?: string; + issueId?: string; + event?: BoardEventType | BoardEventType[]; + label?: string | string[]; + mentions?: string; + schema?: string; + after?: string; +} + +export interface ApproveRejectInput { + answer?: string; + note?: string; + reason?: string; + interactionId?: string; +} + +export interface ClaimedTask { + task: HeadlessIssueView; + claimToken: string; + claimEpoch: number; + leaseExpiresAt: string; + cursor: string; + renew(lease?: string | number): Promise; + release(comment?: string): Promise<{ released: boolean; cursor: string }>; + complete( + opts?: string | Omit, + ): Promise; + fail( + reason: string, + opts?: { requeue?: boolean }, + ): Promise; + ask( + question: string, + opts?: Omit, + ): Promise; + confirm( + prompt: string, + opts?: Omit, + ): Promise; +} + +export interface PaperclipHandle { + as(profile: string | null, opts?: { scopes?: ClientScopes }): PaperclipHandle; + whoami(): Promise; + channels: { + list(prefix?: string): Promise; + create( + path: string, + opts?: Omit, + ): Promise; + ensure( + path: string, + opts?: Omit, + ): Promise; + }; + post( + channel: string, + bodyOrOpts: string | PostInput, + maybeOpts?: Omit, + ): Promise; + reply( + id: string, + bodyOrOpts: string | ReplyInput, + maybeOpts?: Omit, + ): Promise; + read( + channelOrId: string, + filters?: ReadFilters, + ): Promise; + label( + id: string, + mutation: KvLabelMutation, + ): Promise<{ id: string; kvLabels: Record; cursor: string }>; + tasks: { + create( + channelOrId: string, + input?: string | CreateTaskInput, + maybeOpts?: CreateTaskInput, + ): Promise; + createPlan( + channel: string, + tasks: PlanTaskInput[], + opts?: { + projectId?: string | null; + board?: boolean; + idempotencyKey?: string; + }, + ): Promise; + list( + filters?: TaskListFilters, + ): Promise<{ items: HeadlessIssueView[]; cursor: string }>; + claim( + idOrReadyQuery?: string | TaskClaimOptions, + opts?: TaskClaimOptions, + ): Promise; + }; + ask( + id: string, + question: string, + opts?: Omit, + ): Promise; + confirm( + id: string, + prompt: string, + opts?: Omit, + ): Promise; + approve(id: string, opts?: ApproveRejectInput): Promise; + reject(id: string, opts?: ApproveRejectInput): Promise; + schemas: { + list(): Promise; + get(ref: string): Promise; + create( + input: CreateCompanySchemaInput, + ): Promise<{ schema: CompanySchemaView; created: boolean }>; + }; + schedule( + target: string, + opts: Omit, + ): Promise; + schedules: { + list(filters?: { target?: string }): Promise; + cancel(id: string): Promise<{ cancelled: boolean }>; + }; + wait( + targetOrFilters?: string | EventWaitFilters, + filters?: EventWaitFilters, + opts?: { timeout?: string | number; signal?: AbortSignal }, + ): Promise; + events( + filters?: EventStreamFilters, + opts?: { signal?: AbortSignal }, + ): AsyncGenerator; +} diff --git a/scripts/build-npm.sh b/scripts/build-npm.sh index 937a8502120..df3806886d7 100755 --- a/scripts/build-npm.sh +++ b/scripts/build-npm.sh @@ -44,13 +44,16 @@ fi # ── Step 3: Bundle CLI with esbuild ──────────────────────────────────────────── echo " [3/6] Bundling CLI with esbuild..." +cd "$REPO_ROOT" +corepack pnpm --filter @paperclipai/shared build >/dev/null cd "$CLI_DIR" rm -rf dist node --input-type=module -e " import esbuild from 'esbuild'; -import config from './esbuild.config.mjs'; +import config, { emitSdkTypes } from './esbuild.config.mjs'; await esbuild.build(config); +emitSdkTypes(); " chmod +x dist/index.js @@ -58,6 +61,8 @@ chmod +x dist/index.js # ── Step 4: Validate bundled entrypoint syntax ───────────────────────────────── echo " [4/6] Verifying bundled entrypoint syntax..." node --check "$DIST_DIR/index.js" +node --check "$DIST_DIR/sdk.js" +test -f "$DIST_DIR/sdk.d.ts" # ── Step 5: Back up dev package.json, generate publishable one ───────────────── echo " [5/6] Generating publishable package.json..." diff --git a/scripts/generate-npm-package-json.mjs b/scripts/generate-npm-package-json.mjs index bfa1e13ecf6..d291226e1bb 100644 --- a/scripts/generate-npm-package-json.mjs +++ b/scripts/generate-npm-package-json.mjs @@ -104,6 +104,7 @@ const publishPkg = { description: cliPkg.description, type: cliPkg.type, bin: cliPkg.bin, + ...(cliPkg.exports ? { exports: cliPkg.exports } : {}), keywords: cliPkg.keywords, license: cliPkg.license, repository: cliPkg.repository, diff --git a/server/src/__tests__/company-skills-list-statements.test.ts b/server/src/__tests__/company-skills-list-statements.test.ts index 848ffc7a456..550eab27ed3 100644 --- a/server/src/__tests__/company-skills-list-statements.test.ts +++ b/server/src/__tests__/company-skills-list-statements.test.ts @@ -36,7 +36,7 @@ describeEmbeddedPostgres("GET /api/companies/:companyId/skills statements per re expect(second.body).toEqual(first.body); expect(after.transactions - before.transactions).toBe(0); expect(log.filter((entry) => /pg_advisory/.test(entry.sql))).toEqual([]); - expect(after.statements - before.statements).toBeLessThanOrEqual(45); + expect(after.statements - before.statements).toBeLessThanOrEqual(48); expect(await bundledFolders(company.companyId)).toEqual(foldersAfterFirst); } finally { statements.uninstall(); diff --git a/server/src/__tests__/fixtures/issue-detail-response.json b/server/src/__tests__/fixtures/issue-detail-response.json index ae90e4ae173..cbf15dee791 100644 --- a/server/src/__tests__/fixtures/issue-detail-response.json +++ b/server/src/__tests__/fixtures/issue-detail-response.json @@ -7,6 +7,7 @@ "conversationSessionGeneration": 0, "conversationBoundaryCommentId": null, "projectId": "", + "channelId": null, "projectWorkspaceId": null, "goalId": null, "parentId": "", @@ -32,7 +33,19 @@ "executionLockedAt": null, "createdByAgentId": null, "createdByUserId": "", + "createdByProfile": null, "responsibleUserId": null, + "kvLabels": {}, + "schemaBlocks": [], + "resultSchemaRef": null, + "claimEpoch": 0, + "claimTokenHash": null, + "claimHolderAgentId": null, + "claimHolderUserId": null, + "claimHolderProfile": null, + "claimLeasedAt": null, + "claimLeaseExpiresAt": null, + "claimAttemptCount": 0, "issueNumber": null, "identifier": null, "originKind": "manual", diff --git a/server/src/__tests__/headless-channels-schemas-batch.test.ts b/server/src/__tests__/headless-channels-schemas-batch.test.ts new file mode 100644 index 00000000000..595136c60d7 --- /dev/null +++ b/server/src/__tests__/headless-channels-schemas-batch.test.ts @@ -0,0 +1,1152 @@ +import { randomUUID } from "node:crypto"; +import express from "express"; +import request from "supertest"; +import { and, eq, sql } from "drizzle-orm"; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import { + agents, + authUsers, + companies, + companyMemberships, + createDb, + issueRelations, + issues, + projects, + 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 { issueRoutes } from "../routes/issues.js"; +import { issueService } from "../services/issues.js"; +import { + getEmbeddedPostgresTestSupport, + startEmbeddedPostgresTestDatabase, +} from "./helpers/embedded-postgres.js"; + +const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); +const describeEmbeddedPostgres = embeddedPostgresSupport.supported + ? describe + : describe.skip; + +describeEmbeddedPostgres("headless channels, schemas, CAS labels, and batch DAG", () => { + let db!: Db; + let tempDb: Awaited> | null = + null; + + let companyId!: string; + let ownerUserId!: string; + let peerUserId!: string; + let webProjectId!: string; + let apiProjectId!: string; + let reviewerAgentId!: string; + + beforeAll(async () => { + tempDb = await startEmbeddedPostgresTestDatabase( + "paperclip-headless-ch-schema-batch-", + ); + db = createDb(tempDb.connectionString, { maxConnections: 10 }); + }, 30_000); + + afterAll(async () => { + await db?.$client.end({ timeout: 1 }); + await tempDb?.cleanup(); + }); + + beforeEach(async () => { + ownerUserId = `user-owner-${randomUUID()}`; + peerUserId = `user-peer-${randomUUID()}`; + const prefix = `H${randomUUID().replace(/-/g, "").slice(0, 6).toUpperCase()}`; + + const [company] = await db + .insert(companies) + .values({ + name: `Headless Test Co ${prefix}`, + issuePrefix: prefix, + agentIdentityPolicy: "open_local_profiles", + }) + .returning(); + companyId = company!.id; + + await db.insert(authUsers).values([ + { + id: ownerUserId, + name: "Owner User", + email: `${ownerUserId}@example.test`, + emailVerified: true, + createdAt: new Date(), + updatedAt: new Date(), + }, + { + id: peerUserId, + name: "Peer User", + email: `${peerUserId}@example.test`, + emailVerified: true, + createdAt: new Date(), + updatedAt: new Date(), + }, + ]); + + await db.insert(companyMemberships).values([ + { + companyId, + principalType: "user", + principalId: ownerUserId, + membershipRole: "owner", + status: "active", + }, + { + companyId, + principalType: "user", + principalId: peerUserId, + membershipRole: "operator", + status: "active", + }, + ]); + + const [webProj, apiProj] = await db + .insert(projects) + .values([ + { companyId, name: "Web App", status: "in_progress" }, + { companyId, name: "API Server", status: "in_progress" }, + ]) + .returning(); + webProjectId = webProj!.id; + apiProjectId = apiProj!.id; + + const [reviewer] = await db + .insert(agents) + .values({ + companyId, + name: "reviewer", + role: "qa", + adapterType: "process", + status: "idle", + }) + .returning(); + reviewerAgentId = reviewer!.id; + }); + + function createLocalApp() { + const app = express(); + app.use(express.json()); + app.use( + actorMiddleware(db, { + deploymentMode: "local_trusted", + }), + ); + app.use( + "/api", + headlessChannelsSchemasRoutes(db, { deploymentMode: "local_trusted" }), + ); + app.use(errorHandler); + return app; + } + + function createAuthenticatedApp(sessionUserIdHeader = "x-test-user-id") { + const app = express(); + app.use(express.json()); + app.use( + actorMiddleware(db, { + deploymentMode: "authenticated", + resolveSession: async (req) => { + const uid = req.header(sessionUserIdHeader); + if (!uid) return null; + return { + session: { id: `sess-${uid}`, userId: uid }, + user: { id: uid, name: uid, email: `${uid}@example.test` }, + }; + }, + }), + ); + app.use( + "/api", + headlessChannelsSchemasRoutes(db, { deploymentMode: "authenticated" }), + ); + // Downstream sentinel to verify browser GET /issues/:id calls next() + app.get("/api/issues/:id", (_req, res) => { + res.status(200).json({ delegatedToIssueRoutes: true }); + }); + app.use(errorHandler); + return app; + } + + it("1. creates channels lazily, distinguishes passive posts vs tasks, and reads subtrees", async () => { + const app = createLocalApp(); + + // Empty lazy channel read returns empty ChannelPage (no 404) + const emptyRead = await request(app) + .get(`/api/companies/${companyId}/channels/threads`) + .query({ channel: "#general" }) + .expect(200); + expect(emptyRead.body.kind).toBe("channel"); + expect(emptyRead.body.channel).toBe("general"); + expect(emptyRead.body.items).toEqual([]); + + // Passive post into #general + const generalPost = await request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .set("x-paperclip-actor-profile", "scout") + .send({ + channel: "#general", + text: "Build started on main\nMore context on line 2", + labels: { env: "ci" }, + }) + .expect(201); + + expect(generalPost.body.isPassivePost).toBe(true); + expect(generalPost.body.status).toBe("backlog"); + expect(generalPost.body.scope).toBe("channel"); + expect(generalPost.body.channel).toBe("general"); + expect(generalPost.body.actorProfile).toBe("scout"); + expect(generalPost.body.title).toBe("Build started on main"); + expect(generalPost.body.kvLabels).toEqual({ env: "ci" }); + + // Passive post into #security/findings and queued task into #security/triage + await request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .send({ + channel: "#security/findings", + text: "Found CORS wildcard", + labels: { severity: "high" }, + }) + .expect(201); + + const securityTask = await request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .send({ + channel: "security/triage", + status: "todo", + for: "@reviewer", + title: "Verify CORS fix", + }) + .expect(201); + + expect(securityTask.body.isPassivePost).toBe(false); + expect(securityTask.body.status).toBe("todo"); + expect(securityTask.body.assigneeAgentId).toBe(reviewerAgentId); + + // Subtree read on security/ includes both security/findings and security/triage, excludes general + const subtreeRes = await request(app) + .get(`/api/companies/${companyId}/channels/threads`) + .query({ channel: "security/" }) + .expect(200); + + expect(subtreeRes.body.kind).toBe("channel"); + expect(subtreeRes.body.channel).toBe("security/"); + const channelsReturned = subtreeRes.body.items + .map((i: { channel: string }) => i.channel) + .sort(); + expect(channelsReturned).toEqual(["security/findings", "security/triage"]); + + // Channel list reflects counts + const listRes = await request(app) + .get(`/api/companies/${companyId}/channels`) + .query({ prefix: "security/" }) + .expect(200); + expect(listRes.body.items).toHaveLength(2); + const triageCh = listRes.body.items.find( + (c: { path: string }) => c.path === "security/triage", + ); + expect(triageCh.threadCount).toBe(1); + expect(triageCh.openTaskCount).toBe(1); + expect(triageCh.readyTaskCount).toBe(0); // assigned to reviewer + + // Promote passive post in general from backlog -> todo via PATCH /issues/:id + const promoted = await request(app) + .patch(`/api/issues/${generalPost.body.identifier}`) + .send({ status: "todo", labels: { stage: "ready" } }) + .expect(200); + expect(promoted.body.id).toBe(generalPost.body.id); + expect(promoted.body.status).toBe("todo"); + expect(promoted.body.isPassivePost).toBe(false); + expect(promoted.body.kvLabels).toEqual({ env: "ci", stage: "ready" }); + }); + + it("2. enforces private channel isolation from non-members while allowing creator", async () => { + const app = createAuthenticatedApp(); + + // Owner creates private channel + const createdCh = await request(app) + .post(`/api/companies/${companyId}/channels`) + .set("x-test-user-id", ownerUserId) + .send({ + path: "exec/incident", + visibility: "private", + description: "Private incident room", + }) + .expect(201); + expect(createdCh.body.visibility).toBe("private"); + + const privPost = await request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .set("x-test-user-id", ownerUserId) + .send({ + channel: "exec/incident", + text: "Confidential incident summary", + }) + .expect(201); + + // Creator can list channel, read threads, and read issue + const ownerChannels = await request(app) + .get(`/api/companies/${companyId}/channels`) + .set("x-test-user-id", ownerUserId) + .expect(200); + expect( + ownerChannels.body.items.some( + (c: { path: string }) => c.path === "exec/incident", + ), + ).toBe(true); + + const ownerThreads = await request(app) + .get(`/api/companies/${companyId}/channels/threads`) + .set("x-test-user-id", ownerUserId) + .query({ channel: "exec/incident" }) + .expect(200); + expect(ownerThreads.body.items).toHaveLength(1); + + // Non-member peer cannot see private channel in list or read threads / issue + const peerChannels = await request(app) + .get(`/api/companies/${companyId}/channels`) + .set("x-test-user-id", peerUserId) + .expect(200); + expect( + peerChannels.body.items.some( + (c: { path: string }) => c.path === "exec/incident", + ), + ).toBe(false); + + await request(app) + .get(`/api/companies/${companyId}/channels/threads`) + .set("x-test-user-id", peerUserId) + .query({ channel: "exec/incident" }) + .expect(404); + + await request(app) + .get(`/api/issues/${privPost.body.identifier}`) + .set("x-test-user-id", peerUserId) + .expect(404); + + // Browser UI request with sec-fetch-mode delegates via next() to standard issueRoutes + const browserRes = await request(app) + .get(`/api/issues/${privPost.body.identifier}`) + .set("x-test-user-id", ownerUserId) + .set("sec-fetch-mode", "cors") + .expect(200); + expect(browserRes.body.delegatedToIssueRoutes).toBe(true); + }); + + it("3. enforces optimistic reply concurrency with after cursor", async () => { + const app = createLocalApp(); + + const thread = await request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .send({ channel: "general", text: "Discuss rollout" }) + .expect(201); + + // after: "none" succeeds when 0 comments exist + const c1 = await request(app) + .post(`/api/issues/${thread.body.identifier}/comments`) + .set("x-paperclip-actor-profile", "alice") + .send({ body: "First comment", after: "none" }) + .expect(201); + expect(c1.body.body).toBe("First comment"); + + // after matching c1.id succeeds + const c2 = await request(app) + .post(`/api/issues/${thread.body.identifier}/comments`) + .set("x-paperclip-actor-profile", "bob") + .send({ body: "Second comment", after: c1.body.id }) + .expect(201); + expect(c2.body.body).toBe("Second comment"); + + // Stale after: c1.id now fails with 409 stale_reply_cursor + const staleRes = await request(app) + .post(`/api/issues/${thread.body.identifier}/comments`) + .set("x-paperclip-actor-profile", "charlie") + .send({ body: "Stale comment", after: c1.body.id }) + .expect(409); + + expect(staleRes.body.code).toBe("stale_reply_cursor"); + expect(staleRes.body.details.latestCommentId).toBe(c2.body.id); + + // GET /issues/:id returns full ThreadDetailView with both comments + const detail = await request(app) + .get(`/api/issues/${thread.body.identifier}`) + .expect(200); + expect(detail.body.kind).toBe("thread"); + expect(detail.body.comments).toHaveLength(2); + }); + + it("4. performs atomic kv-labels CAS under concurrency and rejects reserved paperclip.* keys", async () => { + const app = createLocalApp(); + + const task = await request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .send({ + channel: "reviews", + status: "todo", + title: "Review PR #42", + labels: { stage: "review" }, + }) + .expect(201); + + // Concurrent CAS race: both require { stage: "review", reviewer: null } + const [resA, resB] = await Promise.all([ + request(app) + .patch(`/api/issues/${task.body.identifier}/kv-labels`) + .send({ + set: { reviewer: "agent-a", stage: "in_review" }, + if: { stage: "review", reviewer: null }, + }), + request(app) + .patch(`/api/issues/${task.body.identifier}/kv-labels`) + .send({ + set: { reviewer: "agent-b", stage: "in_review" }, + if: { stage: "review", reviewer: null }, + }), + ]); + + const statuses = [resA.status, resB.status].sort((a, b) => a - b); + expect(statuses).toEqual([200, 409]); + + const winner = resA.status === 200 ? resA : resB; + const loser = resA.status === 409 ? resA : resB; + + expect(winner.body.kvLabels.stage).toBe("in_review"); + expect(["agent-a", "agent-b"]).toContain(winner.body.kvLabels.reviewer); + expect(loser.body.code).toBe("label_conflict"); + expect(loser.body.details.conflictingKeys).toEqual(["stage", "reviewer"]); + + // Reserved paperclip.* key rejected with 400 + const reservedRes = await request(app) + .patch(`/api/issues/${task.body.identifier}/kv-labels`) + .send({ set: { "paperclip.pr": "https://github.com/org/repo/pull/1" } }) + .expect(400); + expect(reservedRes.body.code).toBe("reserved_label"); + }); + + it("5. validates built-in and custom immutable JSON schemas with fenced JSON fallback", async () => { + const app = createLocalApp(); + + // Built-in finding@1 works out of the box + const schemasList = await request(app) + .get(`/api/companies/${companyId}/schemas`) + .expect(200); + expect( + schemasList.body.items.some( + (s: { ref: string; builtIn: boolean }) => + s.ref === "finding@1" && s.builtIn === true, + ), + ).toBe(true); + + const findingPost = await request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .send({ + channel: "security/findings", + schema: { + ref: "finding@1", + data: { severity: "high", title: "SQLi in search" }, + }, + }) + .expect(201); + expect(findingPost.body.title).toBe("[finding@1]"); + expect(findingPost.body.description).toContain("```json"); + expect(findingPost.body.blocks).toEqual([ + { + schema: "finding", + version: 1, + data: { severity: "high", title: "SQLi in search" }, + }, + ]); + + // Register custom deploy-report@1 + const deploySchemaDef = { + type: "object", + required: ["env", "sha"], + additionalProperties: false, + properties: { + env: { type: "string", enum: ["staging", "prod"] }, + sha: { type: "string", minLength: 7 }, + }, + }; + + const createRes = await request(app) + .post(`/api/companies/${companyId}/schemas`) + .send({ + ref: "deploy-report@1", + description: "Deployment report", + jsonSchema: deploySchemaDef, + }) + .expect(201); + expect(createRes.body.created).toBe(true); + expect(createRes.body.schema.ref).toBe("deploy-report@1"); + + // Re-POST identical schema with reordered keys -> 200 created: false + const idempotentRes = await request(app) + .post(`/api/companies/${companyId}/schemas`) + .send({ + ref: "deploy-report@1", + jsonSchema: { + properties: { + sha: { minLength: 7, type: "string" }, + env: { enum: ["staging", "prod"], type: "string" }, + }, + additionalProperties: false, + required: ["env", "sha"], + type: "object", + }, + }) + .expect(200); + expect(idempotentRes.body.created).toBe(false); + + // Re-POST mutated deploy-report@1 -> 409 schema_version_immutable + const mutatedRes = await request(app) + .post(`/api/companies/${companyId}/schemas`) + .send({ + ref: "deploy-report@1", + jsonSchema: { + type: "object", + required: ["env", "sha", "actor"], + }, + }) + .expect(409); + expect(mutatedRes.body.code).toBe("schema_version_immutable"); + + // Invalid block against deploy-report@1 -> 422 schema_validation_failed + const badBlockRes = await request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .send({ + channel: "deploys", + blocks: [ + { + schema: "deploy-report", + version: 1, + data: { env: "dev", sha: "abc" }, + }, + ], + }) + .expect(422); + expect(badBlockRes.body.code).toBe("schema_validation_failed"); + expect(Array.isArray(badBlockRes.body.details.details)).toBe(true); + + // Valid block without text -> 201 with fenced JSON description + const goodBlockRes = await request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .send({ + channel: "deploys", + blocks: [ + { + schema: "deploy-report", + version: 1, + data: { env: "prod", sha: "deadbeef" }, + }, + ], + }) + .expect(201); + expect(goodBlockRes.body.title).toBe("[deploy-report@1]"); + expect(goodBlockRes.body.description).toContain("```json"); + expect(goodBlockRes.body.description).toContain("deadbeef"); + }); + + it("6. creates batch plan.json DAGs, enforces ready filter, rejects cycles, and replays idempotently", async () => { + const app = createLocalApp(); + + // Cycle rejected with 422 cyclic_dependencies + const cycleRes = await request(app) + .post(`/api/companies/${companyId}/issues/batch`) + .send({ + channel: "build/auth", + tasks: [ + { key: "a", title: "Task A", needs: ["b"] }, + { key: "b", title: "Task B", needs: ["a"] }, + ], + }) + .expect(422); + expect(cycleRes.body.code).toBe("cyclic_dependencies"); + + const planPayload = { + channel: "build/auth", + projectId: "web-app", + idempotencyKey: "plan-auth-001", + tasks: [ + { + key: "review", + projectId: null, + title: "Review auth patch", + needs: ["patch"], + labels: { role: "reviewer" }, + }, + { + key: "patch", + title: "Patch token check", + labels: { role: "worker" }, + }, + { + key: "audit", + projectId: apiProjectId, + title: "Audit API endpoints", + labels: { role: "worker" }, + }, + ], + }; + + const batchRes = await request(app) + .post(`/api/companies/${companyId}/issues/batch`) + .send(planPayload) + .expect(201); + + expect(batchRes.body.idempotentReplay).toBe(false); + expect(batchRes.body.tasks.map((t: { key: string }) => t.key)).toEqual([ + "patch", + "review", + "audit", + ]); + + const patchTask = batchRes.body.tasks.find( + (t: { key: string }) => t.key === "patch", + ); + const reviewTask = batchRes.body.tasks.find( + (t: { key: string }) => t.key === "review", + ); + const auditTask = batchRes.body.tasks.find( + (t: { key: string }) => t.key === "audit", + ); + + // Top-level projectId + per-task override (explicit null and UUID) + expect(patchTask.issue.projectId).toBe(webProjectId); + expect(reviewTask.issue.projectId).toBeNull(); + expect(auditTask.issue.projectId).toBe(apiProjectId); + expect(reviewTask.issue.blockedByIssueIds).toEqual([patchTask.id]); + + // Verify issue_relations row in Postgres + const relations = await db + .select() + .from(issueRelations) + .where( + and( + eq(issueRelations.companyId, companyId), + eq(issueRelations.relatedIssueId, reviewTask.id), + ), + ); + expect(relations).toHaveLength(1); + expect(relations[0]!.issueId).toBe(patchTask.id); + expect(relations[0]!.type).toBe("blocks"); + + // GET /api/companies/:companyId/issues?ready=true returns ONLY patch and audit (review is blocked by patch) + const readyRes = await request(app) + .get(`/api/companies/${companyId}/issues`) + .query({ channel: "build/auth", ready: "true" }) + .expect(200); + const readyIds = readyRes.body.items.map((i: { id: string }) => i.id).sort(); + expect(readyIds).toEqual([auditTask.id, patchTask.id].sort()); + + // Mark patch done -> review becomes ready! + await db + .update(issues) + .set({ status: "done", completedAt: new Date() }) + .where(eq(issues.id, patchTask.id)); + + const readyAfterDone = await request(app) + .get(`/api/companies/${companyId}/issues`) + .query({ channel: "build/auth", ready: "true", label: "role=reviewer" }) + .expect(200); + expect(readyAfterDone.body.items.map((i: { id: string }) => i.id)).toEqual([ + reviewTask.id, + ]); + + // Idempotency replay with same payload -> 200 idempotentReplay: true + const replayRes = await request(app) + .post(`/api/companies/${companyId}/issues/batch`) + .send(planPayload) + .expect(200); + expect(replayRes.body.idempotentReplay).toBe(true); + expect(replayRes.body.tasks.map((t: { id: string }) => t.id)).toEqual( + batchRes.body.tasks.map((t: { id: string }) => t.id), + ); + + // Idempotency conflict with different payload -> 409 idempotency_conflict + const conflictRes = await request(app) + .post(`/api/companies/${companyId}/issues/batch`) + .send({ + channel: "build/auth", + idempotencyKey: "plan-auth-001", + tasks: [{ key: "other", title: "Changed payload" }], + }) + .expect(409); + expect(conflictRes.body.code).toBe("idempotency_conflict"); + }); + + it("6. enforces issue/project/channel privacy on headless and canonical routes, guards channel metadata updates, and serializes concurrent batch idempotency", async () => { + 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` }, + }; + }, + }), + ); + app.use( + "/api", + headlessChannelsSchemasRoutes(db, { deploymentMode: "authenticated" }), + ); + app.use("/api", issueRoutes(db, { deploymentMode: "authenticated" } as any)); + app.use(errorHandler); + + // 1. Private channel persists visibility='private' and stays invisible across both headless & canonical routes + await request(app) + .post(`/api/companies/${companyId}/channels`) + .set("x-test-user-id", ownerUserId) + .send({ path: "exec/secret", visibility: "private" }) + .expect(201); + + const secretPost = await request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .set("x-test-user-id", ownerUserId) + .send({ channel: "exec/secret", text: "Private board plan" }) + .expect(201); + + const [secretRow] = await db + .select({ visibility: issues.visibility }) + .from(issues) + .where(eq(issues.id, secretPost.body.id)); + expect(secretRow?.visibility).toBe("private"); + + // Non-member peerUserId gets 404 on headless & canonical issue reads and mutations + await request(app) + .get(`/api/issues/${secretPost.body.identifier}`) + .set("x-test-user-id", peerUserId) + .expect(404); + await request(app) + .get(`/api/issues/${secretPost.body.identifier}?view=thread`) + .set("x-test-user-id", peerUserId) + .expect(404); + await request(app) + .get(`/api/issues/${secretPost.body.identifier}`) + .set("x-test-user-id", peerUserId) + .set("sec-fetch-mode", "cors") + .expect(404); + await request(app) + .patch(`/api/issues/${secretPost.body.identifier}`) + .set("x-test-user-id", peerUserId) + .send({ labels: { leaked: "true" } }) + .expect(404); + await request(app) + .post(`/api/issues/${secretPost.body.identifier}/comments`) + .set("x-test-user-id", peerUserId) + .send({ body: "Probe comment" }) + .expect(404); + await request(app) + .patch(`/api/issues/${secretPost.body.identifier}/kv-labels`) + .set("x-test-user-id", peerUserId) + .send({ set: { probe: "1" } }) + .expect(404); + + const canonicalListRes = await request(app) + .get(`/api/companies/${companyId}/issues?scope=channel`) + .set("x-test-user-id", peerUserId) + .expect(200); + expect(canonicalListRes.body.map((r: { id: string }) => r.id)).not.toContain( + secretPost.body.id, + ); + + // 2. Standalone private issue & private-project issue cannot be read via ?view=thread or mutated via headless PATCH/comments + const [privateProject] = await db + .insert(projects) + .values({ companyId, name: "Secret Project", visibility: "private" }) + .returning(); + const [privIssue] = await db + .insert(issues) + .values({ + companyId, + projectId: privateProject!.id, + visibility: "private", + title: "Top secret task", + status: "todo", + scope: "board", + issueNumber: 9001, + identifier: "PRIV-9001", + createdByUserId: ownerUserId, + responsibleUserId: ownerUserId, + }) + .returning(); + privIssue!.privacyRootIssueId = privIssue!.id; + await db + .update(issues) + .set({ privacyRootIssueId: privIssue!.id }) + .where(eq(issues.id, privIssue!.id)); + + await request(app) + .get(`/api/issues/${privIssue!.identifier}?view=thread`) + .set("x-test-user-id", peerUserId) + .expect(404); + await request(app) + .patch(`/api/issues/${privIssue!.identifier}`) + .set("x-test-user-id", peerUserId) + .send({ labels: { x: "y" } }) + .expect(404); + await request(app) + .post(`/api/issues/${privIssue!.identifier}/comments`) + .set("x-test-user-id", peerUserId) + .send({ body: "Should fail", kvLabels: { a: "b" } }) + .expect(404); + + // 3. Non-creator/non-admin peer cannot overwrite open channel metadata via POST /channels + await request(app) + .post(`/api/companies/${companyId}/channels`) + .set("x-test-user-id", ownerUserId) + .send({ path: "team/ops", description: "Ops channel" }) + .expect(201); + + await request(app) + .post(`/api/companies/${companyId}/channels`) + .set("x-test-user-id", peerUserId) + .send({ path: "team/ops", visibility: "private" }) + .expect(403); + + // 4. Concurrent batch requests with the same idempotencyKey create tasks only once + const concurrentPlan = { + channel: "team/ops", + idempotencyKey: "concurrent-batch-1", + tasks: [ + { key: "a", title: "Task A" }, + { key: "b", title: "Task B", needs: ["a"] }, + ], + }; + const [r1, r2] = await Promise.all([ + request(app) + .post(`/api/companies/${companyId}/issues/batch`) + .set("x-test-user-id", ownerUserId) + .send(concurrentPlan), + request(app) + .post(`/api/companies/${companyId}/issues/batch`) + .set("x-test-user-id", ownerUserId) + .send(concurrentPlan), + ]); + expect([r1.status, r2.status].sort()).toEqual([200, 201]); + const opsIssues = await db + .select({ id: issues.id }) + .from(issues) + .where(and(eq(issues.companyId, companyId), eq(issues.title, "Task A"))); + expect(opsIssues).toHaveLength(1); + }); + + it("8. inherits private ancestor visibility, rejects idempotency conflicts, and surfaces assigned channel tasks in Mine", async () => { + 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` }, + }; + }, + }), + ); + app.use( + "/api", + headlessChannelsSchemasRoutes(db, { deploymentMode: "authenticated" }), + ); + app.use("/api", issueRoutes(db, { deploymentMode: "authenticated" } as any)); + app.use(errorHandler); + + // 1. Private ancestor rejects explicit visibility='open' child and inherits visibility='private' when omitted + await request(app) + .post(`/api/companies/${companyId}/channels`) + .set("x-test-user-id", ownerUserId) + .send({ path: "exec/vault", visibility: "private" }) + .expect(201); + + await request(app) + .post(`/api/companies/${companyId}/channels`) + .set("x-test-user-id", ownerUserId) + .send({ path: "exec/vault/public-leak", visibility: "open" }) + .expect(403); + + const inheritedChild = await request(app) + .post(`/api/companies/${companyId}/channels`) + .set("x-test-user-id", ownerUserId) + .send({ path: "exec/vault/sub" }) + .expect(201); + expect(inheritedChild.body.visibility).toBe("private"); + + // 2. Idempotency key payload mismatch returns 409 idempotency_conflict + await request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .set("x-test-user-id", ownerUserId) + .send({ + channel: "eng/ci", + text: "Original payload", + idempotencyKey: "post-idem-1", + }) + .expect(201); + + const idemConflict = await request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .set("x-test-user-id", ownerUserId) + .send({ + channel: "eng/ci", + text: "Different payload", + idempotencyKey: "post-idem-1", + }) + .expect(409); + expect(idemConflict.body.code).toBe("idempotency_conflict"); + + // 3. Assigned scope='channel' task appears in Mine + unreadInboxIssueIds, while creator-only passive channel post stays hidden from Mine + const passiveChannelPost = await request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .set("x-test-user-id", ownerUserId) + .send({ channel: "eng/ci", text: "Passive CI chatter" }) + .expect(201); + + const assignedChannelTask = await request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .set("x-test-user-id", peerUserId) + .send({ + channel: "eng/ci", + status: "todo", + title: "Human action item", + }) + .expect(201); + + await db + .update(issues) + .set({ assigneeUserId: ownerUserId }) + .where(eq(issues.id, assignedChannelTask.body.id as string)); + + // External comments make assigned task unread while passive chatter stays hidden from Mine & unread + await request(app) + .post(`/api/issues/${assignedChannelTask.body.identifier}/comments`) + .set("x-test-user-id", peerUserId) + .send({ body: "Please handle this assigned channel task" }) + .expect(201); + await request(app) + .post(`/api/issues/${passiveChannelPost.body.identifier}/comments`) + .set("x-test-user-id", peerUserId) + .send({ body: "Passive channel reply" }) + .expect(201); + + const mineRes = await request(app) + .get(`/api/companies/${companyId}/issues?touchedByUserId=${encodeURIComponent(ownerUserId)}`) + .set("x-test-user-id", ownerUserId) + .expect(200); + const mineIds = (mineRes.body as Array<{ id: string }>).map((row) => row.id); + expect(mineIds).toContain(assignedChannelTask.body.id); + expect(mineIds).not.toContain(passiveChannelPost.body.id); + + const unreadIds = await issueService(db).unreadInboxIssueIds( + companyId, + ownerUserId, + sql`true`, + ); + expect(unreadIds).toContain(assignedChannelTask.body.id); + expect(unreadIds).not.toContain(passiveChannelPost.body.id); + }); + + it("7. enforces project:read in resolveProjectReference, filters tasks/threads in SQL before LIMIT, and cascades parent channel privatization", async () => { + 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` }, + }; + }, + }), + ); + app.use( + "/api", + headlessChannelsSchemasRoutes(db, { deploymentMode: "authenticated" }), + ); + app.use(errorHandler); + + // 1. Private project is rejected with 404 in channel defaultProjectId, post projectId, and batch projectId for non-members + const [privProj] = await db + .insert(projects) + .values({ companyId, name: "Locked Project", visibility: "private" }) + .returning(); + + await request(app) + .post(`/api/companies/${companyId}/channels`) + .set("x-test-user-id", peerUserId) + .send({ path: "proj-probe", defaultProjectId: privProj!.id }) + .expect(404); + await request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .set("x-test-user-id", peerUserId) + .send({ channel: "general", text: "Probe post", projectId: privProj!.id }) + .expect(404); + await request(app) + .post(`/api/companies/${companyId}/issues/batch`) + .set("x-test-user-id", peerUserId) + .send({ + channel: "general", + projectId: privProj!.id, + tasks: [{ key: "k1", title: "Should fail 404" }], + }) + .expect(404); + + // 2. Privatizing an open parent channel cascades visibility='private' to open descendant channels and issues + await request(app) + .post(`/api/companies/${companyId}/channels`) + .set("x-test-user-id", ownerUserId) + .send({ path: "cascade" }) + .expect(201); + const childPost = await request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .set("x-test-user-id", ownerUserId) + .send({ channel: "cascade/sub", text: "Initially open subchannel post" }) + .expect(201); + + await request(app) + .post(`/api/companies/${companyId}/channels`) + .set("x-test-user-id", ownerUserId) + .send({ path: "cascade", visibility: "private" }) + .expect(201); + + await request(app) + .get(`/api/issues/${childPost.body.identifier}?view=thread`) + .set("x-test-user-id", peerUserId) + .expect(404); + await request(app) + .get(`/api/companies/${companyId}/channels/threads?channel=cascade/sub`) + .set("x-test-user-id", peerUserId) + .expect(404); + + // 3. Matching label older than 260 newer nonmatching rows is still returned by GET /tasks and GET /channels/threads + const chRes = await request(app) + .post(`/api/companies/${companyId}/channels`) + .set("x-test-user-id", ownerUserId) + .send({ path: "bulk-filter" }) + .expect(201); + const bulkChannelId = chRes.body.id as string; + + const baseTime = Date.now() - 300_000; + const bulkRows: Array = []; + const oldMatchId = randomUUID(); + bulkRows.push({ + id: oldMatchId, + companyId, + channelId: bulkChannelId, + title: "Needle in haystack", + status: "todo", + scope: "channel", + priority: "medium", + issueNumber: 5000, + identifier: "NEEDLE-5000", + kvLabels: { env: "prod" }, + createdAt: new Date(baseTime - 10_000), + updatedAt: new Date(baseTime - 10_000), + }); + for (let i = 1; i <= 265; i += 1) { + bulkRows.push({ + companyId, + channelId: bulkChannelId, + title: `Noise task ${i}`, + status: "todo", + scope: "channel", + priority: "medium", + issueNumber: 5000 + i, + identifier: `NOISE-${5000 + i}`, + kvLabels: { env: "dev" }, + createdAt: new Date(baseTime + i * 100), + updatedAt: new Date(baseTime + i * 100), + }); + } + await db.insert(issues).values(bulkRows); + + const tasksRes = await request(app) + .get(`/api/companies/${companyId}/issues`) + .set("x-test-user-id", ownerUserId) + .query({ channel: "bulk-filter", label: "env=prod", limit: "1" }) + .expect(200); + expect(tasksRes.body.items.map((t: { id: string }) => t.id)).toEqual([oldMatchId]); + + const threadsRes = await request(app) + .get(`/api/companies/${companyId}/channels/threads`) + .set("x-test-user-id", ownerUserId) + .query({ channel: "bulk-filter", label: "env=prod", limit: "1" }) + .expect(200); + expect(threadsRes.body.items.map((t: { id: string }) => t.id)).toEqual([oldMatchId]); + + // 4. ready=true + status=done returns empty list rather than finished tasks + await db.insert(issues).values({ + companyId, + channelId: bulkChannelId, + title: "Already done", + status: "done", + scope: "channel", + priority: "medium", + issueNumber: 5999, + identifier: "DONE-5999", + }); + const readyDoneRes = await request(app) + .get(`/api/companies/${companyId}/issues`) + .set("x-test-user-id", ownerUserId) + .query({ channel: "bulk-filter", ready: "true", status: "done" }) + .expect(200); + expect(readyDoneRes.body.items).toEqual([]); + + // 5. Underscore '_' in channel path is NOT a SQL LIKE wildcard during privatization or prefix listing + await request(app) + .post(`/api/companies/${companyId}/channels`) + .set("x-test-user-id", ownerUserId) + .send({ path: "team_a" }) + .expect(201); + const decoyPost = await request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .set("x-test-user-id", ownerUserId) + .send({ channel: "teamxa/public", text: "Unrelated open channel with X instead of _" }) + .expect(201); + + await request(app) + .post(`/api/companies/${companyId}/channels`) + .set("x-test-user-id", ownerUserId) + .send({ path: "team_a", visibility: "private" }) + .expect(201); + + const listTeamA = await request(app) + .get(`/api/companies/${companyId}/channels`) + .set("x-test-user-id", ownerUserId) + .query({ prefix: "team_a" }) + .expect(200); + expect(listTeamA.body.items.map((c: { path: string }) => c.path)).toEqual(["team_a"]); + + const peerDecoyRead = await request(app) + .get(`/api/issues/${decoyPost.body.identifier}?view=thread`) + .set("x-test-user-id", peerUserId) + .expect(200); + expect(peerDecoyRead.body.issue.channel).toBe("teamxa/public"); + + // 6. Custom schema with catastrophic backtracking regex pattern is rejected cleanly with 400 + await request(app) + .post(`/api/companies/${companyId}/schemas`) + .set("x-test-user-id", ownerUserId) + .send({ + ref: "redos-test@1", + jsonSchema: { + type: "object", + properties: { + token: { type: "string", pattern: "^(a+)+$" }, + }, + }, + }) + .expect(400); + }); +}); diff --git a/server/src/__tests__/headless-e2e-sdk-cli.test.ts b/server/src/__tests__/headless-e2e-sdk-cli.test.ts new file mode 100644 index 00000000000..5bfcd5874ec --- /dev/null +++ b/server/src/__tests__/headless-e2e-sdk-cli.test.ts @@ -0,0 +1,506 @@ +import { execFile } from "node:child_process"; +import { mkdtemp, rm } from "node:fs/promises"; +import { createServer, type IncomingMessage, type Server as HttpServer } from "node:http"; +import type { AddressInfo } from "node:net"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { + createDb, + getEmbeddedPostgresTestSupport, + projects, + startEmbeddedPostgresTestDatabase, +} from "@paperclipai/db"; +import { PaperclipError, paperclip } from "@paperclipai/shared/sdk"; +import { createApp } from "../app.js"; +import type { StorageService } from "../storage/types.js"; + +const execFileAsync = promisify(execFile); +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const CLI_TSX_BIN = path.resolve(__dirname, "../../../cli/node_modules/.bin/tsx"); +const CLI_ENTRY = path.resolve(__dirname, "../../../cli/src/index.ts"); + +const noopStorage: StorageService = { + provider: "local_disk", + putFile: async () => ({ + provider: "local_disk", + objectKey: "noop", + contentType: "application/octet-stream", + byteSize: 0, + sha256: "0".repeat(64), + originalFilename: null, + }), + getObject: async () => { + throw new Error("not used in headless e2e test"); + }, + headObject: async () => ({ exists: false }), + deleteObject: async () => {}, +}; + +const external = process.env.PAPERCLIP_TEST_DATABASE_URL; +const support = external ? { supported: true } : await getEmbeddedPostgresTestSupport(); +const databaseSuite = support.supported ? describe : describe.skip; + +databaseSuite("Headless Paperclip full-stack E2E (createApp + SDK + pc CLI)", () => { + let db: ReturnType; + let temporary: Awaited> | undefined; + let server: HttpServer; + let apiBase: string; + let tempHomeDir: string; + let appShutdown: (() => Promise) | undefined; + + beforeAll(async () => { + tempHomeDir = await mkdtemp(path.join(os.tmpdir(), "pc-headless-e2e-")); + if (external) { + db = createDb(external); + } else { + temporary = await startEmbeddedPostgresTestDatabase("headless-e2e-"); + db = createDb(temporary.connectionString); + } + + const app = await createApp(db, { + uiMode: "none", + serverPort: 0, + storageService: noopStorage, + deploymentMode: "local_trusted", + deploymentExposure: "private", + allowedHostnames: ["127.0.0.1", "localhost"], + bindHost: "127.0.0.1", + authReady: true, + companyDeletionEnabled: true, + decisionServiceOptions: {} as never, + serverMetricsEnabled: false, + localPluginDir: path.join(tempHomeDir, "empty-plugins"), + }); + appShutdown = app.locals.paperclipShutdown as (() => Promise) | undefined; + + server = createServer(app); + await new Promise((resolve) => { + server.listen(0, "127.0.0.1", () => resolve()); + }); + const addr = server.address() as AddressInfo; + apiBase = `http://127.0.0.1:${addr.port}`; + }, 90_000); + + afterAll(async () => { + if (server) { + await new Promise((resolve) => server.close(() => resolve())); + } + await appShutdown?.(); + await db?.$client.end(); + await temporary?.cleanup(); + if (tempHomeDir) { + await rm(tempHomeDir, { recursive: true, force: true }).catch(() => {}); + } + }, 60_000); + + it("drives zero-ceremony channels, DAG queues, fenced leases, 1-liner ask/approve, CAS labels, and agent identity via paperclip() SDK", async () => { + const pc = paperclip({ apiBase, homeDir: tempHomeDir }); + + // 1. Minute-0 post auto-resolves/creates default company + lazy #general channel + const kickoff = await pc + .as("lead") + .post("general", "Ship v2\n\nAll headless primitives wired into createApp.", { + labels: { release: "v2" }, + }); + expect(kickoff.channel).toBe("general"); + expect(kickoff.scope).toBe("channel"); + expect(kickoff.status).toBe("backlog"); + expect(kickoff.isPassivePost).toBe(true); + expect(kickoff.actorProfile).toBe("lead"); + expect(kickoff.kvLabels).toEqual({ release: "v2" }); + + // Standard GET /api/issues/:id from a browser UI caller (with Referer) still returns the full standard Issue + const uiRes = await fetch(`${apiBase}/api/issues/${kickoff.id}`, { + headers: { referer: `${apiBase}/issues/${kickoff.identifier}` }, + }); + expect(uiRes.status).toBe(200); + const uiIssue = (await uiRes.json()) as { id: string; identifier: string; scope: string }; + expect(uiIssue.id).toBe(kickoff.id); + expect(uiIssue.scope).toBe("channel"); + + // Reply with --after optimistic concurrency + const firstReply = await pc.as("reviewer").reply(kickoff.identifier, "Looks solid!"); + await expect( + pc.as("other").reply(kickoff.identifier, "Stale reply", { after: "00000000-0000-0000-0000-000000000000" }), + ).rejects.toMatchObject({ status: 409, code: "stale_reply_cursor" }); + + const secondReply = await pc + .as("lead") + .reply(kickoff.identifier, "Confirmed after firstReply", { after: firstReply.id }); + expect(secondReply.actorProfile).toBe("lead"); + + const threadDetail = await pc.read(kickoff.identifier); + expect(threadDetail.kind).toBe("thread"); + if (threadDetail.kind === "thread") { + expect(threadDetail.comments.length).toBe(2); + } + + // 2. Create a real project so we can prove projectId resolution by slug on plan.json + await db.insert(projects).values({ + companyId: kickoff.companyId, + name: "Checkout Service", + status: "in_progress", + }); + + // 3. Register a custom immutable JSON Schema + const schemaCreated = await pc.schemas.create({ + name: "smoke-summary", + version: 1, + jsonSchema: { + type: "object", + required: ["passed", "durationMs"], + properties: { + passed: { type: "boolean" }, + durationMs: { type: "integer", minimum: 0 }, + }, + additionalProperties: false, + }, + }); + expect(schemaCreated.created).toBe(true); + + // 4. Submit a 2-step DAG plan with project slug + resultSchema + const plan = await pc.as("planner").tasks.createPlan( + "ci/checkout", + [ + { + key: "unit", + title: "Run unit suite", + priority: "high", + labels: { stage: "test" }, + }, + { + key: "e2e", + title: "Run checkout smoke", + needs: ["unit"], + resultSchema: "smoke-summary@1", + labels: { stage: "verify" }, + }, + ], + { + projectId: "checkout-service", + idempotencyKey: "plan-checkout-v1", + }, + ); + expect(plan.tasks).toHaveLength(2); + expect(plan.idempotentReplay).toBe(false); + expect(plan.tasks[0]!.issue.projectId).toBeTruthy(); + + // Idempotent replay returns exact same tasks + const planReplay = await pc.as("planner").tasks.createPlan( + "ci/checkout", + [ + { + key: "unit", + title: "Run unit suite", + priority: "high", + labels: { stage: "test" }, + }, + { + key: "e2e", + title: "Run checkout smoke", + needs: ["unit"], + resultSchema: "smoke-summary@1", + labels: { stage: "verify" }, + }, + ], + { + projectId: "checkout-service", + idempotencyKey: "plan-checkout-v1", + }, + ); + expect(planReplay.idempotentReplay).toBe(true); + expect(planReplay.tasks[0]!.id).toBe(plan.tasks[0]!.id); + + // 5. Claim from subtree "ci/" -> only "unit" is ready because "e2e" needs "unit" + const claimedUnit = await pc.as("worker-a").tasks.claim({ channel: "ci/", ready: true }); + expect(claimedUnit).not.toBeNull(); + expect(claimedUnit!.task.title).toBe("Run unit suite"); + expect(await pc.as("worker-b").tasks.claim({ channel: "ci/", ready: true })).toBeNull(); + + // Start waiting for "e2e" to become ready, then complete "unit" + const waitReadyPromise = pc.wait("ci/", { + event: "task.ready", + after: claimedUnit!.cursor, + timeout: "5s", + }); + await claimedUnit!.complete("Unit tests green"); + const readyEvent = await waitReadyPromise; + expect(readyEvent).not.toBeNull(); + expect(readyEvent!.issueId).toBe(plan.tasks[1]!.id); + + // 6. Claim "e2e", ask a humanOnly question (stateless pool auto-releases lease & blocks!), then approve + const claimedE2e = await pc.as("worker-b").tasks.claim({ channel: "ci/", ready: true }); + expect(claimedE2e).not.toBeNull(); + expect(claimedE2e!.task.id).toBe(plan.tasks[1]!.id); + + const asked = await claimedE2e!.ask("Approve production smoke target?", { + humanOnly: true, + }); + expect(asked.status).toBe("pending"); + + // Human approves -> requeues to todo! + const approved = await pc.approve(claimedE2e!.task.identifier, { + note: "Approved for staging-mirror", + }); + expect(approved.status).toBe("answered"); + + // Re-claim unblocked "e2e" and verify resultSchema enforcement on complete + const reclaimedE2e = await pc.as("worker-c").tasks.claim({ channel: "ci/", ready: true }); + expect(reclaimedE2e).not.toBeNull(); + expect(reclaimedE2e!.claimEpoch).toBeGreaterThan(claimedE2e!.claimEpoch); + + await expect( + reclaimedE2e!.complete({ data: { passed: "wrong-type" } as never }), + ).rejects.toMatchObject({ status: 422, code: "result_schema_validation_failed" }); + + const completedE2e = await reclaimedE2e!.complete({ + message: "Smoke passed", + data: { passed: true, durationMs: 412 }, + }); + expect(completedE2e.status).toBe("done"); + + // 7. Atomic CAS label update + const casOk = await pc.label(completedE2e.identifier, { + set: { stage: "shipped" }, + if: { stage: "verify" }, + }); + expect(casOk.kvLabels.stage).toBe("shipped"); + + await expect( + pc.label(completedE2e.identifier, { + set: { stage: "duplicate" }, + if: { stage: "verify" }, + }), + ).rejects.toMatchObject({ status: 409, code: "label_conflict" }); + + // 8. Connect a registered headless agent "@guard" -> unauthenticated --as guard fails 409! + const connectRes = await fetch( + `${apiBase}/api/companies/${kickoff.companyId}/agents/connect`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ name: "guard", role: "security" }), + }, + ); + expect(connectRes.status).toBe(201); + const connected = (await connectRes.json()) as { apiKey: string; agentId: string }; + + await expect(pc.as("guard").whoami()).rejects.toBeInstanceOf(PaperclipError); + await expect(pc.as("guard").whoami()).rejects.toMatchObject({ + status: 409, + code: "profile_matches_registered_agent", + }); + + const authedGuard = paperclip({ + apiBase, + apiKey: connected.apiKey, + homeDir: tempHomeDir, + }); + const guardWhoami = await authedGuard.whoami(); + expect(guardWhoami.principalType).toBe("agent"); + expect(guardWhoami.agentId).toBe(connected.agentId); + expect(guardWhoami.agentName).toBe("guard"); + }, 90_000); + + it("drives `pc` CLI persona including `tasks run` lease wrapper end-to-end", async () => { + const cliEnv = { + ...process.env, + HOME: tempHomeDir, + PAPERCLIP_HOME: path.join(tempHomeDir, ".paperclip"), + PAPERCLIP_API_URL: apiBase, + PAPERCLIP_CLI_PERSONA: "pc", + }; + + const runCli = async (args: string[]) => { + const { stdout } = await execFileAsync(CLI_TSX_BIN, [CLI_ENTRY, ...args], { + env: cliEnv, + timeout: 20_000, + }); + return stdout.trim(); + }; + + const whoamiJson = JSON.parse(await runCli(["whoami", "--json"])) as { + companyPrefix: string; + principalType: string; + }; + expect(whoamiJson.companyPrefix).toBe("PC"); + expect(whoamiJson.principalType).toBe("local_trusted"); + + const posted = JSON.parse( + await runCli([ + "post", + "deploys", + "Deployed commit abc1234", + "--as", + "release-bot", + "--label", + "env=staging", + "--json", + ]), + ) as { identifier: string; channel: string; isPassivePost: boolean }; + expect(posted.channel).toBe("deploys"); + expect(posted.isPassivePost).toBe(true); + + // Human-formatted `pc read ` omits `[backlog]` on passive posts and does not fail on tagLabels + const humanReadPost = await runCli(["read", posted.identifier]); + expect(humanReadPost).toContain(posted.identifier); + expect(humanReadPost).not.toContain("[backlog]"); + + // `pc channels list [prefix]`, `pc label --set --if k=null`, `pc schemas` / `get` / `create --version --schema` + const channelsOut = await runCli(["channels", "list", "deploys"]); + expect(channelsOut).toContain("#deploys"); + const labelOut = await runCli([ + "label", + posted.identifier, + "--set", + "stage=verified", + "--if", + "stage=null", + ]); + expect(labelOut).toContain("stage=verified"); + await runCli([ + "schemas", + "create", + "cli-smoke", + "--version", + "1", + "--schema", + '{"type":"object","required":["ok"],"properties":{"ok":{"type":"boolean"}}}', + ]); + const schemaInspect = await runCli(["schemas", "get", "cli-smoke@1"]); + expect(schemaInspect).toContain("cli-smoke@1"); + + const createdTask = JSON.parse( + await runCli([ + "tasks", + "create", + "runner-pool", + "Execute child wrapper test", + "--label", + "suite=cli", + "--json", + ]), + ) as { id: string; identifier: string; status: string }; + expect(createdTask.status).toBe("todo"); + + // `pc tasks` and `pc tasks list` without --channel include open channel tasks + const tasksDefaultOut = await runCli(["tasks"]); + expect(tasksDefaultOut).toContain(createdTask.identifier); + const tasksListOut = await runCli(["tasks", "list", "--label", "suite=cli"]); + expect(tasksListOut).toContain(createdTask.identifier); + + // `pc ask --choices --human-only` + `pc approve --answer` + `pc schedule list` / `cancel` + await runCli([ + "ask", + createdTask.identifier, + "Proceed with wrapper run?", + "--choices", + "yes,no", + "--human-only", + "--as", + "pool-runner", + ]); + await runCli(["approve", createdTask.identifier, "--answer", "yes"]); + const afterApproveRead = await runCli(["read", createdTask.identifier]); + expect(afterApproveRead).toContain("-> yes"); + + const schedId = await runCli([ + "schedule", + "deploys", + "Delayed check", + "--in", + "10m", + "--post", + "-q", + ]); + const schedListOut = await runCli(["schedule", "list"]); + expect(schedListOut).toContain(schedId); + await runCli(["schedule", "cancel", schedId]); + + // `pc wait` WITHOUT --after ignores historical `posted` in #deploys and blocks for the next new event! + const livePoster = paperclip({ apiBase, homeDir: tempHomeDir }).as("cron-bot"); + let waitRequestSeen = false; + let notifyWaitRequest: (() => void) | null = null; + const waitRequestArrived = new Promise((resolve) => { + notifyWaitRequest = resolve; + }); + const onServerRequest = (req: IncomingMessage) => { + if (!waitRequestSeen && req.url?.includes("/events/wait")) { + waitRequestSeen = true; + notifyWaitRequest?.(); + } + }; + server.on("request", onServerRequest); + let postInterval: ReturnType | null = null; + let waitedPing: { identifier: string | null; actor: { profile: string | null } }; + try { + const waitPromise = runCli([ + "wait", + "deploys", + "--event", + "thread.posted", + "--timeout", + "15s", + "--json", + ]); + await waitRequestArrived; + postInterval = setInterval(() => { + void livePoster.post("deploys", "Scheduled live ping"); + }, 250); + waitedPing = JSON.parse(await waitPromise) as { + identifier: string | null; + actor: { profile: string | null }; + }; + } finally { + server.off("request", onServerRequest); + if (postInterval) clearInterval(postInterval); + } + expect(waitedPing.actor.profile).toBe("cron-bot"); + expect(waitedPing.identifier).not.toBe(posted.identifier); + + // `pc agent connect` redacts PAPERCLIP_API_KEY on stdout while saving real key in 0600 profile + const connectStdout = await runCli([ + "agent", + "connect", + "cli-scanner", + "--role", + "engineer", + "--ttl", + "7d", + ]); + expect(connectStdout).toContain("pcp_••••••••"); + expect(connectStdout).not.toMatch(/PAPERCLIP_API_KEY='pcp_[A-Za-z0-9_-]{10,}'/); + const scannerWho = JSON.parse(await runCli(["whoami", "--as", "cli-scanner", "--json"])) as { + principalType: string; + agentName: string | null; + }; + expect(scannerWho.principalType).toBe("agent"); + expect(scannerWho.agentName).toBe("cli-scanner"); + + // `pc tasks run` claims the task, injects PAPERCLIP_* env vars, runs child with shell: false, and completes it! + await runCli([ + "tasks", + "run", + "--channel", + "runner-pool", + "--as", + "pool-runner", + "--lease", + "60s", + "--", + process.execPath, + "-e", + "if (!process.env.PAPERCLIP_TASK_ID || !process.env.PAPERCLIP_CLAIM_TOKEN) process.exit(2);", + ]); + + const pc = paperclip({ apiBase, homeDir: tempHomeDir }); + const afterRun = await pc.read(createdTask.identifier); + expect(afterRun.kind).toBe("thread"); + if (afterRun.kind === "thread") { + expect(afterRun.issue.status).toBe("done"); + } + }, 90_000); +}); diff --git a/server/src/__tests__/headless-identity-auth.test.ts b/server/src/__tests__/headless-identity-auth.test.ts new file mode 100644 index 00000000000..25bb88363dc --- /dev/null +++ b/server/src/__tests__/headless-identity-auth.test.ts @@ -0,0 +1,1290 @@ +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, + boardApiKeys, + channels, + cliAuthChallenges, + companies, + companyMemberships, + createDb, + getEmbeddedPostgresTestSupport, + instanceUserRoles, + issues, + principalPermissionGrants, + projects, + startEmbeddedPostgresTestDatabase, +} from "@paperclipai/db"; +import { findServerAdapter, listEnabledServerAdapters } from "../adapters/registry.js"; +import { actorMiddleware } from "../middleware/auth.js"; +import { errorHandler } from "../middleware/error-handler.js"; +import { accessRoutes } from "../routes/access.js"; +import { assertCompanyAccess } from "../routes/authz.js"; +import { agentRoutes } from "../routes/agents.js"; +import { headlessChannelsSchemasRoutes } from "../routes/headless-channels-schemas.js"; +import { headlessIdentityRoutes } from "../routes/headless-identity.js"; +import { headlessQueuesEventsRoutes } from "../routes/headless-queues-events.js"; +import { issueRoutes } from "../routes/issues.js"; +import { authorizationService, issueReadSqlCondition } from "../services/authorization.js"; +import { enforceHeadlessScopes, resolveHeadlessActor } from "../services/headless-common.js"; + +const external = process.env.PAPERCLIP_TEST_DATABASE_URL; +const support = external ? { supported: true } : await getEmbeddedPostgresTestSupport(); +const databaseSuite = support.supported ? describe : describe.skip; + +databaseSuite("Headless identity, auth & default company (real PostgreSQL)", () => { + let db: ReturnType; + let temporary: Awaited> | undefined; + + beforeAll(async () => { + if (external) { + db = createDb(external); + } else { + temporary = await startEmbeddedPostgresTestDatabase("headless-identity-"); + db = createDb(temporary.connectionString); + } + }, 60_000); + + afterAll(async () => { + await db?.$client.end(); + await temporary?.cleanup(); + }); + + beforeEach(async () => { + await db.delete(activityLog); + await db.delete(cliAuthChallenges); + await db.delete(boardApiKeys); + await db.delete(agentApiKeys); + await db.delete(issues); + await db.delete(channels); + await db.delete(projects); + await db.delete(agents); + await db.delete(principalPermissionGrants); + await db.delete(companyMemberships); + await db.delete(companies); + await db.delete(instanceUserRoles); + await db.delete(authUsers); + }); + + function buildLocalTrustedApp() { + const app = express(); + app.use(express.json()); + app.use( + actorMiddleware(db, { + deploymentMode: "local_trusted", + localAgentProcessBoundary: { + classify: async () => "operator", + grantsImplicitBoard: async () => true, + }, + }), + ); + app.use("/api", headlessIdentityRoutes(db, { deploymentMode: "local_trusted" })); + app.use( + "/api", + accessRoutes(db, { + deploymentMode: "local_trusted", + deploymentExposure: "private", + bindHost: "127.0.0.1", + allowedHostnames: [], + }), + ); + app.use(errorHandler); + return app; + } + + function buildAuthenticatedApp( + validUserIds: Set, + extraRoutes: express.Router[] = [], + ) { + const app = express(); + app.use(express.json()); + app.use( + actorMiddleware(db, { + deploymentMode: "authenticated", + resolveSession: async (req) => { + const userId = req.header("X-Test-Session"); + if (!userId || !validUserIds.has(userId)) return null; + return { + session: { id: `session-${userId}` }, + user: { + id: userId, + name: "Test User", + email: `${userId}@example.invalid`, + }, + } as never; + }, + }), + ); + app.use("/api", headlessIdentityRoutes(db, { deploymentMode: "authenticated" })); + for (const router of extraRoutes) { + app.use("/api", router); + } + app.use( + "/api", + accessRoutes(db, { + deploymentMode: "authenticated", + deploymentExposure: "private", + bindHost: "127.0.0.1", + allowedHostnames: [], + }), + ); + app.get("/api/test-scoped-read", async (req, res) => { + const companyId = req.header("x-test-company-id") ?? ""; + const channelPath = + typeof req.query.channel === "string" ? req.query.channel : undefined; + const action = + typeof req.query.action === "string" ? req.query.action : undefined; + const ctx = await resolveHeadlessActor(db, req, companyId, { + deploymentMode: "authenticated", + requiredAction: action, + requiredChannel: channelPath, + }); + enforceHeadlessScopes(ctx, { action, channelPath }); + res.json({ ok: true, actorProfile: ctx.actorProfile, scopes: ctx.scopes }); + }); + app.post("/api/test-scoped-write", async (req, res) => { + const companyId = req.header("x-test-company-id") ?? ""; + const action = + typeof req.query.action === "string" ? req.query.action : "issue.create"; + const ctx = await resolveHeadlessActor(db, req, companyId, { + deploymentMode: "authenticated", + requiredAction: action, + }); + res.json({ ok: true, actorProfile: ctx.actorProfile }); + }); + app.get("/api/test-canonical/:companyId", (req, res) => { + assertCompanyAccess(req, req.params.companyId); + res.json({ ok: true }); + }); + app.use(errorHandler); + return app; + } + + it("registers the pull-only headless adapter while excluding it from listEnabledServerAdapters", () => { + const headless = findServerAdapter("headless"); + expect(headless).not.toBeNull(); + expect(headless?.type).toBe("headless"); + expect(headless?.models).toEqual([]); + expect(listEnabledServerAdapters([]).some((a) => a.type === "headless")).toBe(false); + }); + + it("auto-creates a single default company in local_trusted mode idempotently across concurrent calls", async () => { + const app = buildLocalTrustedApp(); + + const results = await Promise.all([ + request(app).get("/api/companies/resolve-default"), + request(app).get("/api/companies/resolve-default"), + request(app).get("/api/companies/resolve-default"), + request(app).get("/api/companies/resolve-default"), + ]); + + for (const res of results) { + expect(res.status).toBe(200); + expect(res.body).toMatchObject({ + name: "Workspace", + issuePrefix: "PC", + agentIdentityPolicy: "open_local_profiles", + }); + } + + const uniqueIds = new Set(results.map((r) => r.body.id)); + expect(uniqueIds.size).toBe(1); + + const allCompanies = await db.select().from(companies); + expect(allCompanies).toHaveLength(1); + expect(allCompanies[0]?.defaultResponsibleUserId).toBe("local-board"); + + // Prefix / name lookup also resolves cleanly + const byPrefix = await request(app).get("/api/companies/resolve-default?company=pc"); + expect(byPrefix.status).toBe(200); + expect(byPrefix.body.id).toBe(allCompanies[0]!.id); + + const missing = await request(app).get("/api/companies/resolve-default?company=NOPE"); + expect(missing.status).toBe(404); + }); + + it("enforces agentIdentityPolicy on ephemeral profiles across open_local_profiles, delegated_profiles, and strict_agent_keys", async () => { + const app = buildLocalTrustedApp(); + const resolved = await request(app).get("/api/companies/resolve-default"); + expect(resolved.status).toBe(200); + const companyId = resolved.body.id as string; + + const openRes = await request(app) + .get("/api/whoami") + .set("X-Paperclip-Actor-Profile", "unregistered-bot"); + expect(openRes.status).toBe(200); + expect(openRes.body).toMatchObject({ + companyId, + principalType: "local_trusted", + actorProfile: "unregistered-bot", + agentIdentityPolicy: "open_local_profiles", + agentId: null, + agentName: null, + }); + + const patchDelegated = await request(app) + .patch(`/api/companies/${companyId}/agent-identity-policy`) + .send({ agentIdentityPolicy: "delegated_profiles" }); + expect(patchDelegated.status).toBe(200); + expect(patchDelegated.body.agentIdentityPolicy).toBe("delegated_profiles"); + + const delegatedRes = await request(app) + .get(`/api/whoami?companyId=${companyId}`) + .set("X-Paperclip-Actor-Profile", "unregistered-bot"); + expect(delegatedRes.status).toBe(200); + expect(delegatedRes.body).toMatchObject({ + companyId, + actorProfile: "unregistered-bot", + agentIdentityPolicy: "delegated_profiles", + }); + + const patchStrict = await request(app) + .patch(`/api/companies/${companyId}/agent-identity-policy`) + .send({ agentIdentityPolicy: "strict_agent_keys" }); + expect(patchStrict.status).toBe(200); + + const strictRes = await request(app) + .get(`/api/whoami?companyId=${companyId}`) + .set("X-Paperclip-Actor-Profile", "unregistered-bot"); + expect(strictRes.status).toBe(403); + expect(strictRes.body.code).toBe("agent_key_required"); + }); + + it("connects @scanner, blocks unauthenticated profile impersonation with 409, and authenticates Bearer agent key", async () => { + const app = buildLocalTrustedApp(); + const resolved = await request(app).get("/api/companies/resolve-default"); + const companyId = resolved.body.id as string; + + const connectRes = await request(app) + .post(`/api/companies/${companyId}/agents/connect`) + .send({ name: "scanner", role: "security" }); + expect(connectRes.status).toBe(201); + expect(connectRes.body.agentName).toBe("scanner"); + expect(connectRes.body.companyId).toBe(companyId); + expect(connectRes.body.apiKey).toMatch(/^pcp_/); + expect(connectRes.body.agent).toMatchObject({ + name: "scanner", + role: "security", + adapterType: "headless", + status: "active", + }); + + const scannerToken = connectRes.body.apiKey as string; + + // Attempting to impersonate @scanner without its API key fails closed with 409 + const impersonateRes = await request(app) + .get(`/api/whoami?companyId=${companyId}`) + .set("X-Paperclip-Actor-Profile", "scanner"); + expect(impersonateRes.status).toBe(409); + expect(impersonateRes.body.code).toBe("profile_matches_registered_agent"); + + // Authenticating with @scanner's Bearer key succeeds as principalType: "agent" + const agentWhoami = await request(app) + .get(`/api/whoami?companyId=${companyId}`) + .set("Authorization", `Bearer ${scannerToken}`); + expect(agentWhoami.status).toBe(200); + expect(agentWhoami.body).toMatchObject({ + companyId, + principalType: "agent", + agentId: connectRes.body.agentId, + agentName: "scanner", + actorProfile: "scanner", + }); + + // An agent key cannot connect/mint keys for other agents + const agentMintAttempt = await request(app) + .post(`/api/companies/${companyId}/agents/connect`) + .set("Authorization", `Bearer ${scannerToken}`) + .send({ name: "rogue-bot" }); + expect(agentMintAttempt.status).toBe(403); + }); + + it("enforces scoped board_api_keys (lockedProfile, companyId, scopes) and mints agent_api_key on agent_key CLI auth approval", async () => { + const userId = randomUUID(); + const companyAId = randomUUID(); + const companyBId = randomUUID(); + const now = new Date(); + + await db.insert(authUsers).values({ + id: userId, + name: "Board Owner", + email: `${userId}@example.invalid`, + createdAt: now, + updatedAt: now, + }); + await db.insert(companies).values([ + { id: companyAId, name: "Company Alpha", issuePrefix: "ALF", agentIdentityPolicy: "delegated_profiles" }, + { id: companyBId, name: "Company Beta", issuePrefix: "BET", agentIdentityPolicy: "delegated_profiles" }, + ]); + await db.insert(companyMemberships).values([ + { companyId: companyAId, principalType: "user", principalId: userId, status: "active", membershipRole: "owner" }, + { companyId: companyBId, principalType: "user", principalId: userId, status: "active", membershipRole: "owner" }, + ]); + await db.insert(principalPermissionGrants).values([ + { companyId: companyAId, principalType: "user", principalId: userId, permissionKey: "agents:create", grantedByUserId: userId }, + { companyId: companyAId, principalType: "user", principalId: userId, permissionKey: "agents:configure", grantedByUserId: userId }, + { companyId: companyBId, principalType: "user", principalId: userId, permissionKey: "agents:create", grantedByUserId: userId }, + { companyId: companyBId, principalType: "user", principalId: userId, permissionKey: "agents:configure", grantedByUserId: userId }, + ]); + + const app = buildAuthenticatedApp(new Set([userId])); + + // 1. Create a scoped board API key locked to companyAId, profile "ci-triage", and restricted scopes + const keyRes = await request(app) + .post("/api/board-api-keys") + .set("X-Test-Session", userId) + .send({ + name: "Scoped CI Key", + companyId: companyAId, + lockedProfile: "ci-triage", + scopes: { + channels: ["eng/*"], + actions: ["issue.read", "issue.comment"], + }, + expiresAt: "2099-01-01T00:00:00.000Z", + }); + expect(keyRes.status).toBe(201); + const scopedBoardToken = keyRes.body.token as string; + expect(scopedBoardToken).toMatch(/^pcp_board_/); + expect(keyRes.body.companyId).toBe(companyAId); + expect(keyRes.body.lockedProfile).toBe("ci-triage"); + + // resolve-default restricts to companyAId + const resolvedDefault = await request(app) + .get("/api/companies/resolve-default") + .set("Authorization", `Bearer ${scopedBoardToken}`); + expect(resolvedDefault.status).toBe(200); + expect(resolvedDefault.body.id).toBe(companyAId); + + const otherCompanyResolve = await request(app) + .get(`/api/companies/resolve-default?company=${companyBId}`) + .set("Authorization", `Bearer ${scopedBoardToken}`); + expect(otherCompanyResolve.status).toBe(404); + + // Passing a mismatched profile header fails with 403 profile_locked + const wrongProfile = await request(app) + .get(`/api/whoami?companyId=${companyAId}`) + .set("Authorization", `Bearer ${scopedBoardToken}`) + .set("X-Paperclip-Actor-Profile", "impostor"); + expect(wrongProfile.status).toBe(403); + expect(wrongProfile.body.code).toBe("profile_locked"); + + // Passing the matching profile (or no header) succeeds and reports the locked profile + scopes + const rightProfile = await request(app) + .get(`/api/whoami?companyId=${companyAId}`) + .set("Authorization", `Bearer ${scopedBoardToken}`); + expect(rightProfile.status).toBe(200); + expect(rightProfile.body).toMatchObject({ + companyId: companyAId, + principalType: "user", + userId, + actorProfile: "ci-triage", + scopes: { + channels: ["eng/*"], + actions: ["issue.read", "issue.comment"], + }, + }); + + // Scoped enforcement: allowed channel + action succeeds + const allowedAction = await request(app) + .get("/api/test-scoped-read?channel=eng/backend&action=issue.read") + .set("Authorization", `Bearer ${scopedBoardToken}`) + .set("x-test-company-id", companyAId); + expect(allowedAction.status).toBe(200); + + // Disallowed action fails with 403 scope_denied + const deniedAction = await request(app) + .get("/api/test-scoped-read?channel=eng/backend&action=issue.delete") + .set("Authorization", `Bearer ${scopedBoardToken}`) + .set("x-test-company-id", companyAId); + expect(deniedAction.status).toBe(403); + expect(deniedAction.body.code).toBe("scope_denied"); + + // Disallowed channel fails with 403 scope_denied + const deniedChannel = await request(app) + .get("/api/test-scoped-read?channel=ops/alerts&action=issue.read") + .set("Authorization", `Bearer ${scopedBoardToken}`) + .set("x-test-company-id", companyAId); + expect(deniedChannel.status).toBe(403); + expect(deniedChannel.body.code).toBe("scope_denied"); + + // 2. agent_key CLI auth challenge mints an agent_api_key without creating a board_api_keys row + const boardKeysBefore = await db.select().from(boardApiKeys); + + const challengeCreate = await request(app) + .post("/api/cli-auth/challenges") + .send({ + command: "paperclipai agent login --name triage-bot", + clientName: "paperclipai cli", + requestedAccess: "board", + requestedCompanyId: companyAId, + challengeKind: "agent_key", + agentName: "triage-bot", + agentRole: "qa", + }); + expect(challengeCreate.status).toBe(201); + const { id: challengeId, token: challengeSecret, boardApiToken: issuedAgentToken } = + challengeCreate.body as { + id: string; + token: string; + boardApiToken: string; + }; + expect(issuedAgentToken).toMatch(/^pcp_/); + + // Pending token cannot authenticate yet + const preApproveWhoami = await request(app) + .get(`/api/whoami?companyId=${companyAId}`) + .set("Authorization", `Bearer ${issuedAgentToken}`); + expect(preApproveWhoami.status).toBe(401); + + // Approve challenge as user + const approveRes = await request(app) + .post(`/api/cli-auth/challenges/${challengeId}/approve`) + .set("X-Test-Session", userId) + .send({ token: challengeSecret }); + expect(approveRes.status).toBe(200); + expect(approveRes.body).toMatchObject({ + approved: true, + status: "approved", + keyId: null, + companyId: companyAId, + }); + expect(approveRes.body.agentId).toBeTruthy(); + + // No new board_api_keys row was created + const boardKeysAfter = await db.select().from(boardApiKeys); + expect(boardKeysAfter).toHaveLength(boardKeysBefore.length); + + // Polling returns approved + agentId + companyId + const pollRes = await request(app).get( + `/api/cli-auth/challenges/${challengeId}?token=${encodeURIComponent(challengeSecret)}`, + ); + expect(pollRes.status).toBe(200); + expect(pollRes.body).toMatchObject({ + status: "approved", + challengeKind: "agent_key", + agentId: approveRes.body.agentId, + companyId: companyAId, + }); + + // The issued token now authenticates directly as agent @triage-bot + const postApproveWhoami = await request(app) + .get(`/api/whoami?companyId=${companyAId}`) + .set("Authorization", `Bearer ${issuedAgentToken}`); + expect(postApproveWhoami.status).toBe(200); + expect(postApproveWhoami.body).toMatchObject({ + companyId: companyAId, + principalType: "agent", + agentId: approveRes.body.agentId, + agentName: "triage-bot", + }); + + const [createdAgent] = await db + .select() + .from(agents) + .where(eq(agents.id, approveRes.body.agentId)); + expect(createdAgent).toMatchObject({ + companyId: companyAId, + name: "triage-bot", + role: "qa", + adapterType: "headless", + status: "active", + }); + }); + + it("enforces viewer read-only limits, prevents scope/key privilege escalation, and expires ttlSec agent keys", async () => { + const ownerId = randomUUID(); + const viewerId = randomUUID(); + const companyId = randomUUID(); + const now = new Date(); + + await db.insert(authUsers).values([ + { id: ownerId, name: "Owner", email: `${ownerId}@example.invalid`, createdAt: now, updatedAt: now }, + { id: viewerId, name: "Viewer", email: `${viewerId}@example.invalid`, createdAt: now, updatedAt: now }, + ]); + await db.insert(companies).values({ + id: companyId, + name: "Security Co", + issuePrefix: "SEC", + agentIdentityPolicy: "delegated_profiles", + }); + await db.insert(companyMemberships).values([ + { companyId, principalType: "user", principalId: ownerId, status: "active", membershipRole: "owner" }, + { companyId, principalType: "user", principalId: viewerId, status: "active", membershipRole: "viewer" }, + ]); + await db.insert(principalPermissionGrants).values([ + { companyId, principalType: "user", principalId: ownerId, permissionKey: "agents:create", grantedByUserId: ownerId }, + { companyId, principalType: "user", principalId: ownerId, permissionKey: "agents:configure", grantedByUserId: ownerId }, + ]); + + const app = buildAuthenticatedApp(new Set([ownerId, viewerId])); + + // 1. Viewer can read headless routes but is blocked from headless writes (403) + await request(app) + .get("/api/test-scoped-read?action=issue.read") + .set("X-Test-Session", viewerId) + .set("x-test-company-id", companyId) + .expect(200); + await request(app) + .post("/api/test-scoped-write?action=issue.create") + .set("X-Test-Session", viewerId) + .set("x-test-company-id", companyId) + .expect(403); + + // 2. Scoped board_key cannot call canonical company routes, connect agents, mint unrestricted child keys, or widen scopes via header + const scopedKeyRes = await request(app) + .post("/api/board-api-keys") + .set("X-Test-Session", ownerId) + .send({ + name: "Narrow Channel Key", + companyId, + lockedProfile: "narrow-bot", + scopes: { + channels: ["eng/backend"], + actions: ["issue.read", "issue.comment", "board_keys.create"], + }, + expiresAt: "2099-01-01T00:00:00.000Z", + }) + .expect(201); + const scopedToken = scopedKeyRes.body.token as string; + + // Canonical route rejects restricted board_key + await request(app) + .get(`/api/test-canonical/${companyId}`) + .set("Authorization", `Bearer ${scopedToken}`) + .expect(403); + + // Profile-locked / channel-scoped key cannot connect agent + await request(app) + .post(`/api/companies/${companyId}/agents/connect`) + .set("Authorization", `Bearer ${scopedToken}`) + .send({ name: "escalated-agent" }) + .expect(403); + + // Scoped key cannot mint unrestricted or wider-scoped board API key + await request(app) + .post("/api/board-api-keys") + .set("Authorization", `Bearer ${scopedToken}`) + .send({ name: "Wildcard Key", companyId }) + .expect(403); + + // Header attempting to widen ['eng/backend'] to ['eng/*'] is rejected for out-of-scope channel 'eng/frontend' + await request(app) + .get("/api/test-scoped-read?channel=eng/frontend&action=issue.read") + .set("Authorization", `Bearer ${scopedToken}`) + .set("x-test-company-id", companyId) + .set("X-Paperclip-Actor-Scopes", JSON.stringify({ channels: ["eng/*"] })) + .expect(403); + + // 3. connectAgent ttlSec sets expiresAt and expired agent API keys are rejected with 401 + const connectRes = await request(app) + .post(`/api/companies/${companyId}/agents/connect`) + .set("X-Test-Session", ownerId) + .send({ name: "ephemeral-bot", role: "qa", ttlSec: 60 }) + .expect(201); + const ephemeralToken = connectRes.body.apiKey as string; + const [keyRow] = await db + .select() + .from(agentApiKeys) + .where(eq(agentApiKeys.agentId, connectRes.body.agentId as string)); + expect(keyRow?.expiresAt).toBeInstanceOf(Date); + + await db + .update(agentApiKeys) + .set({ expiresAt: new Date(Date.now() - 5_000) }) + .where(eq(agentApiKeys.id, keyRow!.id)); + + await request(app) + .get(`/api/whoami?companyId=${companyId}`) + .set("Authorization", `Bearer ${ephemeralToken}`) + .expect(401); + }); + + it("requires agents:create + manage rights on connectAgent & agent_key CLI approval and denies instance_admin bypass on restricted board_keys", async () => { + const adminId = randomUUID(); + const memberId = randomUUID(); + const creatorId = randomUUID(); + const companyAId = randomUUID(); + const companyBId = randomUUID(); + const now = new Date(); + + await db.insert(authUsers).values([ + { id: adminId, name: "Inst Admin", email: `${adminId}@example.invalid`, createdAt: now, updatedAt: now }, + { id: memberId, name: "Plain Member", email: `${memberId}@example.invalid`, createdAt: now, updatedAt: now }, + { id: creatorId, name: "Creator", email: `${creatorId}@example.invalid`, createdAt: now, updatedAt: now }, + ]); + await db.insert(instanceUserRoles).values({ + userId: adminId, + role: "instance_admin", + }); + await db.insert(companies).values([ + { id: companyAId, name: "Authz Alpha", issuePrefix: "AA", agentIdentityPolicy: "delegated_profiles" }, + { id: companyBId, name: "Authz Beta", issuePrefix: "AB", agentIdentityPolicy: "delegated_profiles" }, + ]); + await db.insert(companyMemberships).values([ + { companyId: companyAId, principalType: "user", principalId: adminId, status: "active", membershipRole: "operator" }, + { companyId: companyAId, principalType: "user", principalId: memberId, status: "active", membershipRole: "member" }, + { companyId: companyAId, principalType: "user", principalId: creatorId, status: "active", membershipRole: "owner" }, + { companyId: companyBId, principalType: "user", principalId: creatorId, status: "active", membershipRole: "owner" }, + ]); + await db.insert(principalPermissionGrants).values([ + { companyId: companyAId, principalType: "user", principalId: creatorId, permissionKey: "agents:create", grantedByUserId: creatorId }, + { companyId: companyAId, principalType: "user", principalId: creatorId, permissionKey: "agents:configure", grantedByUserId: creatorId }, + ]); + + const [ceoAgent] = await db + .insert(agents) + .values({ + companyId: companyAId, + name: "ceo", + role: "ceo", + adapterType: "headless", + status: "idle", + }) + .returning(); + + const app = buildAuthenticatedApp(new Set([adminId, memberId, creatorId])); + app.use("/api", issueRoutes(db, { deploymentMode: "authenticated" } as any)); + app.get("/api/test-decide-issue", async (req, res) => { + const targetCompany = req.header("x-test-company-id")!; + const targetIssueId = req.header("x-test-issue-id")!; + const decision = await authorizationService(db).decide({ + actor: req.actor, + action: "issue:read", + resource: { type: "issue", companyId: targetCompany, issueId: targetIssueId }, + }); + const cond = await issueReadSqlCondition(db, req.actor); + const rows = await db + .select({ id: issues.id }) + .from(issues) + .where(eq(issues.id, targetIssueId)); + const readableRows = await db + .select({ id: issues.id }) + .from(issues) + .where(cond); + res.json({ + allowed: decision.allowed, + reason: decision.reason, + ignoreInstanceAdmin: Boolean(req.actor.ignoreInstanceAdmin), + total: rows.length, + readable: readableRows.some((r) => r.id === targetIssueId), + }); + }); + + // 1. Plain member without agents:create cannot connect existing 'ceo' or new agent + await request(app) + .post(`/api/companies/${companyAId}/agents/connect`) + .set("X-Test-Session", memberId) + .send({ name: ceoAgent!.name }) + .expect(403); + await request(app) + .post(`/api/companies/${companyAId}/agents/connect`) + .set("X-Test-Session", memberId) + .send({ name: "rogue-member-bot" }) + .expect(403); + + // 2. Plain member without agents:create cannot approve an agent_key CLI challenge for 'ceo' or new agent + const challengeRes = await request(app) + .post("/api/cli-auth/challenges") + .send({ + command: "paperclipai agent login --name ceo", + clientName: "paperclipai cli", + requestedAccess: "board", + requestedCompanyId: companyAId, + challengeKind: "agent_key", + agentName: "ceo", + }) + .expect(201); + await request(app) + .post(`/api/cli-auth/challenges/${challengeRes.body.id}/approve`) + .set("X-Test-Session", memberId) + .send({ token: challengeRes.body.token }) + .expect(403); + + // 3. Restricted board_key owned by instance_admin cannot elevate via instance_user_roles DB fallback + const [privProjB] = await db + .insert(projects) + .values({ companyId: companyBId, name: "Private Beta", visibility: "private" }) + .returning(); + const [privIssueB] = await db + .insert(issues) + .values({ + companyId: companyBId, + projectId: privProjB!.id, + visibility: "private", + title: "Secret in Beta", + status: "todo", + scope: "board", + issueNumber: 1, + identifier: "AB-1", + createdByUserId: creatorId, + responsibleUserId: creatorId, + }) + .returning(); + await db.update(issues).set({ privacyRootIssueId: privIssueB!.id }).where(eq(issues.id, privIssueB!.id)); + + const restrictedKey = await request(app) + .post("/api/board-api-keys") + .set("X-Test-Session", adminId) + .send({ + name: "Scopes-Only Key", + scopes: { actions: ["*"] }, + expiresAt: "2099-01-01T00:00:00.000Z", + }) + .expect(201); + + const probe = await request(app) + .get("/api/test-decide-issue") + .set("Authorization", `Bearer ${restrictedKey.body.token}`) + .set("x-test-company-id", companyBId) + .set("x-test-issue-id", privIssueB!.id) + .expect(200); + expect(probe.body).toMatchObject({ + allowed: false, + ignoreInstanceAdmin: true, + readable: false, + }); + }); + + it("blocks channel-scoped board_api_key (scopes.channels=['build/*']) from reading or mutating unchanneled board issues", async () => { + const ownerId = randomUUID(); + const companyId = randomUUID(); + const now = new Date(); + await db.insert(authUsers).values({ + id: ownerId, + name: "Scope Owner", + email: `${ownerId}@example.invalid`, + createdAt: now, + updatedAt: now, + }); + await db.insert(companies).values({ + id: companyId, + name: "Scoped Key Org", + issuePrefix: "SKO", + agentIdentityPolicy: "delegated_profiles", + }); + await db.insert(companyMemberships).values({ + companyId, + principalType: "user", + principalId: ownerId, + status: "active", + membershipRole: "owner", + }); + + const [unchanneledIssue] = await db + .insert(issues) + .values({ + companyId, + channelId: null, + title: "Board-level confidential task", + status: "todo", + scope: "board", + priority: "medium", + issueNumber: 1, + identifier: "SKO-1", + createdByUserId: ownerId, + responsibleUserId: ownerId, + }) + .returning(); + + const app = buildAuthenticatedApp(new Set([ownerId]), [ + headlessChannelsSchemasRoutes(db, { deploymentMode: "authenticated" }), + headlessQueuesEventsRoutes(db, { deploymentMode: "authenticated" }), + issueRoutes(db, { deploymentMode: "authenticated" } as any), + ]); + const scopedKeyRes = await request(app) + .post("/api/board-api-keys") + .set("X-Test-Session", ownerId) + .send({ + name: "Build Channel Only", + companyId, + scopes: { channels: ["build/*"] }, + expiresAt: "2099-01-01T00:00:00.000Z", + }) + .expect(201); + const scopedToken = scopedKeyRes.body.token as string; + + // Seed one issue in #build/ci and verify matching channel succeeds while unchanneled SKO-1 is denied across every headless handler + await request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .set("Authorization", `Bearer ${scopedToken}`) + .send({ channel: "build/ci", text: "In-scope post" }) + .expect(201); + + await request(app) + .get(`/api/issues/${unchanneledIssue!.identifier}?view=thread`) + .set("Authorization", `Bearer ${scopedToken}`) + .expect(403); + await request(app) + .post(`/api/issues/${unchanneledIssue!.identifier}/comments`) + .set("Authorization", `Bearer ${scopedToken}`) + .send({ body: "Out of scope comment" }) + .expect(403); + await request(app) + .patch(`/api/issues/${unchanneledIssue!.identifier}/kv-labels`) + .set("Authorization", `Bearer ${scopedToken}`) + .send({ set: { hijacked: "1" } }) + .expect(403); + await request(app) + .patch(`/api/issues/${unchanneledIssue!.identifier}`) + .set("Authorization", `Bearer ${scopedToken}`) + .send({ status: "done" }) + .expect(403); + await request(app) + .patch(`/api/issues/${unchanneledIssue!.identifier}`) + .set("Authorization", `Bearer ${scopedToken}`) + .send({ status: "done", labels: { hijacked: "1" } }) + .expect(403); + await request(app) + .post(`/api/issues/${unchanneledIssue!.identifier}/claim/complete`) + .set("Authorization", `Bearer ${scopedToken}`) + .send({ text: "Hijacked completion" }) + .expect(403); + await request(app) + .post(`/api/issues/${unchanneledIssue!.identifier}/ask`) + .set("Authorization", `Bearer ${scopedToken}`) + .send({ question: "Block?", choices: ["yes", "no"] }) + .expect(403); + await request(app) + .post(`/api/issues/${unchanneledIssue!.identifier}/approve`) + .set("Authorization", `Bearer ${scopedToken}`) + .send({ note: "Hijacked approval" }) + .expect(403); + await request(app) + .post(`/api/companies/${companyId}/schedules`) + .set("Authorization", `Bearer ${scopedToken}`) + .send({ target: unchanneledIssue!.identifier, message: "Ping", in: "5m" }) + .expect(403); + + // Disjoint X-Paperclip-Actor-Scopes header narrows to empty [] (deny-all), NEVER widens to unrestricted + const disjointList = await request(app) + .get(`/api/companies/${companyId}/issues?headless=1`) + .set("Authorization", `Bearer ${scopedToken}`) + .set("X-Paperclip-Actor-Scopes", JSON.stringify({ channels: ["other"] })) + .expect(200); + expect(disjointList.body.items).toEqual([]); + await request(app) + .get(`/api/issues/${unchanneledIssue!.identifier}?view=thread`) + .set("Authorization", `Bearer ${scopedToken}`) + .set("X-Paperclip-Actor-Scopes", JSON.stringify({ channels: ["other"] })) + .expect(403); + }); + + it("blocks board_api_keys from approving CLI challenges and restricts key-management and /cli-auth/me metadata", async () => { + const adminId = randomUUID(); + const companyAId = randomUUID(); + const companyBId = randomUUID(); + const now = new Date(); + await db.insert(authUsers).values({ + id: adminId, + name: "Key Admin", + email: `${adminId}@example.invalid`, + createdAt: now, + updatedAt: now, + }); + await db.insert(instanceUserRoles).values({ + userId: adminId, + role: "instance_admin", + }); + await db.insert(companies).values([ + { id: companyAId, name: "Scoped Co A", issuePrefix: "SCA", agentIdentityPolicy: "delegated_profiles" }, + { id: companyBId, name: "Scoped Co B", issuePrefix: "SCB", agentIdentityPolicy: "delegated_profiles" }, + ]); + await db.insert(companyMemberships).values([ + { companyId: companyAId, principalType: "user", principalId: adminId, status: "active", membershipRole: "owner" }, + { companyId: companyBId, principalType: "user", principalId: adminId, status: "active", membershipRole: "owner" }, + ]); + const [agentA] = await db + .insert(agents) + .values({ + companyId: companyAId, + name: "key-agent-a", + role: "engineer", + adapterType: "headless", + status: "idle", + }) + .returning(); + + const app = buildAuthenticatedApp(new Set([adminId]), [ + agentRoutes(db), + ]); + + // Seed an unrestricted board key plus three restricted variants (company-scoped, profile-locked, channel-scoped) + const targetKeyRes = await request(app) + .post("/api/board-api-keys") + .set("X-Test-Session", adminId) + .send({ name: "Target Unrestricted", expiresAt: "2099-01-01T00:00:00.000Z" }) + .expect(201); + const companyKeyRes = await request(app) + .post("/api/board-api-keys") + .set("X-Test-Session", adminId) + .send({ name: "Company A Only", companyId: companyAId, expiresAt: "2099-01-01T00:00:00.000Z" }) + .expect(201); + const profileKeyRes = await request(app) + .post("/api/board-api-keys") + .set("X-Test-Session", adminId) + .send({ name: "Profile Locked", lockedProfile: "scanner", expiresAt: "2099-01-01T00:00:00.000Z" }) + .expect(201); + const channelKeyRes = await request(app) + .post("/api/board-api-keys") + .set("X-Test-Session", adminId) + .send({ name: "Channel Scoped", scopes: { channels: ["build/*"] }, expiresAt: "2099-01-01T00:00:00.000Z" }) + .expect(201); + + const challenge = await request(app) + .post("/api/cli-auth/challenges") + .send({ command: "paperclipai auth login", clientName: "cli", requestedAccess: "board" }) + .expect(201); + + for (const restricted of [companyKeyRes.body, profileKeyRes.body, channelKeyRes.body]) { + const tok = restricted.token as string; + // 1. Cannot approve CLI auth challenges to mint an unrestricted key + await request(app) + .post(`/api/cli-auth/challenges/${challenge.body.id}/approve`) + .set("Authorization", `Bearer ${tok}`) + .send({ token: challenge.body.token }) + .expect(403); + // 2. Cannot list or revoke other board API keys + await request(app) + .get("/api/board-api-keys") + .set("Authorization", `Bearer ${tok}`) + .expect(403); + await request(app) + .delete(`/api/board-api-keys/${targetKeyRes.body.id}`) + .set("Authorization", `Bearer ${tok}`) + .expect(403); + } + + // 3. Company-scoped key /cli-auth/me hides other companies and instance-admin status + const meRes = await request(app) + .get("/api/cli-auth/me") + .set("Authorization", `Bearer ${companyKeyRes.body.token}`) + .expect(200); + expect(meRes.body.isInstanceAdmin).toBe(false); + expect(meRes.body.companyIds).toEqual([companyAId]); + expect(meRes.body.memberships.map((m: { companyId: string }) => m.companyId)).toEqual([companyAId]); + + // 4. Scoped & profile-locked board keys cannot list or revoke agent API keys + for (const restricted of [profileKeyRes.body, channelKeyRes.body]) { + const tok = restricted.token as string; + await request(app) + .get(`/api/agents/${agentA!.id}/keys`) + .set("Authorization", `Bearer ${tok}`) + .expect(403); + await request(app) + .delete(`/api/agents/${agentA!.id}/keys/${randomUUID()}`) + .set("Authorization", `Bearer ${tok}`) + .expect(403); + } + + // 5. Self-revocation via /cli-auth/revoke-current remains permitted + await request(app) + .post("/api/cli-auth/revoke-current") + .set("Authorization", `Bearer ${companyKeyRes.body.token}`) + .expect(200); + }); + + it("blocks skill_test and task_bridge agent API keys across headless channel, queue, and identity endpoints", async () => { + const companyId = randomUUID(); + const adminId = randomUUID(); + await db.insert(authUsers).values({ + id: adminId, + name: "Admin", + email: "admin-scope@example.invalid", + emailVerified: true, + createdAt: new Date(), + updatedAt: new Date(), + }); + await db.insert(companies).values({ + id: companyId, + name: "Scoped Agent Key Corp", + issuePrefix: "SAK", + }); + await db.insert(companyMemberships).values({ + companyId, + principalType: "user", + principalId: adminId, + membershipRole: "owner", + status: "active", + }); + await db.insert(channels).values({ + companyId, + path: "general", + visibility: "open", + }); + const [agent] = await db + .insert(agents) + .values({ + companyId, + name: "scoped-runner", + role: "engineer", + adapterType: "headless", + status: "idle", + }) + .returning(); + + const allowedIssueId = randomUUID(); + await db.insert(issues).values({ + id: allowedIssueId, + companyId, + title: "Scoped harness issue", + status: "in_progress", + issueNumber: 1, + identifier: "SAK-1", + }); + const skillToken = "pcp_skill_test_token_12345"; + const bridgeToken = "pcp_task_bridge_token_67890"; + await db.insert(agentApiKeys).values([ + { + agentId: agent!.id, + companyId, + name: "skill-test-key", + keyHash: createHash("sha256").update(skillToken).digest("hex"), + responsibleUserId: adminId, + scopeConfig: { + kind: "skill_test", + issueId: allowedIssueId, + }, + }, + { + agentId: agent!.id, + companyId, + name: "task-bridge-key", + keyHash: createHash("sha256").update(bridgeToken).digest("hex"), + responsibleUserId: adminId, + scopeConfig: { + kind: "task_bridge", + parentIssueId: allowedIssueId, + projectIds: [], + allowedAssigneeAgentIds: [], + }, + }, + ]); + + expect(() => + enforceHeadlessScopes( + { scopes: null, keyScope: { kind: "skill_test", issueId: allowedIssueId } }, + { action: "read" }, + ), + ).toThrow(/cannot access headless/); + expect(() => + enforceHeadlessScopes( + { + scopes: null, + keyScope: { + kind: "task_bridge", + parentIssueId: allowedIssueId, + projectIds: [], + allowedAssigneeAgentIds: [], + }, + }, + { action: "tasks.claim" }, + ), + ).toThrow(/cannot access headless/); + + const app = buildAuthenticatedApp(new Set([adminId]), [ + headlessChannelsSchemasRoutes(db, { deploymentMode: "authenticated" }), + headlessQueuesEventsRoutes(db, { deploymentMode: "authenticated" }), + ]); + + for (const token of [skillToken, bridgeToken]) { + const resolveRes = await request(app) + .get("/api/companies/resolve-default") + .set("Authorization", `Bearer ${token}`) + .expect(403); + expect(resolveRes.body.code).toBe("scope_denied"); + + const chRes = await request(app) + .get(`/api/companies/${companyId}/channels`) + .set("Authorization", `Bearer ${token}`) + .expect(403); + expect(chRes.body.code).toBe("scope_denied"); + + const threadsRes = await request(app) + .get(`/api/companies/${companyId}/channels/threads?channel=general`) + .set("Authorization", `Bearer ${token}`) + .expect(403); + expect(threadsRes.body.code).toBe("scope_denied"); + + const postRes = await request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .set("Authorization", `Bearer ${token}`) + .send({ channel: "general", message: "Bypass attempt" }) + .expect(403); + expect(postRes.body.code).toBe("scope_denied"); + + const schemasRes = await request(app) + .get(`/api/companies/${companyId}/schemas`) + .set("Authorization", `Bearer ${token}`) + .expect(403); + expect(schemasRes.body.code).toBe("scope_denied"); + + const issuesRes = await request(app) + .get(`/api/companies/${companyId}/issues?ready=true`) + .set("Authorization", `Bearer ${token}`) + .expect(403); + expect(issuesRes.body.code).toBe("scope_denied"); + + const waitRes = await request(app) + .get(`/api/companies/${companyId}/events/wait?timeoutMs=0`) + .set("Authorization", `Bearer ${token}`) + .expect(403); + expect(waitRes.body.code).toBe("scope_denied"); + + const scheduleRes = await request(app) + .post(`/api/companies/${companyId}/schedules`) + .set("Authorization", `Bearer ${token}`) + .send({ target: "general", message: "Bypass ping", in: "1m" }) + .expect(403); + expect(scheduleRes.body.code).toBe("scope_denied"); + + const claimRes = await request(app) + .post(`/api/companies/${companyId}/tasks/claim`) + .set("Authorization", `Bearer ${token}`) + .send({ channel: "general", wait: 0 }) + .expect(403); + expect(claimRes.body.code).toBe("scope_denied"); + + const askRes = await request(app) + .post(`/api/issues/${allowedIssueId}/ask`) + .set("Authorization", `Bearer ${token}`) + .send({ question: "Bypass ask?" }) + .expect(403); + expect(askRes.body.code).toBe("scope_denied"); + + const whoRes = await request(app) + .get(`/api/whoami?companyId=${companyId}`) + .set("Authorization", `Bearer ${token}`) + .expect(403); + expect(whoRes.body.code).toBe("scope_denied"); + } + }); + + it("enforces requireBoardApprovalForNewAgents on connectAgent and agent_key CLI approval", async () => { + const ownerId = randomUUID(); + const companyId = randomUUID(); + const now = new Date(); + await db.insert(authUsers).values({ + id: ownerId, + name: "Approval Owner", + email: `${ownerId}@example.invalid`, + createdAt: now, + updatedAt: now, + }); + await db.insert(companies).values({ + id: companyId, + name: "Approval Gate Org", + issuePrefix: "AGO", + agentIdentityPolicy: "strict_agent_keys", + requireBoardApprovalForNewAgents: true, + }); + await db.insert(companyMemberships).values({ + companyId, + principalType: "user", + principalId: ownerId, + status: "active", + membershipRole: "owner", + }); + await db.insert(principalPermissionGrants).values([ + { companyId, principalType: "user", principalId: ownerId, permissionKey: "agents:create", grantedByUserId: ownerId }, + { companyId, principalType: "user", principalId: ownerId, permissionKey: "agents:configure", grantedByUserId: ownerId }, + ]); + + const [approvedAgent, pendingAgent] = await db + .insert(agents) + .values([ + { + companyId, + name: "approved-worker", + role: "engineer", + adapterType: "headless", + status: "idle", + }, + { + companyId, + name: "pending-worker", + role: "engineer", + adapterType: "headless", + status: "pending_approval", + }, + ]) + .returning(); + + const app = buildAuthenticatedApp(new Set([ownerId])); + + // 1. Direct new-agent creation via connectAgent returns 409 when requireBoardApprovalForNewAgents=true + const newConnectRes = await request(app) + .post(`/api/companies/${companyId}/agents/connect`) + .set("X-Test-Session", ownerId) + .send({ name: "unapproved-connect-bot", role: "engineer" }) + .expect(409); + expect(newConnectRes.body.code).toBe("board_approval_required"); + + // 2. Direct new-agent creation via agent_key CLI challenge approval returns 409 + const challengeRes = await request(app) + .post("/api/cli-auth/challenges") + .send({ + command: "paperclipai agent login --name unapproved-cli-bot", + clientName: "paperclipai cli", + requestedAccess: "board", + requestedCompanyId: companyId, + challengeKind: "agent_key", + agentName: "unapproved-cli-bot", + }) + .expect(201); + const approveNewRes = await request(app) + .post(`/api/cli-auth/challenges/${challengeRes.body.id}/approve`) + .set("X-Test-Session", ownerId) + .send({ token: challengeRes.body.token }) + .expect(409); + expect(approveNewRes.body.code).toBe("board_approval_required"); + + // 3. Pending-approval agents cannot be issued keys before approval + await request(app) + .post(`/api/companies/${companyId}/agents/connect`) + .set("X-Test-Session", ownerId) + .send({ name: pendingAgent!.name }) + .expect(409); + + // 4. Existing approved agents can still mint keys via both connectAgent and agent_key approval + const existingConnectRes = await request(app) + .post(`/api/companies/${companyId}/agents/connect`) + .set("X-Test-Session", ownerId) + .send({ name: approvedAgent!.name }) + .expect(201); + expect(existingConnectRes.body.agentId).toBe(approvedAgent!.id); + + const existingChallengeRes = await request(app) + .post("/api/cli-auth/challenges") + .send({ + command: `paperclipai agent login --name ${approvedAgent!.name}`, + clientName: "paperclipai cli", + requestedAccess: "board", + requestedCompanyId: companyId, + challengeKind: "agent_key", + agentName: approvedAgent!.name, + }) + .expect(201); + const approveExistingRes = await request(app) + .post(`/api/cli-auth/challenges/${existingChallengeRes.body.id}/approve`) + .set("X-Test-Session", ownerId) + .send({ token: existingChallengeRes.body.token }) + .expect(200); + expect(approveExistingRes.body.agentId).toBe(approvedAgent!.id); + + const companyAgents = await db + .select({ name: agents.name }) + .from(agents) + .where(eq(agents.companyId, companyId)); + expect(companyAgents.map((a) => a.name).sort()).toEqual([ + "approved-worker", + "pending-worker", + ]); + }); +}); diff --git a/server/src/__tests__/headless-queues-leases-events.test.ts b/server/src/__tests__/headless-queues-leases-events.test.ts new file mode 100644 index 00000000000..e3cf468ed59 --- /dev/null +++ b/server/src/__tests__/headless-queues-leases-events.test.ts @@ -0,0 +1,1565 @@ +import { randomUUID } from "node:crypto"; +import { createServer, type Server as HttpServer } from "node:http"; +import express from "express"; +import { and, eq, sql } from "drizzle-orm"; +import { + afterAll, + afterEach, + beforeAll, + describe, + expect, + it, + vi, +} from "vitest"; +import { + agents, + authUsers, + boardEvents, + channels, + companies, + companyMemberships, + companySchemas, + createDb, + executionWorkspaces, + issueAccessGrants, + issueComments, + issueRelations, + issues, + issueThreadInteractions, + issueTreeHolds, + issueWorkProducts, + projectAccessMembers, + projects, + reconcileDatabaseWork, + scheduledBoardPosts, + workspaceOperations, + type Db, +} from "@paperclipai/db"; +import { + type BoardEventView, + type HeadlessIssueView, + type InteractionView, + type ScheduleView, + type TaskClaimView, +} from "@paperclipai/shared"; +import { parseSseEventStream } from "@paperclipai/shared/sdk/sse"; +import { actorMiddleware } from "../middleware/auth.js"; +import { errorHandler } from "../middleware/error-handler.js"; +import { headlessQueuesEventsRoutes } from "../routes/headless-queues-events.js"; +import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js"; +import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js"; +import { + appendBoardEvent, + publishCommittedBoardEvent, +} from "../services/headless-common.js"; +import { createScheduledBoardPostsWorker } from "../services/headless-events-schedules-interactions.js"; +import { createClaimLeaseExpiryWorker } from "../services/headless-task-queue.js"; +import { issueThreadInteractionService } from "../services/issue-thread-interactions.js"; +import { recoveryService } from "../services/recovery/service.js"; +import { + getEmbeddedPostgresTestSupport, + startEmbeddedPostgresTestDatabase, +} from "./helpers/embedded-postgres.js"; + +vi.hoisted(() => { + process.env.PAPERCLIP_HOME = "/tmp/paperclip-test-home"; + process.env.PAPERCLIP_INSTANCE_ID = "vitest-headless-queues"; + process.env.PAPERCLIP_LOG_DIR = "/tmp/paperclip-test-home/logs"; + process.env.PAPERCLIP_IN_WORKTREE = "false"; +}); + +const support = await getEmbeddedPostgresTestSupport(); +const describeEmbeddedPostgres = support.supported ? describe : describe.skip; + +function createTestServer(db: Db) { + const app = express(); + app.use(express.json()); + app.use((req, _res, next) => { + const actorType = req.header("x-test-actor-type"); + if (actorType === "agent") { + req.actor = { + type: "agent", + agentId: req.header("x-test-agent-id") ?? undefined, + companyId: req.header("x-test-company-id") ?? undefined, + source: "agent_key", + }; + } else { + req.actor = { + type: "board", + userId: req.header("x-test-user-id") ?? "board-user", + source: "local_implicit", + isInstanceAdmin: true, + }; + } + next(); + }); + app.use("/api", headlessQueuesEventsRoutes(db)); + app.use(errorHandler); + return createServer(app); +} + +async function listenServer(server: HttpServer): Promise { + await new Promise((resolve) => { + server.listen(0, "127.0.0.1", () => resolve()); + }); + const addr = server.address(); + if (!addr || typeof addr === "string") { + throw new Error("Expected TCP server address"); + } + return `http://127.0.0.1:${addr.port}`; +} + +async function closeServer(server: HttpServer): Promise { + await new Promise((resolve, reject) => { + server.close((err) => (err ? reject(err) : resolve())); + }); +} + +describeEmbeddedPostgres("headless queues, fenced leases, events & interactions", () => { + let db!: Db; + let tempDb: Awaited> | null = null; + let server!: HttpServer; + let baseUrl = ""; + let issueSeq = 0; + + beforeAll(async () => { + tempDb = await startEmbeddedPostgresTestDatabase("headless-queues-events-"); + db = createDb(tempDb.connectionString, { + maxConnections: 10, + idleTimeoutSeconds: 0, + connectTimeoutSeconds: 0, + maxLifetimeSeconds: 0, + }); + server = createTestServer(db); + baseUrl = await listenServer(server); + }, 30_000); + + afterEach(async () => { + await reconcileDatabaseWork(db, DELIVERY_QUEUES.claimLeaseExpiry); + await reconcileDatabaseWork(db, DELIVERY_QUEUES.scheduledBoardPosts); + await db.execute(sql`truncate companies cascade`); + await db.delete(authUsers); + issueSeq = 0; + }); + + afterAll(async () => { + await closeServer(server); + await db?.$client.end(); + await tempDb?.cleanup(); + }); + + async function seedCompanyAndChannel(channelPath = "eng") { + const prefix = `HQ${randomUUID().replace(/-/g, "").slice(0, 4).toUpperCase()}`; + const [company] = await db + .insert(companies) + .values({ + name: `Headless Test ${prefix}`, + issuePrefix: prefix, + defaultResponsibleUserId: "board-user", + }) + .returning(); + + const [channel] = await db + .insert(channels) + .values({ + companyId: company!.id, + path: channelPath, + visibility: "open", + }) + .returning(); + + const [agent] = await db + .insert(agents) + .values({ + companyId: company!.id, + name: "worker-bot", + role: "engineer", + status: "idle", + lifecycleState: "ready", + adapterType: "process", + }) + .returning(); + + return { company: company!, channel: channel!, agent: agent! }; + } + + async function seedTask( + companyId: string, + issuePrefix: string, + opts: { + title?: string; + channelId?: string | null; + projectId?: string | null; + assigneeAgentId?: string | null; + visibility?: "open" | "private"; + priority?: "critical" | "high" | "medium" | "low"; + status?: string; + kvLabels?: Record; + resultSchemaRef?: string | null; + } = {}, + ) { + issueSeq += 1; + const [issue] = await db + .insert(issues) + .values({ + companyId, + channelId: opts.channelId ?? null, + projectId: opts.projectId ?? null, + assigneeAgentId: opts.assigneeAgentId ?? null, + visibility: opts.visibility ?? "open", + title: opts.title ?? `Task ${issueSeq}`, + status: opts.status ?? "todo", + scope: opts.channelId ? "channel" : "board", + priority: opts.priority ?? "medium", + issueNumber: issueSeq, + identifier: `${issuePrefix}-${issueSeq}`, + kvLabels: opts.kvLabels ?? {}, + resultSchemaRef: opts.resultSchemaRef ?? null, + }) + .returning(); + if (issue && opts.visibility === "private") { + await db + .update(issues) + .set({ privacyRootIssueId: issue.id }) + .where(eq(issues.id, issue.id)); + } + return issue!; + } + + it("1. atomically pops distinct tasks under concurrent FOR UPDATE SKIP LOCKED claims", async () => { + const { company, channel } = await seedCompanyAndChannel("workers"); + const seeded = await Promise.all( + Array.from({ length: 5 }, (_, i) => + seedTask(company.id, company.issuePrefix, { + title: `Pool task ${i + 1}`, + channelId: channel.id, + }), + ), + ); + + const responses = await Promise.all( + Array.from({ length: 10 }, (_, i) => + fetch(`${baseUrl}/api/companies/${company.id}/tasks/claim`, { + method: "POST", + headers: { + "content-type": "application/json", + "x-paperclip-actor-profile": `worker-${i}`, + }, + body: JSON.stringify({ + ready: true, + channel: "workers", + leaseSec: 30, + }), + }), + ), + ); + + const successes = responses.filter((r) => r.status === 200); + const empties = responses.filter((r) => r.status === 204); + + expect(successes).toHaveLength(5); + expect(empties).toHaveLength(5); + + const claims = (await Promise.all( + successes.map((r) => r.json() as Promise), + )); + const claimedIds = new Set(claims.map((c) => c.issue.id)); + expect(claimedIds.size).toBe(5); + for (const s of seeded) { + expect(claimedIds.has(s.id)).toBe(true); + } + for (const c of claims) { + expect(c.claimEpoch).toBe(1); + expect(c.claimToken).toMatch(/^clm_/); + expect(c.issue.status).toBe("in_progress"); + } + }); + + it("2. wakes blocking waitSec claim immediately when task.ready is published", async () => { + const { company, channel } = await seedCompanyAndChannel("wait-queue"); + + const startedAt = Date.now(); + const claimPromise = fetch( + `${baseUrl}/api/companies/${company.id}/tasks/claim`, + { + method: "POST", + headers: { + "content-type": "application/json", + "x-paperclip-actor-profile": "waiter-1", + }, + body: JSON.stringify({ + ready: true, + channel: "wait-queue", + waitSec: 3, + leaseSec: 30, + }), + }, + ); + + await new Promise((r) => setTimeout(r, 100)); + const created = await seedTask(company.id, company.issuePrefix, { + title: "Late arriving task", + channelId: channel.id, + }); + const readyEvent = await appendBoardEvent(db, { + companyId: company.id, + type: "task.ready", + channelId: channel.id, + channelPath: channel.path, + issueId: created.id, + identifier: created.identifier, + actor: { principalType: "system", actorProfile: "producer" }, + payload: {}, + }); + publishCommittedBoardEvent(readyEvent); + + const res = await claimPromise; + const elapsedMs = Date.now() - startedAt; + + expect(res.status).toBe(200); + expect(elapsedMs).toBeLessThan(800); + const claim = (await res.json()) as TaskClaimView; + expect(claim.issue.id).toBe(created.id); + expect(claim.claimEpoch).toBe(1); + }); + + it("3. enforces laptop-sleep-safe renewal and fenced 409 claim_lost after lease expiry", async () => { + const { company, channel } = await seedCompanyAndChannel("leases"); + const task = await seedTask(company.id, company.issuePrefix, { + title: "Lease test task", + channelId: channel.id, + }); + + const claimRes = await fetch( + `${baseUrl}/api/companies/${company.id}/tasks/claim`, + { + method: "POST", + headers: { + "content-type": "application/json", + "x-paperclip-actor-profile": "sleeper", + }, + body: JSON.stringify({ issueId: task.id, leaseSec: 1 }), + }, + ); + expect(claimRes.status).toBe(200); + const claim1 = (await claimRes.json()) as TaskClaimView; + + // Backdate claimLeaseExpiresAt past TTL WITHOUT running the lease expiry reconciler -> laptop-sleep-safe renew succeeds! + await db + .update(issues) + .set({ claimLeaseExpiresAt: new Date(Date.now() - 5_000) }) + .where(eq(issues.id, task.id)); + + const sleepRenewRes = await fetch( + `${baseUrl}/api/issues/${task.id}/claim/renew`, + { + method: "POST", + headers: { + "content-type": "application/json", + "x-paperclip-claim-token": claim1.claimToken, + }, + body: JSON.stringify({ + claimEpoch: claim1.claimEpoch, + leaseSec: 1, + }), + }, + ); + expect(sleepRenewRes.status).toBe(200); + const renewed = (await sleepRenewRes.json()) as TaskClaimView; + expect(renewed.claimEpoch).toBe(claim1.claimEpoch); + expect(renewed.claimToken).toBe(claim1.claimToken); + + // Backdate renewed lease past expiry AND run the lease expiry worker + await db + .update(issues) + .set({ claimLeaseExpiresAt: new Date(Date.now() - 5_000) }) + .where(eq(issues.id, task.id)); + const worker = createClaimLeaseExpiryWorker(db); + const expiredCount = await worker.expireDueClaimLeases(); + expect(expiredCount).toBe(1); + expect(worker.nextRunAt()).toBeNull(); + + // Stale worker's renew & complete fail with 409 claim_lost + const staleRenew = await fetch( + `${baseUrl}/api/issues/${task.id}/claim/renew`, + { + method: "POST", + headers: { + "content-type": "application/json", + "x-paperclip-claim-token": claim1.claimToken, + }, + body: JSON.stringify({ claimEpoch: claim1.claimEpoch }), + }, + ); + expect(staleRenew.status).toBe(409); + const staleRenewJson = (await staleRenew.json()) as { + error: string; + code: string; + }; + expect(staleRenewJson.code).toBe("claim_lost"); + + const staleComplete = await fetch( + `${baseUrl}/api/issues/${task.id}/claim/complete`, + { + method: "POST", + headers: { + "content-type": "application/json", + "x-paperclip-claim-token": claim1.claimToken, + }, + body: JSON.stringify({ claimEpoch: claim1.claimEpoch, message: "late" }), + }, + ); + expect(staleComplete.status).toBe(409); + const staleCompleteJson = (await staleComplete.json()) as { code: string }; + expect(staleCompleteJson.code).toBe("claim_lost"); + + // New worker claims at bumped claimEpoch (reconciler bumped 1 -> 2, new claim bumps 2 -> 3) + const reclaimRes = await fetch( + `${baseUrl}/api/companies/${company.id}/tasks/claim`, + { + method: "POST", + headers: { + "content-type": "application/json", + "x-paperclip-actor-profile": "fresh-worker", + }, + body: JSON.stringify({ ready: true, channel: "leases", leaseSec: 30 }), + }, + ); + expect(reclaimRes.status).toBe(200); + const claim2 = (await reclaimRes.json()) as TaskClaimView; + expect(claim2.issue.id).toBe(task.id); + expect(claim2.claimEpoch).toBeGreaterThan(claim1.claimEpoch); + expect(claim2.claimToken).not.toBe(claim1.claimToken); + }); + + it("4. poison-blocks a task after maxClaimAttempts failures and emits task.lease_poison_blocked", async () => { + const { company, channel } = await seedCompanyAndChannel("poison"); + const task = await seedTask(company.id, company.issuePrefix, { + title: "Flaky task", + channelId: channel.id, + }); + + for (let attempt = 1; attempt <= 3; attempt += 1) { + const claimRes = await fetch( + `${baseUrl}/api/companies/${company.id}/tasks/claim`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ ready: true, channel: "poison", leaseSec: 30 }), + }, + ); + expect(claimRes.status).toBe(200); + const claim = (await claimRes.json()) as TaskClaimView; + expect(claim.issue.claimAttemptCount).toBe(attempt); + + const failRes = await fetch( + `${baseUrl}/api/issues/${task.id}/claim/fail`, + { + method: "POST", + headers: { + "content-type": "application/json", + "x-paperclip-claim-token": claim.claimToken, + }, + body: JSON.stringify({ + claimEpoch: claim.claimEpoch, + reason: `crash #${attempt}`, + }), + }, + ); + expect(failRes.status).toBe(200); + const updated = (await failRes.json()) as HeadlessIssueView; + expect(updated.status).toBe(attempt < 3 ? "todo" : "blocked"); + } + + const events = await db + .select() + .from(boardEvents) + .where( + and( + eq(boardEvents.companyId, company.id), + eq(boardEvents.issueId, task.id), + eq(boardEvents.eventType, "task.lease_poison_blocked"), + ), + ); + expect(events).toHaveLength(1); + }); + + it("5. validates resultSchemaRef on complete (422 vs 200) and unblocks downstream DAG dependent", async () => { + const { company, channel } = await seedCompanyAndChannel("dag"); + + await db.insert(companySchemas).values({ + companyId: company.id, + name: "audit-result", + version: 1, + jsonSchema: { + type: "object", + required: ["passed", "score"], + properties: { + passed: { type: "boolean" }, + score: { type: "integer", minimum: 0, maximum: 100 }, + }, + additionalProperties: false, + }, + }); + + const upstream = await seedTask(company.id, company.issuePrefix, { + title: "Run audit", + channelId: channel.id, + resultSchemaRef: "audit-result@1", + }); + const downstream = await seedTask(company.id, company.issuePrefix, { + title: "Deploy after audit", + channelId: channel.id, + }); + + await db.insert(issueRelations).values({ + companyId: company.id, + issueId: upstream.id, + relatedIssueId: downstream.id, + type: "blocks", + }); + + // Pool pop must skip blocked downstream and claim upstream + const claimRes = await fetch( + `${baseUrl}/api/companies/${company.id}/tasks/claim`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ ready: true, channel: "dag" }), + }, + ); + expect(claimRes.status).toBe(200); + const claim = (await claimRes.json()) as TaskClaimView; + expect(claim.issue.id).toBe(upstream.id); + + // Invalid result payload -> 422 + const invalidComplete = await fetch( + `${baseUrl}/api/issues/${upstream.id}/claim/complete`, + { + method: "POST", + headers: { + "content-type": "application/json", + "x-paperclip-claim-token": claim.claimToken, + }, + body: JSON.stringify({ + claimEpoch: claim.claimEpoch, + data: { passed: "yes", score: 150 }, + }), + }, + ); + expect(invalidComplete.status).toBe(422); + const errBody = (await invalidComplete.json()) as { code: string }; + expect(errBody.code).toBe("result_schema_validation_failed"); + + // Start waiting for downstream task.ready event + const waitReadyPromise = fetch( + `${baseUrl}/api/companies/${company.id}/events/wait?issueId=${downstream.id}&event=task.ready&after=${claim.cursor}&timeoutMs=3000`, + ); + + // Valid result payload + prUrl -> 200 + const validComplete = await fetch( + `${baseUrl}/api/issues/${upstream.id}/claim/complete`, + { + method: "POST", + headers: { + "content-type": "application/json", + "x-paperclip-claim-token": claim.claimToken, + }, + body: JSON.stringify({ + claimEpoch: claim.claimEpoch, + message: "Audit passed cleanly", + data: { passed: true, score: 98 }, + prUrl: "https://github.com/paperclipai/paperclip/pull/999", + }), + }, + ); + expect(validComplete.status).toBe(200); + const completed = (await validComplete.json()) as HeadlessIssueView; + expect(completed.status).toBe("done"); + + const workProducts = await db + .select() + .from(issueWorkProducts) + .where(eq(issueWorkProducts.issueId, upstream.id)); + expect(workProducts).toHaveLength(1); + expect(workProducts[0]!.url).toBe( + "https://github.com/paperclipai/paperclip/pull/999", + ); + + const waitRes = await waitReadyPromise; + expect(waitRes.status).toBe(200); + const readyEv = (await waitRes.json()) as BoardEventView; + expect(readyEv.type).toBe("task.ready"); + expect(readyEv.issueId).toBe(downstream.id); + + // Downstream is now claimable! + const claimDownstream = await fetch( + `${baseUrl}/api/companies/${company.id}/tasks/claim`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ ready: true, channel: "dag" }), + }, + ); + expect(claimDownstream.status).toBe(200); + const downstreamClaim = (await claimDownstream.json()) as TaskClaimView; + expect(downstreamClaim.issue.id).toBe(downstream.id); + }); + + it("6. auto-releases lease on ask, enforces humanOnly on approve (403 for agent), and requeues on human approve", async () => { + const { company, channel, agent } = await seedCompanyAndChannel("approvals"); + const task = await seedTask(company.id, company.issuePrefix, { + title: "Prod migration", + channelId: channel.id, + }); + + const claimRes = await fetch( + `${baseUrl}/api/companies/${company.id}/tasks/claim`, + { + method: "POST", + headers: { + "content-type": "application/json", + "x-test-actor-type": "agent", + "x-test-agent-id": agent.id, + "x-test-company-id": company.id, + }, + body: JSON.stringify({ ready: true, channel: "approvals" }), + }, + ); + expect(claimRes.status).toBe(200); + const claim = (await claimRes.json()) as TaskClaimView; + + // Stateless ask releases lease and blocks task + const askRes = await fetch(`${baseUrl}/api/issues/${task.id}/ask`, { + method: "POST", + headers: { + "content-type": "application/json", + "x-test-actor-type": "agent", + "x-test-agent-id": agent.id, + "x-test-company-id": company.id, + "x-paperclip-claim-token": claim.claimToken, + }, + body: JSON.stringify({ + question: "Proceed with table drop?", + choices: ["yes", "no"], + humanOnly: true, + claimToken: claim.claimToken, + }), + }); + expect(askRes.status).toBe(200); + const interaction = (await askRes.json()) as InteractionView; + expect(interaction.status).toBe("pending"); + expect(interaction.resolverPolicy).toBe("human_only"); + expect(interaction.continuationPolicy).toBe("requeue_on_resolve"); + + const [blockedRow] = await db + .select() + .from(issues) + .where(eq(issues.id, task.id)); + expect(blockedRow!.status).toBe("blocked"); + expect(blockedRow!.claimTokenHash).toBeNull(); + expect(blockedRow!.claimAttemptCount).toBe(0); + + // Agent attempt to approve humanOnly interaction -> 403 + const agentApprove = await fetch( + `${baseUrl}/api/issues/${task.id}/approve`, + { + method: "POST", + headers: { + "content-type": "application/json", + "x-test-actor-type": "agent", + "x-test-agent-id": agent.id, + "x-test-company-id": company.id, + }, + body: JSON.stringify({ note: "self-approve" }), + }, + ); + expect(agentApprove.status).toBe(403); + const agentApproveErr = (await agentApprove.json()) as { code: string }; + expect(agentApproveErr.code).toBe("human_resolver_required"); + + // Human approve -> resolves interaction, requeues task to todo, emits task.ready + const waitReady = fetch( + `${baseUrl}/api/companies/${company.id}/events/wait?issueId=${task.id}&event=task.ready&after=${interaction.cursor}&timeoutMs=3000`, + ); + const humanApprove = await fetch( + `${baseUrl}/api/issues/${task.id}/approve`, + { + method: "POST", + headers: { + "content-type": "application/json", + "x-test-actor-type": "board", + "x-test-user-id": "dotta", + }, + body: JSON.stringify({ note: "Yes, proceed" }), + }, + ); + expect(humanApprove.status).toBe(200); + const resolved = (await humanApprove.json()) as InteractionView; + expect(resolved.status).toBe("answered"); + + const [requeuedRow] = await db + .select() + .from(issues) + .where(eq(issues.id, task.id)); + expect(requeuedRow!.status).toBe("todo"); + + const readyRes = await waitReady; + expect(readyRes.status).toBe(200); + const readyEv = (await readyRes.json()) as BoardEventView; + expect(readyEv.type).toBe("task.ready"); + }); + + it("7. supports race-free events/wait, SSE events/stream replay+live, and sleep-aware workers with null nextRunAt when idle", async () => { + const { company, channel } = await seedCompanyAndChannel("stream"); + + // Seed an earlier event before stream starts + const ev1 = await appendBoardEvent(db, { + companyId: company.id, + type: "thread.posted", + channelId: channel.id, + channelPath: channel.path, + actor: { principalType: "user", userId: "board-user", agentId: null, agentName: null, actorProfile: "dotta" }, + payload: { text: "Hello @alice", kvLabels: { env: "prod" } }, + }); + publishCommittedBoardEvent(ev1); + + const ev2 = await appendBoardEvent(db, { + companyId: company.id, + type: "thread.posted", + channelId: channel.id, + channelPath: channel.path, + actor: { principalType: "user", userId: "board-user", agentId: null, agentName: null, actorProfile: "dotta" }, + payload: { text: "Deploy @alice now", kvLabels: { env: "prod" } }, + }); + publishCommittedBoardEvent(ev2); + + // Start SSE stream after ev1, filtering by mentions=alice and label=env=prod + const sseAbort = new AbortController(); + const sseRes = await fetch( + `${baseUrl}/api/companies/${company.id}/events/stream?after=${ev1.cursor}&mentions=alice&label=${encodeURIComponent("env=prod")}`, + { + headers: { accept: "text/event-stream" }, + signal: sseAbort.signal, + }, + ); + expect(sseRes.status).toBe(200); + expect(sseRes.body).toBeTruthy(); + + const received: BoardEventView[] = []; + const readerTask = (async () => { + for await (const ev of parseSseEventStream(sseRes.body!, sseAbort.signal)) { + received.push(ev); + if (received.length >= 2) { + sseAbort.abort(); + break; + } + } + })(); + + // Publish a non-matching event then a matching live event + const nonMatching = await appendBoardEvent(db, { + companyId: company.id, + type: "thread.posted", + channelId: channel.id, + channelPath: channel.path, + actor: { principalType: "user", userId: "board-user", agentId: null, agentName: null, actorProfile: "dotta" }, + payload: { text: "Ping @bob", kvLabels: { env: "prod" } }, + }); + publishCommittedBoardEvent(nonMatching); + + const ev3 = await appendBoardEvent(db, { + companyId: company.id, + type: "thread.posted", + channelId: channel.id, + channelPath: channel.path, + actor: { principalType: "user", userId: "board-user", agentId: null, agentName: null, actorProfile: "dotta" }, + payload: { text: "Live ping @alice", kvLabels: { env: "prod" } }, + }); + publishCommittedBoardEvent(ev3); + + await readerTask.catch(() => {}); + expect(received.map((e) => e.seq)).toEqual([ev2.seq, ev3.seq]); + + // Sleep-aware workers test with DeliveryWorkCoordinator + const coordinatorErrors: unknown[] = []; + const coordinator = createDeliveryWorkCoordinator({ + owner: db, + canRun: () => true, + onError: (err) => coordinatorErrors.push(err), + }); + + const leaseWorker = createClaimLeaseExpiryWorker(db); + const scheduleWorker = createScheduledBoardPostsWorker(db); + + const regLease = coordinator.register( + DELIVERY_QUEUES.claimLeaseExpiry, + leaseWorker.deliveryTask, + ); + const regSchedule = coordinator.register( + DELIVERY_QUEUES.scheduledBoardPosts, + scheduleWorker.deliveryTask, + ); + + try { + await Promise.all([regLease.ready, regSchedule.ready]); + // Wait for initial pass to settle when idle + await vi.waitFor(() => { + expect(leaseWorker.nextRunAt()).toBeNull(); + expect(scheduleWorker.nextRunAt()).toBeNull(); + expect(coordinator.nextWakeAt()).toBeNull(); + }); + + // Schedule a post in 80ms via HTTP API + const schedRes = await fetch( + `${baseUrl}/api/companies/${company.id}/schedules`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + target: "#stream", + message: "Scheduled check-in\n\nDetails here", + in: "80ms", + }), + }, + ); + expect(schedRes.status).toBe(201); + const schedule = (await schedRes.json()) as ScheduleView; + expect(schedule.status).toBe("scheduled"); + + // Wait for scheduled post worker to fire automatically and return to idle (nextRunAt() === null) + await vi.waitFor( + async () => { + const [row] = await db + .select() + .from(scheduledBoardPosts) + .where(eq(scheduledBoardPosts.id, schedule.id)); + expect(row?.status).toBe("completed"); + expect(scheduleWorker.nextRunAt()).toBeNull(); + expect(coordinator.nextWakeAt()).toBeNull(); + }, + { timeout: 3000 }, + ); + + const createdTasks = await db + .select() + .from(issues) + .where( + and( + eq(issues.companyId, company.id), + eq(issues.originKind, "scheduled_post"), + ), + ); + expect(createdTasks).toHaveLength(1); + expect(createdTasks[0]!.title).toBe("Scheduled check-in"); + expect(createdTasks[0]!.status).toBe("todo"); + + expect(coordinatorErrors).toEqual([]); + } finally { + await coordinator.stop(); + } + }); + + it("8. enforces lease fencing on release->complete & ask/confirm, schema overrides, pause holds, and Web UI requeue_on_resolve", async () => { + const { company, channel, agent } = await seedCompanyAndChannel("fencing"); + + // 1. release followed by complete must fail with 409 claim_lost (even without token or with old token) + const releaseTask = await seedTask(company.id, company.issuePrefix, { + title: "Release fencing task", + channelId: channel.id, + }); + const relClaimRes = await fetch( + `${baseUrl}/api/companies/${company.id}/tasks/claim`, + { + method: "POST", + headers: { + "content-type": "application/json", + "x-test-actor-type": "agent", + "x-test-agent-id": agent.id, + "x-test-company-id": company.id, + }, + body: JSON.stringify({ issueId: releaseTask.id }), + }, + ); + expect(relClaimRes.status).toBe(200); + const relClaim = (await relClaimRes.json()) as TaskClaimView; + + // ask without claimToken while task has an active pool lease fails 409 claim_lost + const stolenAskRes = await fetch(`${baseUrl}/api/issues/${releaseTask.id}/ask`, { + method: "POST", + headers: { + "content-type": "application/json", + "x-test-actor-type": "agent", + "x-test-agent-id": agent.id, + "x-test-company-id": company.id, + }, + body: JSON.stringify({ question: "Attempt without claim token" }), + }); + expect(stolenAskRes.status).toBe(409); + + await fetch(`${baseUrl}/api/issues/${releaseTask.id}/claim/release`, { + method: "POST", + headers: { + "content-type": "application/json", + "x-paperclip-claim-token": relClaim.claimToken, + }, + body: JSON.stringify({ claimEpoch: relClaim.claimEpoch }), + }).then((r) => expect(r.status).toBe(200)); + + const postReleaseComplete = await fetch( + `${baseUrl}/api/issues/${releaseTask.id}/claim/complete`, + { + method: "POST", + headers: { + "content-type": "application/json", + "x-paperclip-claim-token": relClaim.claimToken, + }, + body: JSON.stringify({ message: "Stale completion" }), + }, + ); + expect(postReleaseComplete.status).toBe(409); + + // 2. resultSchema override on complete is rejected with 409 result_schema_mismatch, and extra invalid block returns 422 + const schemaTask = await seedTask(company.id, company.issuePrefix, { + title: "Strict result schema task", + channelId: channel.id, + resultSchemaRef: "handoff@1", + }); + const schemaClaimRes = await fetch( + `${baseUrl}/api/companies/${company.id}/tasks/claim`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ issueId: schemaTask.id }), + }, + ); + const schemaClaim = (await schemaClaimRes.json()) as TaskClaimView; + + const overrideRes = await fetch( + `${baseUrl}/api/issues/${schemaTask.id}/claim/complete`, + { + method: "POST", + headers: { + "content-type": "application/json", + "x-paperclip-claim-token": schemaClaim.claimToken, + }, + body: JSON.stringify({ + claimEpoch: schemaClaim.claimEpoch, + resultSchema: "approval@1", + data: { status: "approved" }, + }), + }, + ); + expect(overrideRes.status).toBe(409); + + const invalidExtraBlock = await fetch( + `${baseUrl}/api/issues/${schemaTask.id}/claim/complete`, + { + method: "POST", + headers: { + "content-type": "application/json", + "x-paperclip-claim-token": schemaClaim.claimToken, + }, + body: JSON.stringify({ + claimEpoch: schemaClaim.claimEpoch, + data: { summary: "Done", nextSteps: ["Verify"] }, + blocks: [{ schema: "approval", version: 1, data: {} }], + }), + }, + ); + expect(invalidExtraBlock.status).toBe(422); + + // 3. Task with active pause hold is excluded from pool claims + const pausedTask = await seedTask(company.id, company.issuePrefix, { + title: "Paused tree task", + channelId: channel.id, + }); + await db.insert(issueTreeHolds).values({ + companyId: company.id, + rootIssueId: pausedTask.id, + mode: "pause", + status: "active", + reason: "Paused by test", + }); + + const claimPaused = await fetch( + `${baseUrl}/api/companies/${company.id}/tasks/claim`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ issueId: pausedTask.id }), + }, + ); + expect(claimPaused.status).toBe(409); + + // 4. Web UI issueThreadInteractionService acceptInteraction & answerQuestions requeue requeue_on_resolve blocked pool tasks + const uiTask = await seedTask(company.id, company.issuePrefix, { + title: "Web UI confirm requeue", + channelId: channel.id, + }); + const uiClaim = (await ( + await fetch(`${baseUrl}/api/companies/${company.id}/tasks/claim`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ issueId: uiTask.id }), + }) + ).json()) as TaskClaimView; + + const confirmRes = await fetch(`${baseUrl}/api/issues/${uiTask.id}/confirm`, { + method: "POST", + headers: { + "content-type": "application/json", + "x-paperclip-claim-token": uiClaim.claimToken, + }, + body: JSON.stringify({ + prompt: "Proceed with UI confirm?", + continuationPolicy: "requeue_on_resolve", + }), + }); + expect(confirmRes.status).toBe(200); + const confirmView = (await confirmRes.json()) as InteractionView; + + const interactionSvc = issueThreadInteractionService(db); + await interactionSvc.acceptInteraction( + uiTask, + confirmView.id, + {}, + { userId: "board-user" }, + ); + const [requeuedRow] = await db.select().from(issues).where(eq(issues.id, uiTask.id)); + expect(requeuedRow?.status).toBe("todo"); + + // 5. Multi-question ask rejects collapsing via /approve and resolves via Web UI answerQuestions into todo + await db.update(issues).set({ status: "blocked" }).where(eq(issues.id, uiTask.id)); + const [multiQRow] = await db + .insert(issueThreadInteractions) + .values({ + companyId: company.id, + issueId: uiTask.id, + kind: "ask_user_questions", + status: "pending", + requestedResolverPolicy: "anyone", + effectiveResolverPolicy: "anyone", + continuationPolicy: "requeue_on_resolve", + payload: { + version: 1, + questions: [ + { id: "q1", prompt: "Env?", selectionMode: "single", options: [{ id: "staging", label: "staging" }, { id: "prod", label: "prod" }] }, + { id: "q2", prompt: "Canary?", selectionMode: "single", options: [{ id: "yes", label: "yes" }, { id: "no", label: "no" }] }, + ], + } as never, + }) + .returning(); + + const multiCollapse = await fetch(`${baseUrl}/api/issues/${uiTask.id}/approve`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ interactionId: multiQRow!.id, answer: "staging" }), + }); + expect(multiCollapse.status).toBe(422); + + await interactionSvc.answerQuestions( + uiTask, + multiQRow!.id, + { + answers: [ + { questionId: "q1", optionIds: ["staging"] }, + { questionId: "q2", optionIds: ["yes"] }, + ], + }, + { userId: "board-user" }, + ); + const [requeuedMulti] = await db.select().from(issues).where(eq(issues.id, uiTask.id)); + expect(requeuedMulti?.status).toBe("todo"); + }); + + it("9. blocks paused project claims, redacts private-project events on /events/wait & /events/stream, and wakes assigned agents on issue schedules", async () => { + const { company, channel, agent } = await seedCompanyAndChannel("proj-pause-ev"); + + // 1. Paused project blocks both explicit and pool claims + const [pausedProject] = await db + .insert(projects) + .values({ + companyId: company.id, + name: "Paused Budget Project", + visibility: "open", + pausedAt: new Date(), + pauseReason: "budget", + }) + .returning(); + + const pausedProjTask = await seedTask(company.id, company.issuePrefix, { + title: "Paused project task", + channelId: channel.id, + projectId: pausedProject!.id, + }); + + const explicitPaused = await fetch( + `${baseUrl}/api/companies/${company.id}/tasks/claim`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ issueId: pausedProjTask.id }), + }, + ); + expect(explicitPaused.status).toBe(409); + + const poolPaused = await fetch( + `${baseUrl}/api/companies/${company.id}/tasks/claim`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ channel: channel.path, wait: 0 }), + }, + ); + expect(poolPaused.status).toBe(204); + + // 2. Issue-target scheduled post with post=false invokes onWakeAssignee + const assignedTask = await seedTask(company.id, company.issuePrefix, { + title: "Monitor task", + channelId: channel.id, + assigneeAgentId: agent.id, + }); + const dueSchedRes = await fetch( + `${baseUrl}/api/companies/${company.id}/schedules`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + target: assignedTask.identifier, + message: "Check CI status", + in: "1s", + post: false, + }), + }, + ); + expect(dueSchedRes.status).toBe(201); + const dueSched = (await dueSchedRes.json()) as ScheduleView; + await db + .update(scheduledBoardPosts) + .set({ nextRunAt: new Date(Date.now() - 5_000) }) + .where(eq(scheduledBoardPosts.id, dueSched.id)); + + const woken: Array<{ issueId: string; assigneeAgentId: string; scheduleId: string }> = []; + const wakeWorker = createScheduledBoardPostsWorker(db, { + onWakeAssignee: async (wake) => { + woken.push({ + issueId: wake.issueId, + assigneeAgentId: wake.assigneeAgentId, + scheduleId: wake.scheduleId, + }); + }, + }); + await wakeWorker.runDueScheduledPosts(); + expect(woken).toEqual([ + { + issueId: assignedTask.id, + assigneeAgentId: agent.id, + scheduleId: dueSched.id, + }, + ]); + + // 3. Authenticated app: private-project task events in an open channel must NOT leak over /events/wait or /events/stream + const ownerId = randomUUID(); + const viewerId = randomUUID(); + await db.insert(authUsers).values([ + { id: ownerId, name: "Priv Owner", email: `${ownerId}@example.test`, emailVerified: true, createdAt: new Date(), updatedAt: new Date() }, + { id: viewerId, name: "Priv Viewer", email: `${viewerId}@example.test`, emailVerified: true, createdAt: new Date(), updatedAt: new Date() }, + ]); + await db.insert(companyMemberships).values([ + { companyId: company.id, principalType: "user", principalId: ownerId, status: "active", membershipRole: "owner" }, + { companyId: company.id, principalType: "user", principalId: viewerId, status: "active", membershipRole: "viewer" }, + ]); + + const [privProject] = await db + .insert(projects) + .values({ companyId: company.id, name: "Secret Proj", visibility: "private" }) + .returning(); + const privIssue = await seedTask(company.id, company.issuePrefix, { + title: "Secret Project Title Leak Test", + channelId: channel.id, + projectId: privProject!.id, + visibility: "private", + }); + + const leakedEv = await appendBoardEvent(db, { + companyId: company.id, + type: "task.created", + channelId: channel.id, + channelPath: channel.path, + issueId: privIssue.id, + identifier: privIssue.identifier, + actor: { principalType: "user", userId: ownerId, agentId: null, agentName: null, actorProfile: null }, + payload: { title: "Secret Project Title Leak Test", description: "Confidential body" }, + }); + + const authApp = express(); + authApp.use(express.json()); + authApp.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` }, + }; + }, + }), + ); + authApp.use("/api", headlessQueuesEventsRoutes(db, { deploymentMode: "authenticated" })); + authApp.use(errorHandler); + const authSrv = createServer(authApp); + await new Promise((resolve) => authSrv.listen(0, "127.0.0.1", resolve)); + const authPort = (authSrv.address() as { port: number }).port; + const authBase = `http://127.0.0.1:${authPort}`; + + try { + const waitRes = await fetch( + `${authBase}/api/companies/${company.id}/events/wait?after=evt_${leakedEv.seq - 1}&event=task.created&timeoutMs=0`, + { headers: { "x-test-user-id": viewerId } }, + ); + expect(waitRes.status).toBe(204); + + const streamRes = await fetch( + `${authBase}/api/companies/${company.id}/events/stream?after=evt_${leakedEv.seq - 1}`, + { headers: { "x-test-user-id": viewerId } }, + ); + expect(streamRes.status).toBe(200); + const reader = streamRes.body!.getReader(); + const firstChunk = await reader.read(); + await reader.cancel(); + const text = Buffer.from(firstChunk.value ?? []).toString("utf8"); + expect(text).not.toContain("Secret Project Title Leak Test"); + + // 4. listSchedules & cancelSchedule hide/deny private-issue schedules from non-granted company members + const memberId = randomUUID(); + await db.insert(authUsers).values({ + id: memberId, + name: "Priv NonMember", + email: `${memberId}@example.test`, + emailVerified: true, + createdAt: new Date(), + updatedAt: new Date(), + }); + await db.insert(companyMemberships).values({ + companyId: company.id, + principalType: "user", + principalId: memberId, + status: "active", + membershipRole: "member", + }); + await db + .update(issues) + .set({ privacyRootIssueId: privIssue.id }) + .where(eq(issues.id, privIssue.id)); + await db.insert(projectAccessMembers).values({ + companyId: company.id, + projectId: privProject!.id, + subjectType: "user", + subjectId: ownerId, + }); + await db.insert(issueAccessGrants).values({ + issueId: privIssue.id, + subjectType: "user", + subjectId: ownerId, + source: "explicit", + }); + + const ownerSchedRes = await fetch( + `${authBase}/api/companies/${company.id}/schedules`, + { + method: "POST", + headers: { "content-type": "application/json", "x-test-user-id": ownerId }, + body: JSON.stringify({ + target: privIssue.identifier, + message: "Confidential schedule ping", + in: "10m", + post: false, + }), + }, + ); + expect(ownerSchedRes.status).toBe(201); + const ownerSched = (await ownerSchedRes.json()) as ScheduleView; + + const memberListAll = await fetch( + `${authBase}/api/companies/${company.id}/schedules`, + { headers: { "x-test-user-id": memberId } }, + ); + expect(memberListAll.status).toBe(200); + const memberListBody = (await memberListAll.json()) as { items: ScheduleView[] }; + expect(memberListBody.items.some((s) => s.id === ownerSched.id)).toBe(false); + + const memberListTarget = await fetch( + `${authBase}/api/companies/${company.id}/schedules?target=${encodeURIComponent(privIssue.identifier!)}`, + { headers: { "x-test-user-id": memberId } }, + ); + expect(memberListTarget.status).toBe(404); + + const memberCancel = await fetch( + `${authBase}/api/companies/${company.id}/schedules/${ownerSched.id}`, + { method: "DELETE", headers: { "x-test-user-id": memberId } }, + ); + expect(memberCancel.status).toBe(404); + + const ownerList = await fetch( + `${authBase}/api/companies/${company.id}/schedules?target=${encodeURIComponent(privIssue.identifier!)}`, + { headers: { "x-test-user-id": ownerId } }, + ); + expect(ownerList.status).toBe(200); + const ownerListBody = (await ownerList.json()) as { items: ScheduleView[] }; + expect(ownerListBody.items.some((s) => s.id === ownerSched.id)).toBe(true); + + const ownerCancel = await fetch( + `${authBase}/api/companies/${company.id}/schedules/${ownerSched.id}`, + { method: "DELETE", headers: { "x-test-user-id": ownerId } }, + ); + expect(ownerCancel.status).toBe(200); + } finally { + await new Promise((resolve) => authSrv.close(() => resolve())); + } + }); + + it("10. enforces completion gates, cancelled-blocker holds, 30d schedule intervalMs, and browser-path interaction.resolved events", async () => { + const { company, channel } = await seedCompanyAndChannel("gates-bigint-events"); + + // 1. Cancelled blocker keeps dependent unready across explicit claim and pool claim + const cancelledBlocker = await seedTask(company.id, company.issuePrefix, { + title: "Cancelled blocker", + channelId: channel.id, + status: "cancelled", + }); + const gatedDep = await seedTask(company.id, company.issuePrefix, { + title: "Dependent held by cancelled blocker", + channelId: channel.id, + }); + await db.insert(issueRelations).values({ + companyId: company.id, + issueId: cancelledBlocker.id, + relatedIssueId: gatedDep.id, + type: "blocks", + }); + const claimBlocked = await fetch( + `${baseUrl}/api/companies/${company.id}/tasks/claim`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ issueId: gatedDep.id }), + }, + ); + expect(claimBlocked.status).toBe(409); + const poolBlocked = await fetch( + `${baseUrl}/api/companies/${company.id}/tasks/claim`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ channel: channel.path, wait: 0 }), + }, + ); + expect(poolBlocked.status).toBe(204); + + // 2. completeTaskClaim enforces requiredQualityReview gate + const qrTask = await seedTask(company.id, company.issuePrefix, { + title: "Quality review gated task", + channelId: channel.id, + }); + await db + .update(issues) + .set({ + executionPolicy: { + requiredQualityReview: { + version: 1, + deliverables: [{ key: "report", label: "Report" }], + }, + }, + }) + .where(eq(issues.id, qrTask.id)); + const qrClaimRes = await fetch( + `${baseUrl}/api/companies/${company.id}/tasks/claim`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ issueId: qrTask.id }), + }, + ); + expect(qrClaimRes.status).toBe(200); + const qrClaim = (await qrClaimRes.json()) as TaskClaimView; + const blockedComplete = await fetch( + `${baseUrl}/api/issues/${qrTask.id}/claim/complete`, + { + method: "POST", + headers: { + "content-type": "application/json", + "x-paperclip-claim-token": qrClaim.claimToken, + }, + body: JSON.stringify({ claimEpoch: qrClaim.claimEpoch }), + }, + ); + expect(blockedComplete.status).toBe(422); + expect(((await blockedComplete.json()) as { code: string }).code).toBe( + "required_quality_review_incomplete", + ); + + // 3. Long recurrence intervals (> int32 max ms) persist in scheduled_board_posts.interval_ms + const sched30dRes = await fetch( + `${baseUrl}/api/companies/${company.id}/schedules`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + target: channel.path, + message: "Monthly audit", + every: "30d", + }), + }, + ); + expect(sched30dRes.status).toBe(201); + const sched30d = (await sched30dRes.json()) as ScheduleView; + expect(sched30d.intervalMs).toBe(2_592_000_000); + + // 4. Web UI / service-path interaction resolution emits interaction.resolved board event + const askRes = await fetch( + `${baseUrl}/api/issues/${qrTask.id}/ask`, + { + method: "POST", + headers: { + "content-type": "application/json", + "x-paperclip-claim-token": qrClaim.claimToken, + }, + body: JSON.stringify({ + question: "Approve rollout?", + choices: ["yes", "no"], + claimToken: qrClaim.claimToken, + }), + }, + ); + expect(askRes.status).toBe(200); + const askView = (await askRes.json()) as InteractionView; + const waitEvPromise = fetch( + `${baseUrl}/api/companies/${company.id}/events/wait?issueId=${qrTask.id}&event=interaction.resolved&after=${askView.cursor}&timeoutMs=3000`, + ); + await issueThreadInteractionService(db).answerQuestions( + { id: qrTask.id, companyId: company.id, status: "blocked" }, + askView.id, + { answers: [{ questionId: "q1", optionIds: ["opt_1"] }] }, + { userId: "board-user" }, + ); + const waitEvRes = await waitEvPromise; + expect(waitEvRes.status).toBe(200); + const resolvedEv = (await waitEvRes.json()) as BoardEventView; + expect(resolvedEv.type).toBe("interaction.resolved"); + expect(resolvedEv.payload.interactionId).toBe(askView.id); + + // 5. Completing a blocker with an unfinalized workspace withholds task.ready, then workspace_finalize backstop wakes waiting pool workers + const [finalizeChannel] = await db + .insert(channels) + .values({ + companyId: company.id, + path: "finalize-wake", + visibility: "open", + }) + .returning(); + const [execWs] = await db + .insert(executionWorkspaces) + .values({ + companyId: company.id, + mode: "isolated_worktree", + strategyType: "git_worktree", + name: "blocker-ws", + }) + .returning(); + const finalizeBlocker = await seedTask(company.id, company.issuePrefix, { + title: "Finalize gated blocker", + channelId: finalizeChannel!.id, + }); + await db + .update(issues) + .set({ executionWorkspaceId: execWs!.id }) + .where(eq(issues.id, finalizeBlocker.id)); + await db.insert(workspaceOperations).values({ + companyId: company.id, + executionWorkspaceId: execWs!.id, + issueId: finalizeBlocker.id, + phase: "workspace_prepare", + status: "succeeded", + startedAt: new Date(Date.now() - 2_000), + }); + const poolDep = await seedTask(company.id, company.issuePrefix, { + title: "Pool dependent waiting on finalize", + channelId: finalizeChannel!.id, + }); + await db.insert(issueRelations).values({ + companyId: company.id, + issueId: finalizeBlocker.id, + relatedIssueId: poolDep.id, + type: "blocks", + }); + + const fbClaimRes = await fetch( + `${baseUrl}/api/companies/${company.id}/tasks/claim`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ issueId: finalizeBlocker.id }), + }, + ); + expect(fbClaimRes.status).toBe(200); + const fbClaim = (await fbClaimRes.json()) as TaskClaimView; + + const fbCompleteRes = await fetch( + `${baseUrl}/api/issues/${finalizeBlocker.id}/claim/complete`, + { + method: "POST", + headers: { + "content-type": "application/json", + "x-paperclip-claim-token": fbClaim.claimToken, + }, + body: JSON.stringify({ claimEpoch: fbClaim.claimEpoch }), + }, + ); + expect(fbCompleteRes.status).toBe(200); + + // Still unready while workspace_finalize has not succeeded + const stillUnreadyClaim = await fetch( + `${baseUrl}/api/companies/${company.id}/tasks/claim`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ channel: finalizeChannel!.path, wait: 0 }), + }, + ); + expect(stillUnreadyClaim.status).toBe(204); + + // Blocking pool worker waits while workspace_finalize completes and backstop runs + const waitingWorkerClaim = fetch( + `${baseUrl}/api/companies/${company.id}/tasks/claim`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ channel: finalizeChannel!.path, wait: "3s" }), + }, + ); + await new Promise((resolve) => setTimeout(resolve, 60)); + await db.insert(workspaceOperations).values({ + companyId: company.id, + executionWorkspaceId: execWs!.id, + issueId: finalizeBlocker.id, + phase: "workspace_finalize", + status: "succeeded", + startedAt: new Date(Date.now() - 500), + finishedAt: new Date(), + }); + await recoveryService(db, { + enqueueWakeup: async () => null, + }).reconcileResolvedDependencyWakeBackstop({ + blockerIssueId: finalizeBlocker.id, + source: "workspace.finalize", + }); + + const wokenClaimRes = await waitingWorkerClaim; + expect(wokenClaimRes.status).toBe(200); + const wokenClaim = (await wokenClaimRes.json()) as TaskClaimView; + expect(wokenClaim.issue.id).toBe(poolDep.id); + }); +}); diff --git a/server/src/__tests__/openapi-routes.test.ts b/server/src/__tests__/openapi-routes.test.ts index 69b4e6f3007..05fb83ca5b3 100644 --- a/server/src/__tests__/openapi-routes.test.ts +++ b/server/src/__tests__/openapi-routes.test.ts @@ -72,6 +72,9 @@ const apiPrefixes: Record = { "folders.ts": "/api", "goals.ts": "/api", "health.ts": "/api/health", + "headless-channels-schemas.ts": "/api", + "headless-identity.ts": "/api", + "headless-queues-events.ts": "/api", "ready.ts": "/api/ready", "liveness.ts": "/api/liveness", "inbox-agent-policy.ts": "/api", diff --git a/server/src/adapters/registry.ts b/server/src/adapters/registry.ts index 8512db5a0ff..223ada6288d 100644 --- a/server/src/adapters/registry.ts +++ b/server/src/adapters/registry.ts @@ -1011,6 +1011,29 @@ const piLocalAdapter: ServerAdapterModule = { agentConfigurationDoc: piAgentConfigurationDoc, }; +const headlessAdapter: ServerAdapterModule = { + type: "headless", + runtimeToolDelivery: "invocation_context", + execute: async (ctx) => { + ctx.onDispatch?.(); + return { exitCode: 0, signal: null, timedOut: false }; + }, + testEnvironment: async () => ({ + adapterType: "headless", + status: "pass", + checks: [], + testedAt: new Date().toISOString(), + }), + models: [], + supportsLocalAgentJwt: false, + agentConfigurationDoc: `# headless agent configuration + +Adapter: headless (Headless (CLI / SDK)) + +Pull-only headless identity. Headless agents pull tasks and subscribe to board events using their agent API key rather than being spawned by the heartbeat runner. +`, +}; + const adaptersByType = new Map(); // For builtin types that are overridden by an external adapter, we keep the @@ -1040,6 +1063,7 @@ function registerBuiltInAdapters() { openclawGatewayAdapter, processAdapter, httpAdapter, + headlessAdapter, ]) { adaptersByType.set(adapter.type, adapter); } @@ -1140,7 +1164,7 @@ export function registerServerAdapter(adapter: ServerAdapterModule): void { export function unregisterServerAdapter(type: string): void { assertExternalAdapterCodeAllowed(); - if (type === processAdapter.type || type === httpAdapter.type) return; + if (type === processAdapter.type || type === httpAdapter.type || type === headlessAdapter.type) return; if (builtinFallbacks.has(type)) { pausedOverrides.delete(type); const fallback = builtinFallbacks.get(type); @@ -1249,9 +1273,9 @@ export function listServerAdapters(): ServerAdapterModule[] { */ export function listEnabledServerAdapters(disabled: string[]): ServerAdapterModule[] { const disabledSet = disabled.length > 0 ? new Set(disabled) : null; - return disabledSet - ? Array.from(adaptersByType.values()).filter((a) => !disabledSet.has(a.type)) - : Array.from(adaptersByType.values()); + return Array.from(adaptersByType.values()).filter( + (a) => a.type !== headlessAdapter.type && (!disabledSet || !disabledSet.has(a.type)), + ); } export async function detectAdapterModel( diff --git a/server/src/app.ts b/server/src/app.ts index adb93b108e8..722fc76fbde 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -131,6 +131,11 @@ import { environmentService } from "./services/environments.js"; import { environmentRuntimeService } from "./services/environment-runtime.js"; import { projectRoutes } from "./routes/projects.js"; import { issueRoutes } from "./routes/issues.js"; +import { headlessIdentityRoutes } from "./routes/headless-identity.js"; +import { headlessChannelsSchemasRoutes } from "./routes/headless-channels-schemas.js"; +import { headlessQueuesEventsRoutes } from "./routes/headless-queues-events.js"; +import { createClaimLeaseExpiryWorker } from "./services/headless-task-queue.js"; +import { createScheduledBoardPostsWorker } from "./services/headless-events-schedules-interactions.js"; import { linkPreviewRoutes } from "./routes/link-previews.js"; import { issueTreeControlRoutes } from "./routes/issue-tree-control.js"; import { caseRoutes } from "./routes/cases.js"; @@ -777,6 +782,7 @@ export async function createApp( api.use(openApiRoutes()); api.use("/cloud", cloudRoutes()); api.use(cloudInferenceRoutes(db, cloudTrialInferenceController)); + api.use(headlessIdentityRoutes(db, { deploymentMode: opts.deploymentMode })); api.use("/companies", companyRoutes(db, opts.storageService)); api.use(llmRoutes(db)); api.use(folderRoutes(db)); @@ -1003,6 +1009,11 @@ export async function createApp( // Issue routes are intentionally mounted after the gateway is constructed because // issue approval endpoints delegate to it. The intervening routers use distinct // route prefixes, so this dependency does not change issue-route precedence. + api.use(headlessChannelsSchemasRoutes(db, { deploymentMode: opts.deploymentMode })); + api.use(headlessQueuesEventsRoutes(db, { + deploymentMode: opts.deploymentMode, + heartbeat: heartbeatService(db, { pluginWorkerManager: workerManager }), + })); api.use(issueRoutes(db, opts.storageService, { chatRunRetries: chatChannels, pluginWorkerManager: workerManager, @@ -1415,6 +1426,8 @@ export async function createApp( const importSpoolCleanup = registerImportSpoolCleanupWork(db, deliveryWork, resolveDefaultImportTransferSpoolRoot(), () => !isWarmStandby() && !isIdleTaskDrainActive()); registerBrowserUseCleanup(deliveryWork, browserUse, () => !isIdleTaskDrainActive()); + deliveryWork.register(DELIVERY_QUEUES.claimLeaseExpiry, createClaimLeaseExpiryWorker(db).deliveryTask); + deliveryWork.register(DELIVERY_QUEUES.scheduledBoardPosts, createScheduledBoardPostsWorker(db).deliveryTask); void companyTransferRunService diff --git a/server/src/middleware/auth.ts b/server/src/middleware/auth.ts index 84e9679737e..9760b1f9eb2 100644 --- a/server/src/middleware/auth.ts +++ b/server/src/middleware/auth.ts @@ -383,19 +383,32 @@ export function actorMiddleware(db: Db, opts: ActorMiddlewareOptions): RequestHa const access = await boardAuth.resolveBoardAccess(boardKey.userId); if (access.user) { await boardAuth.touchBoardApiKey(boardKey.id); + const scopedCompanyIds = boardKey.companyId + ? access.companyIds.filter((id) => id === boardKey.companyId) + : access.companyIds; + const scopedMemberships = boardKey.companyId + ? access.memberships.filter((m) => m.companyId === boardKey.companyId) + : access.memberships; + const hasKeyRestriction = Boolean( + boardKey.companyId || boardKey.lockedProfile || boardKey.scopes, + ); req.actor = { type: "board", userId: boardKey.userId, userName: access.user?.name ?? null, userEmail: access.user?.email ?? null, - companyIds: access.companyIds, - memberships: access.memberships, - isInstanceAdmin: access.isInstanceAdmin, + companyIds: scopedCompanyIds, + memberships: scopedMemberships, + isInstanceAdmin: hasKeyRestriction ? false : access.isInstanceAdmin, + ignoreInstanceAdmin: hasKeyRestriction ? true : undefined, keyId: boardKey.id, + keyCompanyId: boardKey.companyId ?? null, + keyLockedProfile: boardKey.lockedProfile ?? null, + keyScopes: boardKey.scopes ?? null, runId: runIdHeader || undefined, source: "board_key", }; - if (isCloudManagedInstance() && (access.isInstanceAdmin || access.companyIds.length)) { + if (isCloudManagedInstance() && (!hasKeyRestriction && access.isInstanceAdmin || scopedCompanyIds.length)) { _res.once("finish", () => { if (_res.statusCode >= 200 && _res.statusCode < 400) idleApiActivity.record(); }); } next(); @@ -407,7 +420,7 @@ export function actorMiddleware(db: Db, opts: ActorMiddlewareOptions): RequestHa .select() .from(agentApiKeys) .where(and(eq(agentApiKeys.keyHash, hashToken(token)), isNull(agentApiKeys.revokedAt))) - .then((rows) => rows[0] ?? null); + .then((rows) => rows.find((row) => !row.expiresAt || row.expiresAt.getTime() > Date.now()) ?? null); if (!key) { const claims = verifiedClaims; diff --git a/server/src/modules/agent-lifecycle/index.ts b/server/src/modules/agent-lifecycle/index.ts index 33c9d8f73ae..73222afe1b5 100644 --- a/server/src/modules/agent-lifecycle/index.ts +++ b/server/src/modules/agent-lifecycle/index.ts @@ -63,6 +63,45 @@ export async function requestAgentHireInTransaction(tx: Db, effects: LifecycleEf return records.create(...args); } +export async function createHeadlessAgentInTransaction( + tx: Db, + effects: LifecycleEffects, + input: { + companyId: string; + name: string; + role: string; + createdByUserId: string | null; + }, +) { + if (!("nestedIndex" in tx)) { + throw new AgentLifecycleConflict("Headless agent creation requires a database transaction"); + } + const [inserted] = await tx + .insert(agents) + .values({ + companyId: input.companyId, + name: input.name, + role: input.role, + adapterType: "headless", + status: "active", + lifecycleState: "ready", + lifecycleVersion: 1, + lifecycleHolds: [], + runtimeConfig: { + heartbeat: { + enabled: false, + wakeOnAssignment: false, + wakeOnOnDemand: false, + wakeOnAutomation: false, + }, + }, + createdByUserId: input.createdByUserId, + }) + .returning(); + await effects.recordCreation(tx, input.companyId, inserted!.id); + return inserted!; +} + export function createAgentLifecycle(db: Db, effects: LifecycleEffects) { assertRootDatabase(db); const records = agentRecords(db, effects); diff --git a/server/src/routes/access.ts b/server/src/routes/access.ts index cdba0bb983d..bfea3bfb084 100644 --- a/server/src/routes/access.ts +++ b/server/src/routes/access.ts @@ -18,11 +18,13 @@ import { fileURLToPath } from "node:url"; import { Router } from "express"; import type { NextFunction, Request, Response } from "express"; import { and, desc, eq, gt, inArray, isNotNull, isNull, lte, ne } from "drizzle-orm"; +import { z } from "zod"; import type { Db } from "@paperclipai/db"; import { assets, agentApiKeys, authUsers, + boardApiKeys, companies, companyLogos, companyMemberships, @@ -34,6 +36,7 @@ import { import { EXTERNAL_AGENT_TOOL_GUIDANCE, acceptInviteSchema, + clientScopesSchema, createCliAuthChallengeSchema, claimJoinRequestApiKeySchema, createBoardApiKeySchema, @@ -60,6 +63,11 @@ import { badRequest, tooManyRequests } from "../errors.js"; +import { + actionMatchesScopePattern, + actionScopePatternCovers, + channelScopePatternCovers, +} from "../services/headless-common.js"; import { getHiddenSettings } from "../services/settings-visibility.js"; import { runtimeCanonicalOrigin } from "../services/cloud-runtime-identity.js"; @@ -2715,10 +2723,32 @@ export function accessRoutes( res.json({ claimed: true, userId: claimed.userId }); }); + const createCliAuthChallengeBodySchema = createCliAuthChallengeSchema + .extend({ + challengeKind: z.enum(["board", "agent_key"]).optional().default("board"), + agentName: z.string().trim().min(1).max(120).optional().nullable(), + agentRole: z.string().trim().min(1).max(60).optional().nullable(), + }) + .superRefine((value, ctx) => { + if (value.challengeKind === "agent_key" && !value.agentName?.trim()) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "agentName is required when challengeKind is 'agent_key'", + path: ["agentName"], + }); + } + }); + + const createBoardApiKeyBodySchema = createBoardApiKeySchema.extend({ + companyId: z.string().guid().optional().nullable(), + lockedProfile: z.string().trim().min(1).max(120).optional().nullable(), + scopes: clientScopesSchema.optional().nullable(), + }); + router.post( "/cli-auth/challenges", limitCliAuth(cliAuthCreateRateLimiter), - validate(createCliAuthChallengeSchema), + validate(createCliAuthChallengeBodySchema), async (req, res) => { const created = await boardAuth.createCliAuthChallenge(req.body); const approvalPath = buildCliAuthApprovalPath( @@ -2770,6 +2800,43 @@ export function accessRoutes( }); }); + async function resolveCallingBoardKeyRestrictions(req: Request): Promise<{ + companyId: string | null; + lockedProfile: string | null; + scopes: { channels?: string[]; actions?: string[] } | null; + }> { + let callingKey: { + companyId: string | null; + lockedProfile: string | null; + scopes: { channels?: string[]; actions?: string[] } | null; + } | null = null; + if (req.actor.source === "board_key" && req.actor.keyId) { + const [row] = await db + .select({ + companyId: boardApiKeys.companyId, + lockedProfile: boardApiKeys.lockedProfile, + scopes: boardApiKeys.scopes, + }) + .from(boardApiKeys) + .where(eq(boardApiKeys.id, req.actor.keyId)); + callingKey = row ?? null; + } + return { + companyId: callingKey?.companyId ?? req.actor.keyCompanyId ?? null, + lockedProfile: + callingKey?.lockedProfile?.trim() || req.actor.keyLockedProfile?.trim() || null, + scopes: callingKey?.scopes ?? req.actor.keyScopes ?? null, + }; + } + + function hasBoardKeyRestrictions(restrictions: { + companyId: string | null; + lockedProfile: string | null; + scopes: { channels?: string[]; actions?: string[] } | null; + }): boolean { + return Boolean(restrictions.companyId || restrictions.lockedProfile || restrictions.scopes); + } + router.post( "/cli-auth/challenges/:id/approve", validate(resolveCliAuthChallengeSchema), @@ -2781,6 +2848,16 @@ export function accessRoutes( ) { throw unauthorized("Sign in before approving CLI access"); } + if ( + req.actor.source !== "session" && + req.actor.source !== "cloud_tenant" && + !isLocalImplicit(req) + ) { + throw forbidden( + "Board API keys cannot approve CLI authentication challenges; sign in via browser", + { code: "forbidden" }, + ); + } if (!isUuidLike(id)) throw badRequest("Invalid CLI auth challenge ID"); const userId = req.actor.userId ?? "local-board"; @@ -2795,6 +2872,8 @@ export function accessRoutes( status: approved.status, userId, keyId: approved.challenge.boardApiKeyId ?? null, + agentId: approved.challenge.approvedAgentId ?? null, + companyId: approved.challenge.requestedCompanyId ?? null, expiresAt: approved.challenge.expiresAt.toISOString(), }); }, @@ -2819,14 +2898,33 @@ export function accessRoutes( throw unauthorized("Board authentication required"); } const accessSnapshot = await boardAuth.resolveBoardAccess(req.actor.userId); + let isInstanceAdmin = + req.actor.source === "cloud_tenant" + ? req.actor.isInstanceAdmin === true + : accessSnapshot.isInstanceAdmin; + let companyIds = accessSnapshot.companyIds; + let memberships = accessSnapshot.memberships; + + if (req.actor.source === "board_key") { + const restrictions = await resolveCallingBoardKeyRestrictions(req); + if (hasBoardKeyRestrictions(restrictions)) { + isInstanceAdmin = false; + const actorCompanyIds = req.actor.companyIds ?? []; + companyIds = restrictions.companyId + ? actorCompanyIds.filter((cid) => cid === restrictions.companyId) + : actorCompanyIds; + memberships = accessSnapshot.memberships.filter((m) => + companyIds.includes(m.companyId), + ); + } + } + res.json({ user: accessSnapshot.user, userId: req.actor.userId, - isInstanceAdmin: req.actor.source === "cloud_tenant" - ? req.actor.isInstanceAdmin === true - : accessSnapshot.isInstanceAdmin, - companyIds: accessSnapshot.companyIds, - memberships: accessSnapshot.memberships, + isInstanceAdmin, + companyIds, + memberships, source: req.actor.source ?? "none", keyId: req.actor.source === "board_key" ? req.actor.keyId ?? null : null, }); @@ -2836,6 +2934,14 @@ export function accessRoutes( if (req.actor.type !== "board" || !req.actor.userId) { throw unauthorized("Board authentication required"); } + if (req.actor.source === "board_key") { + const restrictions = await resolveCallingBoardKeyRestrictions(req); + if (hasBoardKeyRestrictions(restrictions)) { + throw forbidden("Restricted board API keys cannot manage other board API keys", { + code: "scope_denied", + }); + } + } const keys = await boardAuth.listBoardApiKeys(req.actor.userId, { includeInactive: req.query.includeInactive === "true", }); @@ -2844,24 +2950,121 @@ export function accessRoutes( router.post( "/board-api-keys", - validate(createBoardApiKeySchema), + validate(createBoardApiKeyBodySchema), async (req, res) => { if (req.actor.type !== "board" || !req.actor.userId) { throw unauthorized("Board authentication required"); } - if (req.body.requestedCompanyId) { - assertCompanyAccess(req, req.body.requestedCompanyId); + const targetCompanyId = req.body.companyId ?? req.body.requestedCompanyId ?? null; + if (targetCompanyId) { + assertCompanyAccess(req, targetCompanyId); + } + let nextCompanyId = req.body.companyId; + let nextLockedProfile = req.body.lockedProfile; + let nextScopes = req.body.scopes; + if (req.actor.source === "board_key") { + const { + companyId: effectiveCallerCompanyId, + lockedProfile: effectiveCallerLockedProfile, + scopes: effectiveCallerScopes, + } = await resolveCallingBoardKeyRestrictions(req); + + if (effectiveCallerScopes?.actions) { + const allowed = effectiveCallerScopes.actions.some((pattern) => + actionMatchesScopePattern("board_keys.create", pattern), + ); + if (!allowed) { + throw forbidden("Caller scopes do not allow creating board API keys", { + code: "scope_denied", + }); + } + } + if (effectiveCallerCompanyId) { + if (req.body.companyId === null || (targetCompanyId && effectiveCallerCompanyId !== targetCompanyId)) { + throw forbidden("Board API key is scoped to another company", { + code: "company_scope_denied", + }); + } + nextCompanyId = effectiveCallerCompanyId; + } + if (effectiveCallerLockedProfile) { + if (req.body.lockedProfile === null) { + throw forbidden("Profile-locked board API key cannot mint an unlocked key", { + code: "profile_locked", + }); + } + if ( + req.body.lockedProfile !== undefined && + req.body.lockedProfile.trim().toLowerCase() !== + effectiveCallerLockedProfile.toLowerCase() + ) { + throw forbidden( + `Board API key is locked to profile '${effectiveCallerLockedProfile}'`, + { code: "profile_locked" }, + ); + } + nextLockedProfile = effectiveCallerLockedProfile; + } + if (effectiveCallerScopes) { + if (req.body.scopes === null) { + throw forbidden("Scoped board API key cannot mint an unrestricted key", { + code: "scope_denied", + }); + } + if (req.body.scopes === undefined) { + nextScopes = effectiveCallerScopes; + } else { + const requestedScopes = req.body.scopes; + if (effectiveCallerScopes.channels) { + if (!requestedScopes.channels) { + throw forbidden("Child key must retain caller channel restrictions", { + code: "scope_denied", + }); + } + const allCovered = requestedScopes.channels.every((ch: string) => + effectiveCallerScopes.channels!.some((allowed) => + channelScopePatternCovers(allowed, ch), + ), + ); + if (!allCovered) { + throw forbidden("Child key channels exceed caller key scopes", { + code: "scope_denied", + }); + } + } + if (effectiveCallerScopes.actions) { + if (!requestedScopes.actions) { + throw forbidden("Child key must retain caller action restrictions", { + code: "scope_denied", + }); + } + const allCovered = requestedScopes.actions.every((act: string) => + effectiveCallerScopes.actions!.some((allowed) => + actionScopePatternCovers(allowed, act), + ), + ); + if (!allCovered) { + throw forbidden("Child key actions exceed caller key scopes", { + code: "scope_denied", + }); + } + } + } + } } const key = await boardAuth.createNamedBoardApiKey({ userId: req.actor.userId, name: req.body.name, expiresAt: req.body.expiresAt === undefined ? undefined : req.body.expiresAt, + ...(nextCompanyId !== undefined ? { companyId: nextCompanyId } : {}), + ...(nextLockedProfile !== undefined ? { lockedProfile: nextLockedProfile } : {}), + ...(nextScopes !== undefined ? { scopes: nextScopes } : {}), }); const companyIds = await boardAuth.resolveBoardActivityCompanyIds({ userId: req.actor.userId, - requestedCompanyId: req.body.requestedCompanyId ?? null, + requestedCompanyId: targetCompanyId, boardApiKeyId: key.id, }); for (const companyId of companyIds) { @@ -2875,7 +3078,9 @@ export function accessRoutes( details: { boardApiKeyId: key.id, name: key.name, - requestedCompanyId: req.body.requestedCompanyId ?? null, + companyId: key.companyId ?? null, + lockedProfile: key.lockedProfile ?? null, + requestedCompanyId: targetCompanyId, expiresAt: key.expiresAt?.toISOString() ?? null, }, }); @@ -2893,6 +3098,14 @@ export function accessRoutes( if (!isUuidLike(keyId)) { throw badRequest("Invalid board API key ID"); } + if (req.actor.source === "board_key") { + const restrictions = await resolveCallingBoardKeyRestrictions(req); + if (hasBoardKeyRestrictions(restrictions)) { + throw forbidden("Restricted board API keys cannot manage other board API keys", { + code: "scope_denied", + }); + } + } const key = await boardAuth.getBoardApiKeyForUser(keyId, req.actor.userId); if (!key) throw notFound("Board API key not found"); const revoked = await boardAuth.revokeBoardApiKey(key.id, { userId: req.actor.userId, revokedVia: "board_api_key_lifecycle" }); diff --git a/server/src/routes/agents.ts b/server/src/routes/agents.ts index 203913f0291..59b34569f12 100644 --- a/server/src/routes/agents.ts +++ b/server/src/routes/agents.ts @@ -6243,8 +6243,17 @@ export function agentRoutes( res.json({ ok: true }); }); + function assertBoardKeyCanManageAgentKeys(req: Request) { + if (req.actor.source === "board_key" && (req.actor.keyLockedProfile || req.actor.keyScopes)) { + throw forbidden("Scoped or profile-locked board API keys cannot manage agent API keys", { + code: "scope_denied", + }); + } + } + router.get("/agents/:id/keys", async (req, res) => { assertBoard(req); + assertBoardKeyCanManageAgentKeys(req); const id = req.params.id as string; const agent = await getAccessibleAgent(req, res, id); if (!agent) { @@ -6256,6 +6265,7 @@ export function agentRoutes( router.post("/agents/:id/keys", validate(createAgentKeySchema), async (req, res) => { assertBoard(req); + assertBoardKeyCanManageAgentKeys(req); const id = req.params.id as string; const agent = await getAccessibleAgent(req, res, id); if (!agent) { @@ -6285,6 +6295,7 @@ export function agentRoutes( router.delete("/agents/:id/keys/:keyId", async (req, res) => { assertBoard(req); + assertBoardKeyCanManageAgentKeys(req); const id = req.params.id as string; const keyId = req.params.keyId as string; const agent = await getAccessibleAgent(req, res, id); diff --git a/server/src/routes/authz.ts b/server/src/routes/authz.ts index 4a29aac022b..2703c4514b0 100644 --- a/server/src/routes/authz.ts +++ b/server/src/routes/authz.ts @@ -239,6 +239,25 @@ export function assertCompanyAccess(req: Request, companyId: string) { } } if (req.actor.type === "board" && req.actor.source !== "local_implicit") { + if (req.actor.source === "board_key") { + if (req.actor.keyCompanyId && req.actor.keyCompanyId !== companyId) { + throw forbidden("Board API key is scoped to another company", { + code: "company_scope_denied", + }); + } + if (req.actor.keyScopes) { + const hasChannelRestriction = Array.isArray(req.actor.keyScopes.channels); + const actionsList = req.actor.keyScopes.actions; + const allowsWildcardAction = + Array.isArray(actionsList) && + actionsList.some((action) => action.trim() === "*"); + if (hasChannelRestriction || (Array.isArray(actionsList) && !allowsWildcardAction)) { + throw forbidden("Scoped board API key cannot access unrestricted company routes", { + code: "scope_denied", + }); + } + } + } const allowedCompanies = req.actor.companyIds ?? []; if (!allowedCompanies.includes(companyId)) { throw forbidden("User does not have access to this company"); diff --git a/server/src/routes/headless-channels-schemas.ts b/server/src/routes/headless-channels-schemas.ts new file mode 100644 index 00000000000..68550999ef1 --- /dev/null +++ b/server/src/routes/headless-channels-schemas.ts @@ -0,0 +1,1430 @@ +import { + and, + asc, + desc, + eq, + gt, + inArray, + isNotNull, + isNull, + like, + lt, + notInArray, + or, + sql, +} from "drizzle-orm"; +import { Router, type Request, type Response, type NextFunction } from "express"; +import type { Db } from "@paperclipai/db"; +import { + boardEvents, + channels, + issueComments, + issueRelations, + issues, + issueThreadInteractions, + projects, +} from "@paperclipai/db"; +import { + createChannelInputSchema, + ISSUE_PRIORITIES, + ISSUE_SCOPES, + ISSUE_STATUSES, + isUuidLike, + matchesLabelFilter, + parseEventCursor, + parseLabelFilterExpr, + parseSchemaRef, + SCHEMA_REF_REGEX, + type BoardEventView, + type DeploymentMode, + type InteractionView, + type IssuePriority, + type IssueScope, + type IssueStatus, + type SchemaBlock, + type ThreadDetailView, +} from "@paperclipai/shared"; +import { badRequest, conflict, forbidden, unprocessable } from "../errors.js"; +import { authorizationService } from "../services/authorization.js"; +import { + logActivity, + publishActivity, + type ActivityPublication, +} from "../services/activity-log.js"; +import { DELIVERY_QUEUES, notifyDeliveryWork } from "../services/delivery-work-notifications.js"; +import { issueTreeControlService } from "../services/issue-tree-control.js"; +import { listIssueDependencyReadinessMap } from "../services/issues.js"; +import { extractClaimToken, verifyClaimToken } from "../services/headless-task-queue.js"; +import { + buildChannelViews, + createChannelPost, + ensureChannel, + listChannels, + listChannelThreads, + normalizeChannelPathOrThrow, + resolveAssigneeAgent, + validateWritableKvLabelsOrThrow, +} from "../services/headless-channels.js"; +import { + allowsUnchanneledScope, + appendBoardEvent, + assertCanonicalIssueAccess, + assertChannelAccess, + assertIssueChannelScopeAccess, + buildSqlIssueLabelFilterCondition, + canAccessChannel, + channelSubtreeCondition, + enforceHeadlessScopes, + findInaccessibleChannelIds, + getLatestCompanyEventCursor, + loadHeadlessIssueView, + loadHeadlessIssueViews, + publishCommittedBoardEvent, + resolveHeadlessActor, + resolveHeadlessIssueReadCondition, + resolveIssueByIdOrIdentifier, + resolveProjectReference, + serializeCommentView, +} from "../services/headless-common.js"; +import { + createBatchIssuesPlan, + mutateIssueKvLabels, +} from "../services/headless-labels-batch.js"; +import { + assertSchemaExists, + createCompanySchema, + formatBlocksAsFencedJson, + getCompanySchema, + listCompanySchemas, + validateSchemaBlocks, +} from "../services/headless-schemas.js"; + +function toStringArray(val: unknown): string[] { + if (val === undefined || val === null) return []; + const rawList = Array.isArray(val) ? val : [val]; + return rawList + .filter((x): x is string => typeof x === "string") + .flatMap((x) => x.split(",")) + .map((s) => s.trim()) + .filter((s) => s.length > 0); +} + +function mapInteractionRowToView( + row: typeof issueThreadInteractions.$inferSelect, + identifier: string, + cursor: string, +): InteractionView { + const payload = (row.payload ?? {}) as unknown as Record; + const result = (row.result ?? {}) as unknown as Record; + const kind: InteractionView["kind"] = + row.kind === "ask_user_questions" + ? "ask_user_questions" + : "request_confirmation"; + const status: InteractionView["status"] = + row.status === "accepted" || + row.status === "rejected" || + row.status === "answered" || + row.status === "cancelled" + ? row.status + : "pending"; + const resolverPolicy: InteractionView["resolverPolicy"] = + row.effectiveResolverPolicy === "human_only" || + row.effectiveResolverPolicy === "not_creator" + ? row.effectiveResolverPolicy + : "anyone"; + + const prompt = + row.title ?? + row.summary ?? + (typeof payload.prompt === "string" ? payload.prompt : ""); + + let choices: string[] | undefined; + if (Array.isArray(payload.questions) && payload.questions.length > 0) { + const firstQ = payload.questions[0] as Record | undefined; + if (firstQ && Array.isArray(firstQ.options)) { + choices = firstQ.options + .map((opt) => + typeof opt === "string" + ? opt + : typeof (opt as { label?: unknown })?.label === "string" + ? (opt as { label: string }).label + : null, + ) + .filter((x): x is string => Boolean(x)); + } + } + + return { + id: row.id, + issueId: row.issueId, + identifier, + kind, + status, + prompt, + ...(choices && choices.length > 0 ? { choices } : {}), + resolverPolicy, + continuationPolicy: row.continuationPolicy, + answer: + typeof result.summaryMarkdown === "string" + ? result.summaryMarkdown + : typeof result.answer === "string" + ? result.answer + : null, + note: + typeof result.reason === "string" + ? result.reason + : typeof result.note === "string" + ? result.note + : null, + cursor, + createdAt: row.createdAt.toISOString(), + resolvedAt: row.resolvedAt ? row.resolvedAt.toISOString() : null, + }; +} + +function isRestrictedBoardKeyRequest(req: Request): boolean { + return ( + req.actor.source === "board_key" && + Boolean( + req.actor.keyScopes?.channels || + (req.actor.keyScopes?.actions && + !req.actor.keyScopes.actions.some((a) => a.trim() === "*")), + ) + ); +} + +export function headlessChannelsSchemasRoutes( + db: Db, + opts?: { deploymentMode?: DeploymentMode }, +): Router { + const router = Router(); + const deploymentMode = opts?.deploymentMode; + + router.get( + "/companies/:companyId/channels", + async (req: Request, res: Response) => { + const companyId = req.params.companyId as string; + const actor = await resolveHeadlessActor(db, req, companyId, { + deploymentMode, + requiredAction: "read", + }); + const prefix = + typeof req.query.prefix === "string" ? req.query.prefix : undefined; + const items = await listChannels(db, companyId, actor, prefix); + res.json({ items }); + }, + ); + + router.post( + "/companies/:companyId/channels", + async (req: Request, res: Response) => { + const companyId = req.params.companyId as string; + const parsed = createChannelInputSchema.safeParse(req.body ?? {}); + if (!parsed.success) { + throw badRequest( + parsed.error.issues + .map((i) => `${i.path.join(".") || "$"}: ${i.message}`) + .join("; "), + { + error: "validation_error", + code: "validation_error", + issues: parsed.error.issues, + }, + ); + } + + const actor = await resolveHeadlessActor(db, req, companyId, { + deploymentMode, + requiredAction: "post", + requiredChannel: parsed.data.path, + }); + + const publications: ActivityPublication[] = []; + const view = await db.transaction(async (tx) => { + const ch = await ensureChannel(tx, companyId, actor, parsed.data, { + allowUpdateExisting: true, + publications, + }); + const views = await buildChannelViews(tx, companyId, [ch]); + return views[0]!; + }); + for (const pub of publications) { + publishActivity(pub); + } + + res.status(201).json(view); + }, + ); + + router.post( + "/companies/:companyId/channels/posts", + async (req: Request, res: Response) => { + const companyId = req.params.companyId as string; + const body = (req.body ?? {}) as Record; + const requiredAction = + body.status === "todo" ? "tasks.create" : "post"; + const actor = await resolveHeadlessActor(db, req, companyId, { + deploymentMode, + requiredAction, + }); + + const result = await createChannelPost(db, companyId, actor, body); + res.status(result.created ? 201 : 200).json(result.issue); + }, + ); + + router.get( + "/companies/:companyId/channels/threads", + async (req: Request, res: Response) => { + const companyId = req.params.companyId as string; + const actor = await resolveHeadlessActor(db, req, companyId, { + deploymentMode, + requiredAction: "read", + }); + + const channel = + typeof req.query.channel === "string" && req.query.channel.trim() + ? req.query.channel + : "general"; + const status = toStringArray(req.query.status); + const label = toStringArray(req.query.label); + const after = + typeof req.query.after === "string" ? req.query.after : undefined; + const rawLimit = + typeof req.query.limit === "string" + ? Number.parseInt(req.query.limit, 10) + : undefined; + const limit = + rawLimit !== undefined && Number.isFinite(rawLimit) + ? rawLimit + : undefined; + + const page = await listChannelThreads(db, companyId, actor, { + channel, + status: status.length > 0 ? status : undefined, + label: label.length > 0 ? label : undefined, + after, + limit, + readCondition: await resolveHeadlessIssueReadCondition(db, req), + }); + res.json(page); + }, + ); + + router.patch("/issues/:id/kv-labels", async (req: Request, res: Response) => { + const issue = await resolveIssueByIdOrIdentifier(db, req.params.id as string); + const actor = await resolveHeadlessActor(db, req, issue.companyId, { + deploymentMode, + requiredAction: "label", + }); + await assertCanonicalIssueAccess(db, req, issue, "issue:mutate"); + await assertIssueChannelScopeAccess(db, issue, actor); + const updated = await mutateIssueKvLabels( + db, + issue.id, + actor, + req.body ?? {}, + ); + res.json(updated); + }); + + router.get( + "/companies/:companyId/schemas", + async (req: Request, res: Response) => { + const companyId = req.params.companyId as string; + const actor = await resolveHeadlessActor(db, req, companyId, { + deploymentMode, + requiredAction: "read", + }); + const items = await listCompanySchemas(db, companyId, actor); + res.json({ items }); + }, + ); + + router.get( + "/companies/:companyId/schemas/:ref", + async (req: Request, res: Response) => { + const companyId = req.params.companyId as string; + const actor = await resolveHeadlessActor(db, req, companyId, { + deploymentMode, + requiredAction: "read", + }); + const schema = await getCompanySchema( + db, + companyId, + req.params.ref as string, + actor, + ); + res.json(schema); + }, + ); + + router.post( + "/companies/:companyId/schemas", + async (req: Request, res: Response) => { + const companyId = req.params.companyId as string; + const actor = await resolveHeadlessActor(db, req, companyId, { + deploymentMode, + requiredAction: "post", + }); + const result = await createCompanySchema( + db, + companyId, + actor, + req.body ?? {}, + ); + res.status(result.created ? 201 : 200).json(result); + }, + ); + + router.post( + "/companies/:companyId/issues/batch", + async (req: Request, res: Response) => { + const companyId = req.params.companyId as string; + const actor = await resolveHeadlessActor(db, req, companyId, { + deploymentMode, + requiredAction: "tasks.create", + }); + const result = await createBatchIssuesPlan( + db, + companyId, + actor, + req.body ?? {}, + ); + res.status(result.idempotentReplay ? 200 : 201).json(result); + }, + ); + + // Headless interceptor: POST /issues/:id/comments + router.post( + "/issues/:id/comments", + async (req: Request, res: Response, next: NextFunction) => { + const b = + req.body && typeof req.body === "object" + ? (req.body as Record) + : {}; + 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; + const hasProfileHeader = Boolean(req.header("x-paperclip-actor-profile")); + + let targetIssue: typeof issues.$inferSelect; + try { + targetIssue = await resolveIssueByIdOrIdentifier( + db, + req.params.id as string, + ); + } catch { + next(); + return; + } + + const isHeadless = + hasHeadlessBody || hasProfileHeader || targetIssue.channelId !== null; + const isRestrictedKey = isRestrictedBoardKeyRequest(req); + if (!isHeadless && !isRestrictedKey) { + next(); + return; + } + + const actor = await resolveHeadlessActor(db, req, targetIssue.companyId, { + deploymentMode, + requiredAction: "post", + }); + await assertCanonicalIssueAccess(db, req, targetIssue, "issue:comment"); + + const { channelPath } = await assertIssueChannelScopeAccess( + db, + targetIssue, + actor, + ); + if (!isHeadless) { + next(); + return; + } + + const mergedKvLabels = validateWritableKvLabelsOrThrow({ + ...((b.labels && typeof b.labels === "object" ? b.labels : {}) as Record< + string, + unknown + >), + ...((b.kvLabels && typeof b.kvLabels === "object" + ? b.kvLabels + : {}) as Record), + }); + + const combinedBlocks: SchemaBlock[] = Array.isArray(b.blocks) + ? (b.blocks as SchemaBlock[]) + : []; + if (b.schema && typeof b.schema === "object") { + const schemaInput = b.schema as { ref?: unknown; data?: unknown }; + if ( + typeof schemaInput.ref !== "string" || + !SCHEMA_REF_REGEX.test(schemaInput.ref.trim()) || + !schemaInput.data || + typeof schemaInput.data !== "object" || + Array.isArray(schemaInput.data) + ) { + throw badRequest("Invalid 'schema' block input", { + error: "validation_error", + code: "validation_error", + }); + } + const parsedRef = parseSchemaRef(schemaInput.ref); + combinedBlocks.push({ + schema: parsedRef.name, + version: parsedRef.version, + data: schemaInput.data as Record, + }); + } + const validatedBlocks = await validateSchemaBlocks( + db, + targetIssue.companyId, + combinedBlocks, + ); + + let bodyText = + typeof b.body === "string" && b.body.length > 0 + ? b.body + : typeof b.text === "string" && b.text.length > 0 + ? b.text + : ""; + if (!bodyText.trim()) { + if (validatedBlocks.length > 0) { + bodyText = formatBlocksAsFencedJson(validatedBlocks); + } else { + throw badRequest("Comment body or blocks required", { + error: "validation_error", + code: "validation_error", + }); + } + } + + const afterCursor = + typeof b.afterCommentId === "string" + ? b.afterCommentId.trim() + : typeof b.after === "string" + ? b.after.trim() + : undefined; + const clientRequestId = + typeof b.idempotencyKey === "string" && b.idempotencyKey.trim() + ? b.idempotencyKey.trim() + : typeof b.clientRequestId === "string" && b.clientRequestId.trim() + ? b.clientRequestId.trim() + : null; + const authorUserId = actor.agentId ? null : (actor.userId ?? "local-board"); + const identifier = targetIssue.identifier ?? targetIssue.id; + + const publications: ActivityPublication[] = []; + let committedEvent: BoardEventView | null = null; + + const txResult = await db.transaction(async (tx) => { + await tx + .select({ id: issues.id }) + .from(issues) + .where(eq(issues.id, targetIssue.id)) + .for("update"); + + if (clientRequestId) { + const [existing] = await tx + .select() + .from(issueComments) + .where( + and( + eq(issueComments.issueId, targetIssue.id), + eq(issueComments.clientRequestId, clientRequestId), + actor.agentId + ? eq(issueComments.authorAgentId, actor.agentId) + : eq(issueComments.authorUserId, authorUserId!), + ), + ) + .limit(1); + if (existing) { + const cursor = await getLatestCompanyEventCursor( + tx, + targetIssue.companyId, + ); + return { + comment: serializeCommentView(existing, identifier, cursor), + created: false, + }; + } + } + + if (afterCursor !== undefined) { + const [latest] = await tx + .select({ id: issueComments.id }) + .from(issueComments) + .where( + and( + eq(issueComments.issueId, targetIssue.id), + isNull(issueComments.deletedAt), + ), + ) + .orderBy(desc(issueComments.createdAt), desc(issueComments.id)) + .limit(1); + + const matches = latest + ? afterCursor === latest.id + : afterCursor === "none"; + if (!matches) { + throw conflict( + `New comments were posted after '${afterCursor}' (latest: ${latest?.id ?? "none"}). Read the thread before replying.`, + { + error: "stale_reply_cursor", + code: "stale_reply_cursor", + latestCommentId: latest?.id ?? null, + next: [`pc read ${identifier}`], + }, + ); + } + } + + const now = new Date(); + const [inserted] = await tx + .insert(issueComments) + .values({ + companyId: targetIssue.companyId, + issueId: targetIssue.id, + authorAgentId: actor.agentId, + authorUserId, + authorType: actor.agentId ? "agent" : "user", + actorProfile: actor.actorProfile, + body: bodyText, + kvLabels: mergedKvLabels, + schemaBlocks: validatedBlocks, + noSync: Boolean(b.internal), + clientRequestId, + createdAt: now, + updatedAt: now, + }) + .returning(); + + await tx + .update(issues) + .set({ updatedAt: now }) + .where(eq(issues.id, targetIssue.id)); + + if (targetIssue.channelId) { + await tx + .update(channels) + .set({ lastActivityAt: now, updatedAt: now }) + .where(eq(channels.id, targetIssue.channelId)); + } + + await logActivity( + tx as unknown as Db, + { + companyId: targetIssue.companyId, + actorType: actor.principalType === "agent" ? "agent" : "user", + actorId: + actor.principalType === "agent" + ? actor.agentId! + : (actor.userId ?? "local-board"), + agentId: actor.agentId, + issueId: targetIssue.id, + responsibleUserIdOverride: actor.responsibleUserId, + action: "issue.comment_added", + entityType: "issue", + entityId: targetIssue.id, + details: { + commentId: inserted!.id, + identifier, + internal: Boolean(b.internal), + }, + }, + publications, + ); + + committedEvent = await appendBoardEvent(tx, { + companyId: targetIssue.companyId, + type: "comment.posted", + channelId: targetIssue.channelId, + channelPath, + issueId: targetIssue.id, + identifier, + actor, + payload: { + commentId: inserted!.id, + body: bodyText.slice(0, 4000), + blocks: validatedBlocks, + labels: mergedKvLabels, + internal: Boolean(b.internal), + }, + }); + + return { + comment: serializeCommentView( + inserted!, + identifier, + committedEvent.cursor, + ), + created: true, + }; + }); + + if (txResult.created) { + for (const pub of publications) { + publishActivity(pub); + } + if (committedEvent) { + publishCommittedBoardEvent(committedEvent); + } + } + + res.status(txResult.created ? 201 : 200).json(txResult.comment); + }, + ); + + // Headless interceptor: PATCH /issues/:id + router.patch( + "/issues/:id", + async (req: Request, res: Response, next: NextFunction) => { + const b = + req.body && typeof req.body === "object" + ? (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")); + const isRestrictedKey = isRestrictedBoardKeyRequest(req); + + if (!isHeadless && !isRestrictedKey) { + next(); + return; + } + + let targetIssue: typeof issues.$inferSelect; + try { + targetIssue = await resolveIssueByIdOrIdentifier( + db, + req.params.id as string, + ); + } catch { + next(); + return; + } + const actor = await resolveHeadlessActor(db, req, targetIssue.companyId, { + deploymentMode, + requiredAction: isHeadless ? "tasks.create" : "write", + }); + await assertCanonicalIssueAccess(db, req, targetIssue, "issue:mutate"); + + const { channelPath } = await assertIssueChannelScopeAccess( + db, + targetIssue, + actor, + ); + if (!isHeadless) { + next(); + return; + } + + let labelPatch: Record | undefined; + if (b.labels !== undefined || b.kvLabels !== undefined) { + labelPatch = validateWritableKvLabelsOrThrow({ + ...((b.labels && typeof b.labels === "object" + ? b.labels + : {}) as Record), + ...((b.kvLabels && typeof b.kvLabels === "object" + ? b.kvLabels + : {}) as Record), + }); + } + + let nextStatus: IssueStatus | undefined; + if (b.status !== undefined) { + if ( + typeof b.status !== "string" || + !(ISSUE_STATUSES as readonly string[]).includes(b.status) + ) { + throw badRequest(`Invalid issue status '${String(b.status)}'`, { + error: "validation_error", + code: "validation_error", + }); + } + nextStatus = b.status as IssueStatus; + } + + let nextPriority: IssuePriority | undefined; + if (b.priority !== undefined) { + if ( + typeof b.priority !== "string" || + !(ISSUE_PRIORITIES as readonly string[]).includes(b.priority) + ) { + throw badRequest(`Invalid priority '${String(b.priority)}'`, { + error: "validation_error", + code: "validation_error", + }); + } + nextPriority = b.priority as IssuePriority; + } + + let nextScope: IssueScope | undefined; + if (b.scope !== undefined) { + if ( + typeof b.scope !== "string" || + !(ISSUE_SCOPES as readonly string[]).includes(b.scope) + ) { + throw badRequest(`Invalid scope '${String(b.scope)}'`, { + error: "validation_error", + code: "validation_error", + }); + } + nextScope = b.scope as IssueScope; + if (targetIssue.conversationAgentId && nextScope !== "chat") { + throw unprocessable("Conversation issues must keep scope 'chat'"); + } + if (!targetIssue.conversationAgentId && nextScope === "chat") { + throw unprocessable("Non-conversation issues cannot have scope 'chat'"); + } + if (req.actor.type === "agent" && nextScope !== targetIssue.scope) { + throw forbidden("Agents cannot change issue scope"); + } + } + + let nextResultSchemaRef: string | null | undefined; + if (b.resultSchema !== undefined) { + if (b.resultSchema === null) { + nextResultSchemaRef = null; + } else if (typeof b.resultSchema === "string") { + nextResultSchemaRef = await assertSchemaExists( + db, + targetIssue.companyId, + b.resultSchema, + ); + } else { + throw badRequest("resultSchema must be a string or null", { + error: "validation_error", + code: "validation_error", + }); + } + } + + let nextProjectId: string | null | undefined; + if (b.projectId !== undefined) { + nextProjectId = + b.projectId === null + ? null + : typeof b.projectId === "string" + ? await resolveProjectReference( + db, + targetIssue.companyId, + b.projectId, + req.actor, + ) + : undefined; + } + + let nextAssigneeAgentId: string | null | undefined; + if (b.assigneeAgentId !== undefined || b.for !== undefined) { + nextAssigneeAgentId = await resolveAssigneeAgent(db, targetIssue.companyId, { + assigneeAgentId: + b.assigneeAgentId === null + ? null + : typeof b.assigneeAgentId === "string" + ? b.assigneeAgentId + : undefined, + for: typeof b.for === "string" ? b.for : undefined, + }); + } + + const publications: ActivityPublication[] = []; + const committedEvents: BoardEventView[] = []; + + const updatedView = await db.transaction(async (tx) => { + const [locked] = await tx + .select() + .from(issues) + .where(eq(issues.id, targetIssue.id)) + .for("update"); + if (!locked) { + throw conflict("Issue disappeared during update"); + } + + const now = new Date(); + const updates: Partial = { + updatedAt: now, + }; + const statusChanging = nextStatus !== undefined && nextStatus !== locked.status; + const assigneeChanging = + nextAssigneeAgentId !== undefined && nextAssigneeAgentId !== locked.assigneeAgentId; + if ((statusChanging || assigneeChanging) && locked.claimTokenHash !== null) { + const claimToken = extractClaimToken( + typeof b.claimToken === "string" ? b.claimToken : undefined, + req.header("x-paperclip-claim-token") ?? undefined, + ); + if ( + actor.principalType === "agent" && + !verifyClaimToken(locked.claimTokenHash, claimToken) + ) { + throw conflict("claim_lost", { + code: "claim_lost", + currentEpoch: Number(locked.claimEpoch ?? 0), + status: locked.status, + }); + } + const leavesActiveClaim = + (nextStatus !== undefined && nextStatus !== "in_progress") || + (nextAssigneeAgentId !== undefined && + nextAssigneeAgentId !== locked.claimHolderAgentId); + if (leavesActiveClaim) { + await notifyDeliveryWork(tx, DELIVERY_QUEUES.claimLeaseExpiry, locked.id); + updates.claimEpoch = Number(locked.claimEpoch ?? 0) + 1; + updates.claimTokenHash = null; + updates.claimLeasedAt = null; + updates.claimLeaseExpiresAt = null; + updates.claimHolderAgentId = null; + updates.claimHolderUserId = null; + updates.claimHolderProfile = null; + } + } + if ( + statusChanging && + (nextStatus === "in_progress" || nextStatus === "done") + ) { + const pauseHold = await issueTreeControlService(db).getActivePauseHoldGate( + locked.companyId, + locked.id, + ); + if (pauseHold) { + throw conflict("Issue tree is currently paused", { + code: "issue_paused", + holdId: pauseHold.holdId, + rootIssueId: pauseHold.rootIssueId, + }); + } + } + if (nextStatus !== undefined) { + updates.status = nextStatus; + if (nextStatus === "in_progress" && !locked.startedAt) { + updates.startedAt = now; + } else if (nextStatus === "done" && !locked.completedAt) { + updates.completedAt = now; + } else if (nextStatus === "blocked") { + updates.blockedTransitionAt = now; + } else if (nextStatus === "cancelled" && !locked.cancelledAt) { + updates.cancelledAt = now; + } + } + if (nextPriority !== undefined) updates.priority = nextPriority; + if (nextScope !== undefined) updates.scope = nextScope; + if (nextResultSchemaRef !== undefined) { + updates.resultSchemaRef = nextResultSchemaRef; + } + if (nextProjectId !== undefined) { + updates.projectId = nextProjectId; + if (nextProjectId) { + const [projRow] = await tx + .select({ visibility: projects.visibility }) + .from(projects) + .where( + and( + eq(projects.id, nextProjectId), + eq(projects.companyId, locked.companyId), + ), + ) + .limit(1); + if (projRow?.visibility === "private") { + updates.visibility = "private"; + updates.privacyRootIssueId = locked.privacyRootIssueId ?? locked.id; + } + } + } + if (nextAssigneeAgentId !== undefined) { + updates.assigneeAgentId = nextAssigneeAgentId; + } + if (typeof b.title === "string" && b.title.trim()) { + updates.title = b.title.trim(); + } + if (b.description !== undefined) { + updates.description = + typeof b.description === "string" ? b.description : null; + } + + const previousKv = (locked.kvLabels ?? {}) as Record; + if (labelPatch !== undefined) { + updates.kvLabels = { ...previousKv, ...labelPatch }; + } + + const [saved] = await tx + .update(issues) + .set(updates) + .where(eq(issues.id, locked.id)) + .returning(); + + if (locked.channelId) { + await tx + .update(channels) + .set({ lastActivityAt: now, updatedAt: now }) + .where(eq(channels.id, locked.channelId)); + } + + await logActivity( + tx as unknown as Db, + { + companyId: locked.companyId, + actorType: actor.principalType === "agent" ? "agent" : "user", + actorId: + actor.principalType === "agent" + ? actor.agentId! + : (actor.userId ?? "local-board"), + agentId: actor.agentId, + issueId: locked.id, + responsibleUserIdOverride: actor.responsibleUserId, + action: "issue.updated", + entityType: "issue", + entityId: locked.id, + details: { + identifier: locked.identifier, + status: saved!.status, + previousStatus: locked.status, + }, + }, + publications, + ); + + let lastCursor: string | undefined; + const identifier = saved!.identifier ?? saved!.id; + + if (labelPatch !== undefined) { + const lblEvt = await appendBoardEvent(tx, { + companyId: locked.companyId, + type: "labels.changed", + channelId: locked.channelId, + channelPath, + issueId: locked.id, + identifier, + actor, + payload: { + previous: previousKv, + current: saved!.kvLabels, + }, + }); + committedEvents.push(lblEvt); + lastCursor = lblEvt.cursor; + } + + if (locked.status === "backlog" && saved!.status === "todo") { + const createdEvt = await appendBoardEvent(tx, { + companyId: locked.companyId, + type: "task.created", + channelId: locked.channelId, + channelPath, + issueId: locked.id, + identifier, + actor, + payload: { promotedFromBacklog: true }, + }); + committedEvents.push(createdEvt); + lastCursor = createdEvt.cursor; + + if (!saved!.assigneeAgentId && !saved!.assigneeUserId) { + const readiness = ( + await listIssueDependencyReadinessMap( + tx as unknown as Db, + locked.companyId, + [locked.id], + false, + ) + ).get(locked.id); + if (!readiness || readiness.isDependencyReady) { + const readyEvt = await appendBoardEvent(tx, { + companyId: locked.companyId, + type: "task.ready", + channelId: locked.channelId, + channelPath, + issueId: locked.id, + identifier, + actor, + payload: { promotedFromBacklog: true }, + }); + committedEvents.push(readyEvt); + lastCursor = readyEvt.cursor; + } + } + } + + return loadHeadlessIssueView(tx, saved!.id, lastCursor); + }); + + for (const pub of publications) { + publishActivity(pub); + } + for (const evt of committedEvents) { + publishCommittedBoardEvent(evt); + } + + res.json(updatedView); + }, + ); + + // Headless interceptor: GET /companies/:companyId/issues + router.get( + "/companies/:companyId/issues", + async (req: Request, res: Response, next: NextFunction) => { + 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("=")); + + if (!isHeadless) { + next(); + return; + } + + const companyId = req.params.companyId as string; + const actor = await resolveHeadlessActor(db, req, companyId, { + deploymentMode, + requiredAction: "read", + }); + + const channelParam = + typeof req.query.channel === "string" && req.query.channel.trim() + ? req.query.channel + : undefined; + const statusFilters = toStringArray(req.query.status); + const parsedLabelFilters = labelParams.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" }, + ); + } + }); + + const readyFilter = req.query.ready === "true"; + const rawLimit = + typeof req.query.limit === "string" + ? Number.parseInt(req.query.limit, 10) + : 50; + const limit = Number.isFinite(rawLimit) + ? Math.max(1, Math.min(200, rawLimit)) + : 50; + + // Resolve channel filter & accessible channels + let channelIdsFilter: string[] | null = null; + if (channelParam) { + const norm = normalizeChannelPathOrThrow(channelParam, { + allowSubtreePrefix: true, + }); + enforceHeadlessScopes(actor, { + action: "read", + channelPath: norm.path, + }); + const matchedChannels = await db + .select() + .from(channels) + .where( + and( + eq(channels.companyId, companyId), + isNull(channels.archivedAt), + norm.isSubtreePrefix + ? channelSubtreeCondition(norm.path) + : eq(channels.path, norm.path), + ), + ); + + if (!norm.isSubtreePrefix) { + const exact = matchedChannels[0]; + if (!exact) { + res.json({ + items: [], + cursor: await getLatestCompanyEventCursor(db, companyId), + }); + return; + } + await assertChannelAccess(db, exact, actor); + channelIdsFilter = [exact.id]; + } else { + const allowed: string[] = []; + for (const ch of matchedChannels) { + try { + enforceHeadlessScopes(actor, { channelPath: ch.path }); + } catch { + continue; + } + if (await canAccessChannel(db, ch, actor)) { + allowed.push(ch.id); + } + } + if (allowed.length === 0) { + res.json({ + items: [], + cursor: await getLatestCompanyEventCursor(db, companyId), + }); + return; + } + channelIdsFilter = allowed; + } + } + + // Resolve project filter + let projectIdFilter: string | null | undefined; + if (typeof req.query.project === "string" && req.query.project.trim()) { + projectIdFilter = await resolveProjectReference( + db, + companyId, + req.query.project, + req.actor, + ); + } + + // Resolve assignee filter + let assigneeFilterAgentId: string | null | undefined; + let assigneeProfileFilter: string | null = null; + if ( + typeof req.query.assignee === "string" && + req.query.assignee.trim() + ) { + const rawAssignee = req.query.assignee.trim(); + try { + assigneeFilterAgentId = await resolveAssigneeAgent(db, companyId, { + for: rawAssignee, + }); + } catch { + assigneeProfileFilter = rawAssignee.replace(/^@+/, "").toLowerCase(); + } + } + + const readCondition = await resolveHeadlessIssueReadCondition(db, req); + const conditions = [ + eq(issues.companyId, companyId), + isNull(issues.hiddenAt), + readCondition, + ]; + if (channelIdsFilter) { + conditions.push(inArray(issues.channelId, channelIdsFilter)); + } else { + const companyChannels = await db + .select() + .from(channels) + .where(and(eq(channels.companyId, companyId), isNull(channels.archivedAt))); + const inaccessibleChannelIds = await findInaccessibleChannelIds( + db, + companyId, + actor, + companyChannels, + ); + if (!allowsUnchanneledScope(actor)) { + conditions.push(isNotNull(issues.channelId)); + } + if (inaccessibleChannelIds.length > 0) { + conditions.push( + or( + isNull(issues.channelId), + notInArray(issues.channelId, inaccessibleChannelIds), + )!, + ); + } + } + if (statusFilters.length > 0) { + conditions.push(inArray(issues.status, statusFilters)); + } + if (readyFilter) { + conditions.push(eq(issues.status, "todo")); + } + if (explicitHeadless && statusFilters.length === 0 && !readyFilter) { + conditions.push( + sql`NOT (${issues.scope} = 'channel' AND ${issues.status} = 'backlog' AND ${issues.assigneeAgentId} IS NULL AND ${issues.assigneeUserId} IS NULL)`, + ); + } + if (projectIdFilter !== undefined && projectIdFilter !== null) { + conditions.push(eq(issues.projectId, projectIdFilter)); + } + if (assigneeFilterAgentId) { + conditions.push(eq(issues.assigneeAgentId, assigneeFilterAgentId)); + } + if (assigneeProfileFilter) { + conditions.push(sql`lower(${issues.createdByProfile}) = ${assigneeProfileFilter}`); + } + if (readyFilter) { + conditions.push(isNull(issues.assigneeAgentId)); + conditions.push(isNull(issues.assigneeUserId)); + conditions.push(isNull(issues.conversationAgentId)); + conditions.push(isNull(issues.claimTokenHash)); + conditions.push(isNull(issues.claimLeaseExpiresAt)); + conditions.push( + sql`NOT EXISTS ( + SELECT 1 + FROM ${issueRelations} ir + INNER JOIN ${issues} bi ON bi.id = ir.issue_id + WHERE ir.company_id = ${issues.companyId} + AND ir.related_issue_id = ${issues.id} + AND ir.type = 'blocks' + AND bi.status <> 'done' + )`, + ); + } + for (const expr of parsedLabelFilters) { + conditions.push(buildSqlIssueLabelFilterCondition(expr)); + } + + if (typeof req.query.after === "string" && req.query.after.trim()) { + const afterTrimmed = req.query.after.trim(); + const afterSeq = parseEventCursor(afterTrimmed); + if (afterSeq !== null) { + const eventRows = await db + .selectDistinct({ issueId: boardEvents.issueId }) + .from(boardEvents) + .where( + and( + eq(boardEvents.companyId, companyId), + gt(boardEvents.seq, afterSeq), + ), + ); + const matchingIds = eventRows + .map((r) => r.issueId) + .filter((id): id is string => Boolean(id)); + if (matchingIds.length === 0) { + res.json({ + items: [], + cursor: await getLatestCompanyEventCursor(db, companyId), + }); + return; + } + conditions.push(inArray(issues.id, matchingIds)); + } else if (isUuidLike(afterTrimmed)) { + const refIssue = await resolveIssueByIdOrIdentifier( + db, + afterTrimmed, + companyId, + ); + conditions.push(gt(issues.createdAt, refIssue.createdAt)); + } else { + const parsedDate = Date.parse(afterTrimmed); + if (!Number.isFinite(parsedDate)) { + throw badRequest(`Invalid 'after' cursor '${afterTrimmed}'`, { + error: "invalid_cursor", + code: "invalid_cursor", + }); + } + conditions.push(gt(issues.updatedAt, new Date(parsedDate))); + } + } + + const snapshotCursor = await getLatestCompanyEventCursor(db, companyId); + + const rawCandidateRows = await db + .select() + .from(issues) + .where(and(...conditions)) + .orderBy(desc(issues.createdAt), desc(issues.id)) + .limit(limit); + + let candidateRows = rawCandidateRows; + if (readyFilter && rawCandidateRows.length > 0) { + const readinessMap = await listIssueDependencyReadinessMap( + db, + companyId, + rawCandidateRows.map((row) => row.id), + false, + ); + candidateRows = rawCandidateRows.filter( + (row) => readinessMap.get(row.id)?.isDependencyReady !== false, + ); + } + + const items = await loadHeadlessIssueViews(db, candidateRows); + res.json({ items, cursor: snapshotCursor }); + }, + ); + + // Headless interceptor: GET /issues/:id + router.get( + "/issues/:id", + async (req: Request, res: Response, next: NextFunction) => { + const explicitThreadView = req.query.view === "thread"; + const isBrowserRequest = + Boolean(req.header("referer")) || Boolean(req.header("sec-fetch-mode")); + + let targetIssue: typeof issues.$inferSelect; + try { + targetIssue = await resolveIssueByIdOrIdentifier( + db, + req.params.id as string, + ); + } catch { + next(); + return; + } + + const isRestrictedBoardKey = isRestrictedBoardKeyRequest(req); + + if (!explicitThreadView && !isRestrictedBoardKey && targetIssue.channelId === null) { + next(); + return; + } + + const actor = await resolveHeadlessActor(db, req, targetIssue.companyId, { + deploymentMode, + requiredAction: "read", + }); + await assertCanonicalIssueAccess(db, req, targetIssue, "issue:read"); + await assertIssueChannelScopeAccess(db, targetIssue, actor); + + if (!explicitThreadView && isBrowserRequest) { + next(); + return; + } + + const [issueView, commentRows, interactionRows, latestCursor] = + await Promise.all([ + loadHeadlessIssueView(db, targetIssue.id), + db + .select() + .from(issueComments) + .where( + and( + eq(issueComments.issueId, targetIssue.id), + isNull(issueComments.deletedAt), + ), + ) + .orderBy(asc(issueComments.createdAt), asc(issueComments.id)), + db + .select() + .from(issueThreadInteractions) + .where(eq(issueThreadInteractions.issueId, targetIssue.id)) + .orderBy( + asc(issueThreadInteractions.createdAt), + asc(issueThreadInteractions.id), + ), + getLatestCompanyEventCursor(db, targetIssue.companyId), + ]); + + const identifier = issueView.identifier; + const detail: ThreadDetailView = { + kind: "thread", + issue: issueView, + comments: commentRows.map((c) => + serializeCommentView(c, identifier, issueView.cursor), + ), + interactions: interactionRows.map((i) => + mapInteractionRowToView(i, identifier, issueView.cursor), + ), + cursor: latestCursor, + }; + + res.json(detail); + }, + ); + + return router; +} diff --git a/server/src/routes/headless-identity.ts b/server/src/routes/headless-identity.ts new file mode 100644 index 00000000000..06e51f4d4fc --- /dev/null +++ b/server/src/routes/headless-identity.ts @@ -0,0 +1,68 @@ +import { Router } from "express"; +import { z } from "zod"; +import type { Db } from "@paperclipai/db"; +import { agentIdentityPolicySchema, type DeploymentMode } from "@paperclipai/shared"; +import { validate } from "../middleware/validate.js"; +import { headlessIdentityService } from "../services/headless-identity.js"; + +const connectAgentBodySchema = 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(), +}); + +const updateAgentIdentityPolicyBodySchema = z.object({ + agentIdentityPolicy: agentIdentityPolicySchema, +}); + +export function headlessIdentityRoutes( + db: Db, + opts: { deploymentMode?: DeploymentMode } = {}, +) { + const router = Router(); + const svc = headlessIdentityService(db, opts); + + router.get("/companies/resolve-default", async (req, res) => { + const companyQuery = + typeof req.query.company === "string" ? req.query.company : undefined; + const resolved = await svc.resolveDefaultCompany(req, companyQuery); + res.json(resolved); + }); + + router.get("/whoami", async (req, res) => { + const companyIdQuery = + typeof req.query.companyId === "string" + ? req.query.companyId + : typeof req.query.company === "string" + ? req.query.company + : undefined; + const info = await svc.whoami(req, companyIdQuery); + res.json(info); + }); + + router.post( + "/companies/:companyId/agents/connect", + validate(connectAgentBodySchema), + async (req, res) => { + const companyId = req.params.companyId as string; + const connected = await svc.connectAgent(req, companyId, req.body); + res.status(201).json(connected); + }, + ); + + router.patch( + "/companies/:companyId/agent-identity-policy", + validate(updateAgentIdentityPolicyBodySchema), + async (req, res) => { + const companyId = req.params.companyId as string; + const updated = await svc.updateAgentIdentityPolicy( + req, + companyId, + req.body.agentIdentityPolicy, + ); + res.json(updated); + }, + ); + + return router; +} diff --git a/server/src/routes/headless-queues-events.ts b/server/src/routes/headless-queues-events.ts new file mode 100644 index 00000000000..8eee3dc5cf9 --- /dev/null +++ b/server/src/routes/headless-queues-events.ts @@ -0,0 +1,599 @@ +import { Router, type Request, type Response } from "express"; +import { type Db } from "@paperclipai/db"; +import { + parseDurationMs, + type BoardEventType, + type BoardEventView, + type DeploymentMode, +} from "@paperclipai/shared"; +import { badRequest, notFound, unauthorized } from "../errors.js"; +import { heartbeatService } from "../services/heartbeat.js"; +import { + assertCanonicalIssueAccess, + assertIssueChannelScopeAccess, + resolveHeadlessActor, + resolveHeadlessIssueReadCondition, + resolveIssueByIdOrIdentifier, + subscribeCompanyBoardEvents, + type HeadlessActorContext, +} from "../services/headless-common.js"; +import { + claimTask, + completeTaskClaim, + failTaskClaim, + releaseTaskClaim, + renewTaskClaim, +} from "../services/headless-task-queue.js"; +import { + approveOnIssue, + cancelSchedule, + confirmOnIssue, + createSchedule, + eventMatchesFiltersAndAccess, + getCurrentCompanyMaxEventSeq, + listSchedules, + parseBoardEventFilters, + queryBoardEventsAfter, + rejectOnIssue, + askOnIssue, + waitForBoardEvent, + type BoardEventFilterInput, +} from "../services/headless-events-schedules-interactions.js"; + +function toCommaSplitStrings(value: unknown): string[] { + if (typeof value === "string") { + return value + .split(",") + .map((s) => s.trim()) + .filter(Boolean); + } + if (Array.isArray(value)) { + return value + .flatMap((v) => (typeof v === "string" ? v.split(",") : [])) + .map((s) => s.trim()) + .filter(Boolean); + } + return []; +} + +function toStringList(value: unknown): string[] { + if (typeof value === "string") { + const trimmed = value.trim(); + return trimmed ? [trimmed] : []; + } + if (Array.isArray(value)) { + return value + .filter((v): v is string => typeof v === "string") + .map((v) => v.trim()) + .filter(Boolean); + } + return []; +} + +function parseEventQuery( + req: Request, + fallbackAfter?: string, +): BoardEventFilterInput { + const channel = + typeof req.query.channel === "string" ? req.query.channel : undefined; + const issueId = + typeof req.query.issueId === "string" ? req.query.issueId : undefined; + const eventList = toCommaSplitStrings(req.query.event) as BoardEventType[]; + const labelList = toStringList(req.query.label); + const mentions = + typeof req.query.mentions === "string" ? req.query.mentions : undefined; + const schema = + typeof req.query.schema === "string" ? req.query.schema : undefined; + const after = + typeof req.query.after === "string" && req.query.after.trim() !== "" + ? req.query.after.trim() + : fallbackAfter?.trim() || undefined; + + return { + ...(channel ? { channel } : {}), + ...(issueId ? { issueId } : {}), + ...(eventList.length > 0 ? { event: eventList } : {}), + ...(labelList.length > 0 ? { label: labelList } : {}), + ...(mentions ? { mentions } : {}), + ...(schema ? { schema } : {}), + ...(after ? { after } : {}), + }; +} + +function parseOptionalTimeoutMs(req: Request): number | undefined { + if (typeof req.query.timeoutMs === "string" && req.query.timeoutMs.trim() !== "") { + const num = Number(req.query.timeoutMs); + if (!Number.isFinite(num) || num < 0) { + throw badRequest("Invalid timeoutMs query parameter"); + } + return Math.floor(num); + } + if (typeof req.query.timeout === "string" && req.query.timeout.trim() !== "") { + try { + return parseDurationMs(req.query.timeout); + } catch (err) { + throw badRequest( + err instanceof Error ? err.message : "Invalid timeout query parameter", + ); + } + } + return undefined; +} + +async function resolveIssueAndActor( + db: Db, + req: Request, + idOrIdentifier: string, + deploymentMode: DeploymentMode | undefined, + requiredAction: string, + canonicalAction: "issue:read" | "issue:comment" | "issue:mutate" = "issue:mutate", +): Promise<{ issue: Awaited>; actor: HeadlessActorContext }> { + if (!req.actor || req.actor.type === "none") { + throw unauthorized("Authentication required"); + } + + const expectedCompanyId = + req.actor.type === "agent" ? req.actor.companyId ?? undefined : undefined; + const issue = await resolveIssueByIdOrIdentifier( + db, + idOrIdentifier, + expectedCompanyId, + ); + + if ( + req.actor.type === "board" && + req.actor.source !== "local_implicit" && + !req.actor.isInstanceAdmin && + !(req.actor.companyIds ?? []).includes(issue.companyId) + ) { + throw notFound(`Issue '${idOrIdentifier}' not found`); + } + + const actor = await resolveHeadlessActor(db, req, issue.companyId, { + deploymentMode, + requiredAction, + }); + + await assertCanonicalIssueAccess(db, req, issue, canonicalAction); + await assertIssueChannelScopeAccess(db, issue, actor); + + return { issue, actor }; +} + +function formatSseFrame(ev: BoardEventView): string { + return `id: ${ev.cursor}\nevent: ${ev.type}\ndata: ${JSON.stringify(ev)}\n\n`; +} + +export function headlessQueuesEventsRoutes( + db: Db, + opts?: { + deploymentMode?: DeploymentMode; + heartbeat?: ReturnType; + }, +) { + const router = Router(); + const deploymentMode = opts?.deploymentMode; + const heartbeat = opts?.heartbeat ?? heartbeatService(db); + + const buildWakeHandler = () => async (wake: { + companyId: string; + issueId: string; + assigneeAgentId: string; + interactionId: string; + interactionKind: string; + interactionStatus: string; + sourceCommentId: string | null; + actor: HeadlessActorContext; + }) => { + await heartbeat.wakeup(wake.assigneeAgentId, { + source: "automation", + triggerDetail: "system", + reason: "issue_commented", + payload: { + issueId: wake.issueId, + interactionId: wake.interactionId, + interactionKind: wake.interactionKind, + interactionStatus: wake.interactionStatus, + sourceCommentId: wake.sourceCommentId, + mutation: "interaction", + }, + idempotencyKey: `interaction:${wake.interactionId}:${wake.interactionStatus}`, + requestedByActorType: wake.actor.principalType === "agent" ? "agent" : "user", + requestedByActorId: + wake.actor.principalType === "agent" + ? wake.actor.agentId ?? "unknown-agent" + : wake.actor.userId ?? "board", + contextSnapshot: { + issueId: wake.issueId, + taskId: wake.issueId, + interactionId: wake.interactionId, + interactionKind: wake.interactionKind, + interactionStatus: wake.interactionStatus, + wakeReason: "issue_commented", + }, + }); + }; + + router.post("/companies/:companyId/tasks/claim", async (req, res) => { + const companyId = req.params.companyId as string; + const actor = await resolveHeadlessActor(db, req, companyId, { + deploymentMode, + requiredAction: "tasks.claim", + }); + + const ac = new AbortController(); + const onClose = () => { + if (!res.writableFinished) { + ac.abort(); + } + }; + res.on("close", onClose); + + try { + const readCondition = await resolveHeadlessIssueReadCondition(db, req); + const claimed = await claimTask(db, companyId, actor, req.body, ac.signal, { + readCondition, + }); + if (res.writableFinished || ac.signal.aborted) return; + if (!claimed) { + res.status(204).end(); + return; + } + res.json(claimed); + } finally { + res.off("close", onClose); + } + }); + + router.post("/issues/:id/claim/renew", async (req, res) => { + const { issue, actor } = await resolveIssueAndActor( + db, + req, + req.params.id as string, + deploymentMode, + "tasks.claim_renew", + ); + const result = await renewTaskClaim( + db, + issue.id, + actor, + req.body, + req.header("x-paperclip-claim-token") ?? undefined, + ); + res.json(result); + }); + + router.post("/issues/:id/claim/release", async (req, res) => { + const { issue, actor } = await resolveIssueAndActor( + db, + req, + req.params.id as string, + deploymentMode, + "tasks.claim_release", + ); + const result = await releaseTaskClaim( + db, + issue.id, + actor, + req.body, + req.header("x-paperclip-claim-token") ?? undefined, + ); + res.json(result); + }); + + router.post("/issues/:id/claim/complete", async (req, res) => { + const { issue, actor } = await resolveIssueAndActor( + db, + req, + req.params.id as string, + deploymentMode, + "tasks.complete", + ); + const result = await completeTaskClaim( + db, + issue.id, + actor, + req.body, + req.header("x-paperclip-claim-token") ?? undefined, + ); + res.json(result); + }); + + router.post("/issues/:id/claim/fail", async (req, res) => { + const { issue, actor } = await resolveIssueAndActor( + db, + req, + req.params.id as string, + deploymentMode, + "tasks.fail", + ); + const result = await failTaskClaim( + db, + issue.id, + actor, + req.body, + req.header("x-paperclip-claim-token") ?? undefined, + ); + res.json(result); + }); + + router.post("/issues/:id/ask", async (req, res) => { + const { issue, actor } = await resolveIssueAndActor( + db, + req, + req.params.id as string, + deploymentMode, + "interactions.create", + ); + const result = await askOnIssue( + db, + issue.id, + actor, + req.body, + req.header("x-paperclip-claim-token") ?? undefined, + ); + res.json(result); + }); + + router.post("/issues/:id/confirm", async (req, res) => { + const { issue, actor } = await resolveIssueAndActor( + db, + req, + req.params.id as string, + deploymentMode, + "interactions.create", + ); + const result = await confirmOnIssue( + db, + issue.id, + actor, + req.body, + req.header("x-paperclip-claim-token") ?? undefined, + ); + res.json(result); + }); + + router.post("/issues/:id/approve", async (req, res) => { + const { issue, actor } = await resolveIssueAndActor( + db, + req, + req.params.id as string, + deploymentMode, + "interactions.resolve", + ); + const result = await approveOnIssue(db, issue.id, actor, req.body, { + onWakeAssignee: buildWakeHandler(), + }); + res.json(result); + }); + + router.post("/issues/:id/reject", async (req, res) => { + const { issue, actor } = await resolveIssueAndActor( + db, + req, + req.params.id as string, + deploymentMode, + "interactions.resolve", + ); + const result = await rejectOnIssue(db, issue.id, actor, req.body, { + onWakeAssignee: buildWakeHandler(), + }); + res.json(result); + }); + + router.post("/companies/:companyId/schedules", async (req, res) => { + const companyId = req.params.companyId as string; + const actor = await resolveHeadlessActor(db, req, companyId, { + deploymentMode, + requiredAction: "schedules.create", + }); + const schedule = await createSchedule(db, companyId, actor, req.body, { + authActor: req.actor, + }); + res.status(201).json(schedule); + }); + + router.get("/companies/:companyId/schedules", async (req, res) => { + const companyId = req.params.companyId as string; + const actor = await resolveHeadlessActor(db, req, companyId, { + deploymentMode, + requiredAction: "schedules.read", + }); + const target = + typeof req.query.target === "string" ? req.query.target : undefined; + const items = await listSchedules(db, companyId, actor, { target }, { + authActor: req.actor, + }); + res.json({ items }); + }); + + router.delete("/companies/:companyId/schedules/:id", async (req, res) => { + const companyId = req.params.companyId as string; + const actor = await resolveHeadlessActor(db, req, companyId, { + deploymentMode, + requiredAction: "schedules.cancel", + }); + const result = await cancelSchedule( + db, + companyId, + actor, + req.params.id as string, + { authActor: req.actor }, + ); + res.json(result); + }); + + router.get("/companies/:companyId/events/wait", async (req, res) => { + const companyId = req.params.companyId as string; + const actor = await resolveHeadlessActor(db, req, companyId, { + deploymentMode, + requiredAction: "events.read", + }); + const filters = parseEventQuery(req); + const timeoutMs = parseOptionalTimeoutMs(req); + + const ac = new AbortController(); + const onClose = () => { + if (!res.writableFinished) { + ac.abort(); + } + }; + res.on("close", onClose); + + try { + let resolvedCursor: string | undefined; + const event = await waitForBoardEvent(db, companyId, actor, filters, { + timeoutMs, + signal: ac.signal, + authActor: req.actor, + onResolvedCursor: (cursor) => { + resolvedCursor = cursor; + }, + }); + if (res.writableFinished || ac.signal.aborted) return; + if (!event) { + if (resolvedCursor) { + res.setHeader("X-Paperclip-Cursor", resolvedCursor); + } + res.status(204).end(); + return; + } + res.json(event); + } finally { + res.off("close", onClose); + } + }); + + router.get("/companies/:companyId/events/stream", async (req, res: Response) => { + const companyId = req.params.companyId as string; + const actor = await resolveHeadlessActor(db, req, companyId, { + deploymentMode, + requiredAction: "events.read", + }); + const filters = parseEventQuery( + req, + req.header("last-event-id") ?? undefined, + ); + const parsedFilters = parseBoardEventFilters(filters); + + res.status(200); + res.setHeader("Content-Type", "text/event-stream; charset=utf-8"); + res.setHeader("Cache-Control", "no-cache, no-transform"); + res.setHeader("Connection", "keep-alive"); + res.setHeader("X-Accel-Buffering", "no"); + res.flushHeaders?.(); + res.write(": connected\n\n"); + + let closed = false; + let replaying = true; + let lastSentSeq = parsedFilters.afterSeq; + const buffered: BoardEventView[] = []; + const issueLabelCache = new Map< + string, + { kvLabels: Record; tagLabels: string[] } + >(); + + // Serialize live filter checks and writes so SSE frames preserve order. + let writeChain = Promise.resolve(); + + const deliverEvent = async (ev: BoardEventView) => { + if (ev.type === "labels.changed" && ev.issueId) { + issueLabelCache.delete(ev.issueId); + } + if (closed || ev.seq <= lastSentSeq) return; + // Evaluate channel access fresh on live events so revoked channel membership applies immediately. + const matches = await eventMatchesFiltersAndAccess( + db, + companyId, + actor, + ev, + parsedFilters, + undefined, + issueLabelCache, + undefined, + req.actor, + ); + if (closed || !matches || ev.seq <= lastSentSeq) return; + lastSentSeq = ev.seq; + res.write(formatSseFrame(ev)); + }; + + const unsubscribe = subscribeCompanyBoardEvents(companyId, (ev) => { + if (closed) return; + if (ev.type === "labels.changed" && ev.issueId) { + issueLabelCache.delete(ev.issueId); + } + if (replaying) { + buffered.push(ev); + return; + } + writeChain = writeChain + .then(() => deliverEvent(ev)) + .catch(() => {}); + }); + + const keepaliveTimer = setInterval(() => { + if (!closed) { + res.write(": keepalive\n\n"); + } + }, 25_000); + keepaliveTimer.unref?.(); + + const cleanup = () => { + if (closed) return; + closed = true; + clearInterval(keepaliveTimer); + unsubscribe(); + res.off("close", cleanup); + }; + + res.on("close", cleanup); + + try { + if (parsedFilters.hasExplicitAfter) { + const replayPageSize = 500; + let replayCursorSeq = parsedFilters.afterSeq; + while (!closed) { + const missed = await queryBoardEventsAfter( + db, + companyId, + actor, + { + ...parsedFilters, + afterSeq: replayCursorSeq, + }, + { limit: replayPageSize, authActor: req.actor }, + ); + for (const ev of missed) { + if (closed) break; + replayCursorSeq = Math.max(replayCursorSeq, ev.seq); + if (ev.seq > lastSentSeq) { + lastSentSeq = ev.seq; + res.write(formatSseFrame(ev)); + } + } + if (missed.length < replayPageSize) break; + } + } else { + const maxSeq = await getCurrentCompanyMaxEventSeq(db, companyId); + parsedFilters.afterSeq = maxSeq; + lastSentSeq = maxSeq; + } + replaying = false; + + if (!closed && buffered.length > 0) { + buffered.sort((a, b) => a.seq - b.seq); + for (const ev of buffered) { + await deliverEvent(ev); + } + } + } catch { + cleanup(); + if (!res.writableEnded) { + res.end(); + } + } + }); + + return router; +} diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts index 6be661ea8c2..5cb0242735f 100644 --- a/server/src/routes/openapi.ts +++ b/server/src/routes/openapi.ts @@ -1656,6 +1656,9 @@ const BOARD_ONLY_OPERATIONS = new Set([ "POST /api/issues/{id}/tree-holds", "GET /api/issues/{id}/tree-holds/{holdId}", "POST /api/issues/{id}/tree-holds/{holdId}/release", + // Headless identity enrollment and policy configuration are board-only. + "POST /api/companies/{companyId}/agents/connect", + "PATCH /api/companies/{companyId}/agent-identity-policy", ]); const INSTANCE_ADMIN_OPERATIONS = new Set([ @@ -14451,3 +14454,52 @@ for (const [method, path, summary] of [ 404: r.notFound, 409: r.conflict, 422: r.unprocessable, }, }); + +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], +] as const) { + registerCurrentRoute({ + method, + path, + tags: [tag], + summary, + responses: { + [status]: r.ok(), + ...(path === "/api/companies/{companyId}/tasks/claim" || path === "/api/companies/{companyId}/events/wait" + ? { 204: { description: "No matching work or event before timeout" } } + : {}), + 400: r.badRequest, + 401: r.unauthorized, + 403: r.forbidden, + 404: r.notFound, + 409: r.conflict, + 422: r.unprocessable, + }, + }); +} diff --git a/server/src/services/agent-lifecycle.ts b/server/src/services/agent-lifecycle.ts index 8ff1075e0fc..f9e58c90f11 100644 --- a/server/src/services/agent-lifecycle.ts +++ b/server/src/services/agent-lifecycle.ts @@ -112,6 +112,13 @@ export function requestAgentHireInTransaction(tx: Db, publications: ActivityPubl return lifecycle.requestAgentHireInTransaction(tx, createAgentLifecycleEffects(), publications, ...args); } +export function createHeadlessAgentInTransaction( + tx: Db, + input: Parameters[2], +) { + return lifecycle.createHeadlessAgentInTransaction(tx, createAgentLifecycleEffects(), input); +} + function trackedDriver(driver: lifecycle.LifecycleDriver): lifecycle.LifecycleDriver { return { ...driver, runHost: agent => trackIdleWork(driver.runHost(agent)), runPlugin: (agent, pluginId) => trackIdleWork(driver.runPlugin(agent, pluginId)) }; diff --git a/server/src/services/authorization.ts b/server/src/services/authorization.ts index d8484ff41b9..047b792c271 100644 --- a/server/src/services/authorization.ts +++ b/server/src/services/authorization.ts @@ -12,6 +12,8 @@ import { approvals, issueApprovals, authUsers, + channelAccessMembers, + channels, companyMemberships, chatConversations, chatDeliveries, @@ -682,11 +684,26 @@ function issuePrivacyPrincipalCondition(actor: AuthorizationActor): SQL where p.id = n.project_id and p.company_id = n.company_id and p.visibility = 'private' and m.subject_type = ${principal.type} and m.subject_id = ${principal.id} )` : sql`false`; - // A standalone open task without a project has no restricted ancestor. + const issueChannelMember = principal ? sql`exists ( + select 1 from ${channels} ch + where ch.id = ${issues.channelId} and ch.company_id = ${issues.companyId} and ch.visibility = 'private' + and ( + ${principal.type === "agent" ? sql`ch.created_by_agent_id = ${principal.id}` : sql`ch.created_by_user_id = ${principal.id}`} + or exists ( + select 1 from ${channelAccessMembers} cm + where cm.channel_id = ch.id and cm.subject_type = ${principal.type} and cm.subject_id = ${principal.id} + ) + ) + )` : sql`false`; + const channelPrivacyGate = sql`(${issues.channelId} is null or not exists ( + select 1 from ${channels} ch + where ch.id = ${issues.channelId} and ch.company_id = ${issues.companyId} and ch.visibility = 'private' + ) or ${issueChannelMember})`; + // A standalone open task without a project or private channel has no restricted ancestor. // Keep the recursive predicate for every other shape, including inherited // privacy and delegated principals. This avoids one recursive walk per row // in large readable-child aggregates. - return sql`((${issues.visibility} = 'open' + return sql`(${channelPrivacyGate} and ((${issues.visibility} = 'open' and ${issues.privacyParentIssueId} is null and ${issues.projectId} is null) or exists ( with recursive privacy_ancestors as ( select p.id, p.company_id, p.privacy_parent_issue_id, p.visibility, p.project_id, @@ -708,13 +725,21 @@ function issuePrivacyPrincipalCondition(actor: AuthorizationActor): SQL ) select 1 from privacy_ancestors n where ${implicit} or ${grant} or ${projectMember} + or (n.id = ${issues.id} and ${issueChannelMember} + and not exists (select 1 from projects pp where pp.id = n.project_id and pp.company_id = n.company_id and pp.visibility = 'private') + and not exists ( + select 1 from privacy_ancestors restricted + left join projects private_project on private_project.id = restricted.project_id + and private_project.company_id = restricted.company_id + where restricted.id <> n.id and (restricted.visibility = 'private' or private_project.visibility = 'private') + )) or not exists ( select 1 from privacy_ancestors restricted left join projects private_project on private_project.id = restricted.project_id and private_project.company_id = restricted.company_id where restricted.visibility = 'private' or private_project.visibility = 'private' ) - ))`; + )))`; } function issuePrivacyCondition(actor: AuthorizationActor): SQL { diff --git a/server/src/services/board-auth.ts b/server/src/services/board-auth.ts index 8ee2ad93c4a..07fcacd19d3 100644 --- a/server/src/services/board-auth.ts +++ b/server/src/services/board-auth.ts @@ -1,8 +1,10 @@ import { createHash, randomBytes, timingSafeEqual } from "node:crypto"; -import { and, eq, gt, isNull, or, sql } from "drizzle-orm"; +import { and, asc, eq, gt, inArray, isNull, ne, or, sql } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { activityLog, + agentApiKeys, + agents, authUsers, boardApiKeys, cliAuthChallenges, @@ -10,8 +12,16 @@ import { companyMemberships, instanceUserRoles, } from "@paperclipai/db"; -import { conflict, forbidden, notFound } from "../errors.js"; +import { + AGENT_ROLES, + deriveAgentUrlKey, + type AgentRole, + type ClientScopes, +} from "@paperclipai/shared"; +import { badRequest, conflict, forbidden, notFound } from "../errors.js"; import { logActivity, publishActivity, type ActivityPublication } from "./activity-log.js"; +import { createHeadlessAgentInTransaction } from "./agent-lifecycle.js"; +import { authorizationService } from "./authorization.js"; import { logger } from "../middleware/logger.js"; export const BOARD_API_KEY_TTL_MS = 30 * 24 * 60 * 60 * 1000; @@ -35,10 +45,22 @@ export function createBoardApiToken() { return `pcp_board_${randomBytes(24).toString("hex")}`; } +export function createAgentApiToken() { + return `pcp_${randomBytes(24).toString("hex")}`; +} + export function createCliAuthSecret() { return `pcp_cli_auth_${randomBytes(24).toString("hex")}`; } +function normalizeAgentRole(rawRole?: string | null): AgentRole { + const candidate = rawRole?.trim().toLowerCase() ?? ""; + if ((AGENT_ROLES as readonly string[]).includes(candidate)) { + return candidate as AgentRole; + } + return "general"; +} + export function boardApiKeyExpiresAt(nowMs: number = Date.now()) { return new Date(nowMs + BOARD_API_KEY_TTL_MS); } @@ -50,7 +72,12 @@ export function cliAuthChallengeExpiresAt(nowMs: number = Date.now()) { function challengeStatusForRow(row: typeof cliAuthChallenges.$inferSelect): CliAuthChallengeStatus { if (row.cancelledAt) return "cancelled"; if (row.expiresAt.getTime() <= Date.now()) return "expired"; - if (row.approvedAt && row.boardApiKeyId) return "approved"; + if ( + row.approvedAt && + (row.challengeKind === "agent_key" ? Boolean(row.approvedAgentId) : Boolean(row.boardApiKeyId)) + ) { + return "approved"; + } return "pending"; } @@ -220,12 +247,18 @@ export function boardAuthService(db: Db) { userId: string; name: string; expiresAt?: Date | null; + companyId?: string | null; + lockedProfile?: string | null; + scopes?: ClientScopes | null; }) { const token = createBoardApiToken(); const created = await db .insert(boardApiKeys) .values({ userId: input.userId, + companyId: input.companyId ?? null, + lockedProfile: input.lockedProfile?.trim() || null, + scopes: input.scopes ?? null, name: input.name.trim(), keyHash: hashBearerToken(token), expiresAt: input.expiresAt === undefined ? boardApiKeyExpiresAt() : input.expiresAt, @@ -235,6 +268,9 @@ export function boardAuthService(db: Db) { return { id: created.id, + companyId: created.companyId, + lockedProfile: created.lockedProfile, + scopes: created.scopes, name: created.name, token, createdAt: created.createdAt, @@ -294,15 +330,29 @@ export function boardAuthService(db: Db) { clientName?: string | null; requestedAccess: "board" | "instance_admin_required"; requestedCompanyId?: string | null; + challengeKind?: "board" | "agent_key"; + agentName?: string | null; + agentRole?: string | null; }) { + const challengeKind = input.challengeKind === "agent_key" ? "agent_key" : "board"; + const requestedAgentName = input.agentName?.trim() || null; + if (challengeKind === "agent_key" && !requestedAgentName) { + throw badRequest("agentName is required when challengeKind is 'agent_key'"); + } + const requestedAgentRole = + challengeKind === "agent_key" ? input.agentRole?.trim() || "general" : null; + const challengeSecret = createCliAuthSecret(); - const pendingBoardToken = createBoardApiToken(); + const pendingBoardToken = + challengeKind === "agent_key" ? createAgentApiToken() : createBoardApiToken(); const expiresAt = cliAuthChallengeExpiresAt(); const labelBase = input.clientName?.trim() || "paperclipai cli"; const pendingKeyName = - input.requestedAccess === "instance_admin_required" - ? `${labelBase} (instance admin)` - : `${labelBase} (board)`; + challengeKind === "agent_key" + ? `${labelBase} (@${requestedAgentName})` + : input.requestedAccess === "instance_admin_required" + ? `${labelBase} (instance admin)` + : `${labelBase} (board)`; const created = await db .insert(cliAuthChallenges) @@ -311,6 +361,9 @@ export function boardAuthService(db: Db) { command: input.command.trim(), clientName: input.clientName?.trim() || null, requestedAccess: input.requestedAccess, + challengeKind, + requestedAgentName, + requestedAgentRole, requestedCompanyId: input.requestedCompanyId?.trim() || null, pendingKeyHash: hashBearerToken(pendingBoardToken), pendingKeyName, @@ -353,14 +406,24 @@ export function boardAuthService(db: Db) { .where(eq(companies.id, challenge.requestedCompanyId!)).then(rows => rows[0] ?? null) : null; + const status = challengeStatusForRow(challenge); return { id: challenge.id, - status: challengeStatusForRow(challenge), + status, command: challenge.command, clientName: challenge.clientName ?? null, requestedAccess: challenge.requestedAccess as "board" | "instance_admin_required", + challengeKind: (challenge.challengeKind ?? "board") as "board" | "agent_key", + requestedAgentName: challenge.requestedAgentName ?? null, + requestedAgentRole: challenge.requestedAgentRole ?? null, requestedCompanyId: challenge.requestedCompanyId ?? null, requestedCompanyName: company?.name ?? null, + ...(challenge.challengeKind === "agent_key" && status === "approved" + ? { + agentId: challenge.approvedAgentId ?? null, + companyId: challenge.requestedCompanyId ?? null, + } + : {}), approvedAt: challenge.approvedAt?.toISOString() ?? null, cancelledAt: challenge.cancelledAt?.toISOString() ?? null, expiresAt: challenge.expiresAt.toISOString(), @@ -406,6 +469,168 @@ export function boardAuthService(db: Db) { throw forbidden("Instance admin required"); } + if (challenge.challengeKind === "agent_key") { + const requestedName = challenge.requestedAgentName?.trim(); + if (!requestedName) { + throw badRequest("Agent name is missing on agent_key challenge"); + } + + let targetCompanyId = challenge.requestedCompanyId; + if (!targetCompanyId) { + const candidateCompanies = + access.companyIds.length > 0 + ? await tx + .select({ id: companies.id }) + .from(companies) + .where( + and( + inArray(companies.id, access.companyIds), + eq(companies.status, "active"), + ), + ) + .orderBy(asc(companies.createdAt)) + .limit(1) + : access.isInstanceAdmin + ? await tx + .select({ id: companies.id }) + .from(companies) + .where(eq(companies.status, "active")) + .orderBy(asc(companies.createdAt)) + .limit(1) + : []; + targetCompanyId = candidateCompanies[0]?.id ?? null; + } + if (!targetCompanyId) { + throw notFound("No accessible active company found for agent approval"); + } + + const [targetCompany] = await tx + .select({ + id: companies.id, + requireBoardApprovalForNewAgents: companies.requireBoardApprovalForNewAgents, + }) + .from(companies) + .where(eq(companies.id, targetCompanyId)) + .limit(1); + if (!targetCompany) { + throw notFound("Company not found"); + } + + const authActor = { + type: "board" as const, + userId, + isInstanceAdmin: access.isInstanceAdmin, + companyIds: access.companyIds, + memberships: access.memberships, + source: "session" as const, + }; + const authz = authorizationService(tx as unknown as Db); + const createDecision = await authz.decide({ + actor: authActor, + action: "agents:create", + resource: { type: "company", companyId: targetCompanyId }, + }); + if (!createDecision.allowed) { + throw forbidden( + createDecision.explanation ?? "Missing permission: agents:create", + { code: "forbidden", reason: createDecision.reason }, + ); + } + + const existingCompanyAgents = await tx + .select() + .from(agents) + .where( + and( + eq(agents.companyId, targetCompanyId), + ne(agents.status, "terminated"), + ), + ); + const lowerTarget = requestedName.toLowerCase(); + let agent = existingCompanyAgents.find( + (row) => + row.name.trim().toLowerCase() === lowerTarget || + deriveAgentUrlKey(row.name, row.id).toLowerCase() === lowerTarget, + ); + + if (agent) { + if (agent.status === "pending_approval") { + throw conflict( + "Agent is pending board approval and cannot receive an API key until approved.", + { code: "board_approval_required" }, + ); + } + const configureDecision = await authz.decide({ + actor: authActor, + action: "agent_config:update", + resource: { type: "agent", companyId: targetCompanyId, agentId: agent.id }, + }); + if (!configureDecision.allowed) { + throw forbidden( + configureDecision.explanation ?? + "Missing permission to manage the target agent", + { code: "forbidden", reason: configureDecision.reason }, + ); + } + } else { + if (targetCompany.requireBoardApprovalForNewAgents) { + throw conflict( + "Direct agent creation requires board approval. Use POST /api/companies/:companyId/agent-hires to create a pending hire approval.", + { code: "board_approval_required" }, + ); + } + agent = await createHeadlessAgentInTransaction(tx as unknown as Db, { + companyId: targetCompanyId, + name: requestedName, + role: normalizeAgentRole(challenge.requestedAgentRole), + createdByUserId: userId, + }); + } + + const [createdAgentKey] = await tx + .insert(agentApiKeys) + .values({ + agentId: agent.id, + companyId: targetCompanyId, + name: challenge.pendingKeyName, + keyHash: challenge.pendingKeyHash, + responsibleUserId: userId, + }) + .returning(); + + const approvedAt = challenge.approvedAt ?? new Date(); + const updated = await tx + .update(cliAuthChallenges) + .set({ + approvedByUserId: userId, + approvedAgentId: agent.id, + requestedCompanyId: targetCompanyId, + approvedAt, + updatedAt: new Date(), + }) + .where(eq(cliAuthChallenges.id, challenge.id)) + .returning() + .then((rows) => rows[0] ?? challenge); + + await logActivity(tx as unknown as Db, { + companyId: targetCompanyId, + actorType: "user", + actorId: userId, + action: "agent_api_key.created", + entityType: "agent", + entityId: agent.id, + details: { + agentId: agent.id, + agentName: agent.name, + agentApiKeyId: createdAgentKey.id, + name: createdAgentKey.name, + challengeId: updated.id, + }, + }, publications); + + return { status: "approved" as const, challenge: updated, created: true }; + } + let boardKeyId = challenge.boardApiKeyId; if (!boardKeyId) { const createdKey = await tx diff --git a/server/src/services/delivery-work-notifications.ts b/server/src/services/delivery-work-notifications.ts index f9c748fdf2b..f5b379fc736 100644 --- a/server/src/services/delivery-work-notifications.ts +++ b/server/src/services/delivery-work-notifications.ts @@ -165,6 +165,8 @@ export const DELIVERY_QUEUES = { caseHandoffs: "case-handoffs", nativeHarnessBackupExpiration: "native-harness-backup-expiration", nativeCheckpointExpiration: "native-checkpoint-expiration", + claimLeaseExpiry: "claim-lease-expiry", + scheduledBoardPosts: "scheduled-board-posts", } as const; export type DeliveryQueue = typeof DELIVERY_QUEUES[keyof typeof DELIVERY_QUEUES]; diff --git a/server/src/services/headless-channels.ts b/server/src/services/headless-channels.ts new file mode 100644 index 00000000000..565a1c95991 --- /dev/null +++ b/server/src/services/headless-channels.ts @@ -0,0 +1,1363 @@ +import { createHash, randomUUID } from "node:crypto"; +import { + and, + asc, + desc, + eq, + gt, + inArray, + isNull, + like, + ne, + or, + sql, + type SQL, +} from "drizzle-orm"; +import { z } from "zod"; +import type { Db } from "@paperclipai/db"; +import { + agents, + boardEvents, + channelAccessMembers, + channels, + companies, + companyMemberships, + issueComments, + issueLabels, + issues, + labels, + projects, +} from "@paperclipai/db"; +import { + channelQueueConfigSchema, + CHANNEL_VISIBILITIES, + deriveAgentUrlKey, + ISSUE_PRIORITIES, + isUuidLike, + matchesLabelFilter, + normalizeChannelPath, + parseEventCursor, + parseLabelFilterExpr, + parseSchemaRef, + SCHEMA_REF_REGEX, + schemaBlockSchema, + splitMessageIntoTitleAndDescription, + writableKvLabelsRecordSchema, + type BoardEventView, + type ChannelPage, + type ChannelQueueConfig, + type ChannelView, + type ChannelVisibility, + type CommentView, + type CreateChannelInput, + type HeadlessIssueView, + type IssuePriority, + type IssueScope, + type IssueStatus, + type SchemaBlock, +} from "@paperclipai/shared"; +import { badRequest, conflict, forbidden, notFound } from "../errors.js"; +import { + logActivity, + publishActivity, + type ActivityPublication, +} from "./activity-log.js"; +import { + appendBoardEvent, + assertChannelAccess, + assertProjectReadAccess, + buildSqlIssueLabelFilterCondition, + canAccessChannel, + channelDescendantsCondition, + channelSubtreeCondition, + enforceHeadlessScopes, + getLatestCompanyEventCursor, + loadHeadlessIssueView, + loadHeadlessIssueViews, + publishCommittedBoardEvent, + resolveIssueByIdOrIdentifier, + resolveProjectReference, + serializeCommentView, + type DbOrTx, + type HeadlessActorContext, +} from "./headless-common.js"; +import { + assertSchemaExists, + formatBlocksAsFencedJson, + validateSchemaBlocks, +} from "./headless-schemas.js"; +import { listIssueDependencyReadinessMap } from "./issues.js"; + +const DEFAULT_TAG_LABEL_COLOR = "#64748b"; + +function isChannelAllowedByScopes( + actor: Pick, + channelPath: string, +): boolean { + try { + enforceHeadlessScopes(actor, { channelPath }); + return true; + } catch { + return false; + } +} + +export function normalizeChannelPathOrThrow( + rawPath: string, + opts?: { allowSubtreePrefix?: boolean }, +) { + try { + return normalizeChannelPath(rawPath, opts); + } catch (err) { + throw badRequest( + err instanceof Error ? err.message : `Invalid channel path "${rawPath}"`, + { + error: "invalid_channel_path", + code: "invalid_channel_path", + }, + ); + } +} + +export function validateWritableKvLabelsOrThrow( + rawLabels: Record, +): Record { + for (const key of Object.keys(rawLabels)) { + if (key.startsWith("paperclip.")) { + throw badRequest( + "Label keys starting with 'paperclip.' are reserved", + { + error: "reserved_label", + code: "reserved_label", + key, + }, + ); + } + } + const parsed = writableKvLabelsRecordSchema.safeParse(rawLabels); + if (!parsed.success) { + throw badRequest( + parsed.error.issues + .map((issue) => `${issue.path.join(".") || "$"}: ${issue.message}`) + .join("; "), + { + error: "validation_error", + code: "validation_error", + issues: parsed.error.issues, + }, + ); + } + return parsed.data; +} + +export async function resolveAssigneeAgent( + dbOrTx: DbOrTx, + companyId: string, + opts: { assigneeAgentId?: string | null; for?: string }, +): Promise { + if (opts.assigneeAgentId !== undefined) { + if (opts.assigneeAgentId === null) return null; + const [agent] = await dbOrTx + .select({ id: agents.id }) + .from(agents) + .where( + and( + eq(agents.id, opts.assigneeAgentId), + eq(agents.companyId, companyId), + ne(agents.status, "terminated"), + ), + ) + .limit(1); + if (!agent) { + throw notFound(`Agent '${opts.assigneeAgentId}' not found`, { + error: "agent_not_found", + code: "agent_not_found", + }); + } + return agent.id; + } + + if (opts.for !== undefined && opts.for.trim().length > 0) { + const target = opts.for.trim().replace(/^@+/, "").toLowerCase(); + if (isUuidLike(target)) { + const [agent] = await dbOrTx + .select({ id: agents.id }) + .from(agents) + .where( + and( + eq(agents.id, target), + eq(agents.companyId, companyId), + ne(agents.status, "terminated"), + ), + ) + .limit(1); + if (!agent) { + throw notFound(`Agent '@${target}' not found`, { + error: "agent_not_found", + code: "agent_not_found", + }); + } + return agent.id; + } + + const companyAgents = await dbOrTx + .select({ id: agents.id, name: agents.name }) + .from(agents) + .where(and(eq(agents.companyId, companyId), ne(agents.status, "terminated"))); + + const match = companyAgents.find( + (a) => + a.name.trim().toLowerCase() === target || + deriveAgentUrlKey(a.name, a.id).toLowerCase() === target, + ); + if (!match) { + throw notFound(`Agent '@${target}' not found`, { + error: "agent_not_found", + code: "agent_not_found", + }); + } + return match.id; + } + + return null; +} + +export async function attachTagLabels( + tx: DbOrTx, + companyId: string, + issueId: string, + tagNames: string[], +): Promise { + const uniqueNames = Array.from( + new Set(tagNames.map((t) => t.trim()).filter((t) => t.length > 0)), + ); + if (uniqueNames.length === 0) return; + + await tx + .insert(labels) + .values( + uniqueNames.map((name) => ({ + companyId, + name, + color: DEFAULT_TAG_LABEL_COLOR, + })), + ) + .onConflictDoNothing({ + target: [labels.companyId, labels.name], + }); + + const labelRows = await tx + .select({ id: labels.id }) + .from(labels) + .where(and(eq(labels.companyId, companyId), inArray(labels.name, uniqueNames))); + + if (labelRows.length === 0) return; + + await tx + .insert(issueLabels) + .values( + labelRows.map((l) => ({ + issueId, + labelId: l.id, + companyId, + })), + ) + .onConflictDoNothing({ + target: [issueLabels.issueId, issueLabels.labelId], + }); +} + +async function addChannelCreatorMembership( + dbOrTx: DbOrTx, + companyId: string, + channelId: string, + actor: HeadlessActorContext, +): Promise { + const member = actor.agentId + ? { subjectType: "agent", subjectId: actor.agentId } + : actor.userId + ? { subjectType: "user", subjectId: actor.userId } + : null; + + if (!member) return; + + await dbOrTx + .insert(channelAccessMembers) + .values({ + companyId, + channelId, + subjectType: member.subjectType, + subjectId: member.subjectId, + }) + .onConflictDoNothing({ + target: [ + channelAccessMembers.channelId, + channelAccessMembers.subjectType, + channelAccessMembers.subjectId, + ], + }); +} + +export interface EnsureChannelInput { + path: string; + description?: string | null; + visibility?: ChannelVisibility; + defaultProjectId?: string | null; + queueConfig?: ChannelQueueConfig; +} + +export async function ensureChannel( + dbOrTx: DbOrTx, + companyId: string, + actor: HeadlessActorContext, + input: EnsureChannelInput | CreateChannelInput, + opts: { allowUpdateExisting?: boolean; publications?: ActivityPublication[] } = {}, +): Promise { + const normalized = normalizeChannelPathOrThrow(input.path, { + allowSubtreePrefix: false, + }); + enforceHeadlessScopes(actor, { channelPath: normalized.path }); + + let resolvedDefaultProjectId: string | null | undefined; + if (input.defaultProjectId !== undefined) { + resolvedDefaultProjectId = + input.defaultProjectId === null + ? null + : await resolveProjectReference(dbOrTx, companyId, input.defaultProjectId, actor); + } + + let validatedQueueConfig: ChannelQueueConfig | undefined; + if (input.queueConfig !== undefined) { + const parsedQc = channelQueueConfigSchema.safeParse(input.queueConfig); + if (!parsedQc.success) { + throw badRequest( + parsedQc.error.issues + .map((i) => `${i.path.join(".") || "$"}: ${i.message}`) + .join("; "), + { + error: "validation_error", + code: "validation_error", + issues: parsedQc.error.issues, + }, + ); + } + validatedQueueConfig = parsedQc.data; + } + + let visibility: ChannelVisibility | undefined = input.visibility; + if (visibility !== undefined && !CHANNEL_VISIBILITIES.includes(visibility)) { + throw badRequest(`Invalid channel visibility '${visibility}'`, { + error: "validation_error", + code: "validation_error", + }); + } + + // 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", { + code: "private_ancestor_required", + }); + } + visibility = "private"; + } + + const now = new Date(); + const [inserted] = await dbOrTx + .insert(channels) + .values({ + companyId, + path: normalized.path, + description: input.description ?? null, + visibility: visibility ?? "open", + defaultProjectId: resolvedDefaultProjectId ?? null, + queueConfig: validatedQueueConfig ?? {}, + createdByAgentId: actor.agentId, + createdByUserId: actor.agentId ? null : actor.userId, + createdByProfile: actor.actorProfile, + lastActivityAt: now, + createdAt: now, + updatedAt: now, + }) + .onConflictDoNothing({ + target: [channels.companyId, channels.path], + }) + .returning(); + + if (inserted) { + if (inserted.visibility === "private") { + await addChannelCreatorMembership(dbOrTx, companyId, inserted.id, actor); + } + if (opts.publications) { + await logActivity( + dbOrTx as unknown as Db, + { + companyId, + actorType: actor.principalType === "agent" ? "agent" : "user", + actorId: + actor.principalType === "agent" + ? actor.agentId! + : (actor.userId ?? "local-board"), + agentId: actor.agentId, + responsibleUserIdOverride: actor.responsibleUserId, + action: "channel.created", + entityType: "channel", + entityId: inserted.id, + details: { + path: inserted.path, + visibility: inserted.visibility, + }, + }, + opts.publications, + ); + } + return inserted; + } + + const [existing] = await dbOrTx + .select() + .from(channels) + .where(and(eq(channels.companyId, companyId), eq(channels.path, normalized.path))) + .limit(1); + + if (!existing) { + throw notFound(`Channel '${normalized.path}' not found`); + } + + if (existing.visibility === "private") { + await assertChannelAccess(dbOrTx, existing, actor); + } + + if (!opts.allowUpdateExisting) { + return existing; + } + + const updates: Partial = {}; + if (input.description !== undefined && input.description !== existing.description) { + updates.description = input.description; + } + if (input.visibility !== undefined && input.visibility !== existing.visibility) { + updates.visibility = input.visibility; + } + if ( + resolvedDefaultProjectId !== undefined && + resolvedDefaultProjectId !== existing.defaultProjectId + ) { + updates.defaultProjectId = resolvedDefaultProjectId; + } + if ( + validatedQueueConfig !== undefined && + JSON.stringify(validatedQueueConfig) !== JSON.stringify(existing.queueConfig ?? {}) + ) { + updates.queueConfig = validatedQueueConfig; + } + + if (Object.keys(updates).length > 0) { + enforceHeadlessScopes(actor, { + action: "channels.manage", + channelPath: existing.path, + }); + const isOwnerOrCreator = + actor.isInstanceAdmin || + actor.principalType === "local_trusted" || + (Boolean(actor.userId) && existing.createdByUserId === actor.userId) || + (Boolean(actor.agentId) && existing.createdByAgentId === actor.agentId); + let canManage = isOwnerOrCreator; + if (!canManage && actor.userId && actor.principalType === "user") { + const [membership] = await dbOrTx + .select({ role: companyMemberships.membershipRole }) + .from(companyMemberships) + .where( + and( + eq(companyMemberships.companyId, companyId), + eq(companyMemberships.principalType, "user"), + eq(companyMemberships.principalId, actor.userId), + eq(companyMemberships.status, "active"), + inArray(companyMemberships.membershipRole, ["owner", "admin"]), + ), + ) + .limit(1); + canManage = Boolean(membership); + } + if (!canManage) { + throw forbidden("Only the channel creator or a company admin can update channel settings"); + } + + updates.updatedAt = new Date(); + const privatizingTree = + updates.visibility === "private" && existing.visibility !== "private"; + + let childChannels: Array<{ id: string; visibility: string }> = []; + let affectedChannelIds: string[] = []; + if (privatizingTree) { + childChannels = await dbOrTx + .select({ id: channels.id, visibility: channels.visibility }) + .from(channels) + .where( + and( + eq(channels.companyId, companyId), + isNull(channels.archivedAt), + channelDescendantsCondition(existing.path), + ), + ); + affectedChannelIds = [existing.id, ...childChannels.map((c) => c.id)].sort(); + + // Lock issues BEFORE locking channels so all transactions share issues -> channels -> board_events lock order. + await dbOrTx.execute( + sql`SELECT id FROM issues WHERE company_id = ${companyId} AND channel_id IN (${sql.join( + affectedChannelIds.map((id) => sql`${id}`), + sql`, `, + )}) AND visibility <> 'private' ORDER BY id FOR UPDATE`, + ); + await dbOrTx.execute( + sql`SELECT id FROM channels WHERE company_id = ${companyId} AND id IN (${sql.join( + affectedChannelIds.map((id) => sql`${id}`), + sql`, `, + )}) ORDER BY id FOR UPDATE`, + ); + } + + const [updated] = await dbOrTx + .update(channels) + .set(updates) + .where(eq(channels.id, existing.id)) + .returning(); + if (updated?.visibility === "private" && existing.visibility !== "private") { + await addChannelCreatorMembership(dbOrTx, companyId, updated.id, actor); + const newlyPrivatizedChildIds = childChannels + .filter((c) => c.visibility !== "private") + .map((c) => c.id) + .sort(); + if (newlyPrivatizedChildIds.length > 0) { + await dbOrTx + .update(channels) + .set({ visibility: "private", updatedAt: updates.updatedAt }) + .where(inArray(channels.id, newlyPrivatizedChildIds)); + for (const childId of newlyPrivatizedChildIds) { + await addChannelCreatorMembership(dbOrTx, companyId, childId, actor); + } + } + await dbOrTx + .update(issues) + .set({ + visibility: "private", + privacyRootIssueId: sql`coalesce(${issues.privacyRootIssueId}, ${issues.id})`, + updatedAt: updates.updatedAt, + }) + .where( + and( + eq(issues.companyId, companyId), + inArray(issues.channelId, affectedChannelIds), + ne(issues.visibility, "private"), + ), + ); + } + if (updated && opts.publications) { + await logActivity( + dbOrTx as unknown as Db, + { + companyId, + actorType: actor.principalType === "agent" ? "agent" : "user", + actorId: + actor.principalType === "agent" + ? actor.agentId! + : (actor.userId ?? "local-board"), + agentId: actor.agentId, + responsibleUserIdOverride: actor.responsibleUserId, + action: "channel.updated", + entityType: "channel", + entityId: updated.id, + details: { + path: updated.path, + visibility: updated.visibility, + }, + }, + opts.publications, + ); + } + return updated ?? existing; + } + + return existing; +} + +export async function buildChannelViews( + dbOrTx: DbOrTx, + companyId: string, + channelRows: Array, +): Promise { + if (channelRows.length === 0) return []; + + const channelIds = channelRows.map((c) => c.id); + const channelIssues = await dbOrTx + .select({ + id: issues.id, + channelId: issues.channelId, + status: issues.status, + assigneeAgentId: issues.assigneeAgentId, + assigneeUserId: issues.assigneeUserId, + conversationAgentId: issues.conversationAgentId, + }) + .from(issues) + .where( + and( + eq(issues.companyId, companyId), + inArray(issues.channelId, channelIds), + isNull(issues.hiddenAt), + ), + ); + + const candidateReadyIds = channelIssues + .filter( + (i) => + i.status === "todo" && + !i.assigneeAgentId && + !i.assigneeUserId && + !i.conversationAgentId, + ) + .map((i) => i.id); + + const blockedIssueIds = new Set(); + if (candidateReadyIds.length > 0) { + const readinessMap = await listIssueDependencyReadinessMap( + dbOrTx as unknown as Db, + companyId, + candidateReadyIds, + false, + ); + for (const [issueId, readiness] of readinessMap) { + if (!readiness.isDependencyReady) { + blockedIssueIds.add(issueId); + } + } + } + + const counts = new Map< + string, + { threadCount: number; openTaskCount: number; readyTaskCount: number } + >(); + for (const chId of channelIds) { + counts.set(chId, { threadCount: 0, openTaskCount: 0, readyTaskCount: 0 }); + } + + for (const row of channelIssues) { + if (!row.channelId) continue; + const c = counts.get(row.channelId); + if (!c) continue; + c.threadCount += 1; + if ( + row.status === "todo" || + row.status === "in_progress" || + row.status === "in_review" || + row.status === "blocked" + ) { + c.openTaskCount += 1; + } + if ( + row.status === "todo" && + !row.assigneeAgentId && + !row.assigneeUserId && + !row.conversationAgentId && + !blockedIssueIds.has(row.id) + ) { + c.readyTaskCount += 1; + } + } + + return channelRows.map((ch) => { + const c = counts.get(ch.id) ?? { + threadCount: 0, + openTaskCount: 0, + readyTaskCount: 0, + }; + return { + id: ch.id, + companyId: ch.companyId, + path: ch.path, + description: ch.description ?? null, + visibility: ch.visibility, + defaultProjectId: ch.defaultProjectId ?? null, + queueConfig: (ch.queueConfig ?? {}) as ChannelQueueConfig, + threadCount: c.threadCount, + openTaskCount: c.openTaskCount, + readyTaskCount: c.readyTaskCount, + lastActivityAt: ch.lastActivityAt.toISOString(), + createdAt: ch.createdAt.toISOString(), + updatedAt: ch.updatedAt.toISOString(), + }; + }); +} + +export async function listChannels( + db: Db, + companyId: string, + actor: HeadlessActorContext, + prefix?: string, +): Promise { + enforceHeadlessScopes(actor, { action: "read" }); + + const conditions = [ + eq(channels.companyId, companyId), + isNull(channels.archivedAt), + ]; + + if (prefix && prefix.trim().length > 0) { + const norm = normalizeChannelPathOrThrow(prefix, { + allowSubtreePrefix: true, + }); + conditions.push(channelSubtreeCondition(norm.path)); + } + + const rows = await db + .select() + .from(channels) + .where(and(...conditions)) + .orderBy(asc(channels.path)); + + const visibleRows: Array = []; + for (const row of rows) { + if (!isChannelAllowedByScopes(actor, row.path)) continue; + if (!(await canAccessChannel(db, row, actor))) continue; + visibleRows.push(row); + } + + return buildChannelViews(db, companyId, visibleRows); +} + +const createChannelPostInputSchema = z + .object({ + channel: z.string().min(1), + 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(), + labels: z.record(z.string(), z.string()).optional(), + kvLabels: z.record(z.string(), z.string()).optional(), + tagLabels: z.array(z.string().min(1).max(64)).optional(), + blocks: z.array(schemaBlockSchema).optional(), + schema: z + .object({ + ref: z.string().refine((v) => SCHEMA_REF_REGEX.test(v.trim()), { + message: "Invalid schema ref", + }), + data: z.record(z.string(), z.unknown()), + }) + .strict() + .optional(), + priority: z.enum(ISSUE_PRIORITIES).optional(), + projectId: z.string().min(1).nullable().optional(), + board: z.boolean().optional(), + title: z.string().max(240).optional(), + text: z.string().optional(), + description: z.string().nullable().optional(), + idempotencyKey: z.string().min(1).max(255).optional(), + sourceTrust: z.string().min(1).max(64).optional(), + }) + .passthrough(); + +export async function createChannelPost( + db: Db, + companyId: string, + actor: HeadlessActorContext, + rawBody: unknown, +): Promise<{ issue: HeadlessIssueView; created: boolean }> { + const parsedBody = createChannelPostInputSchema.safeParse(rawBody); + if (!parsedBody.success) { + throw badRequest( + parsedBody.error.issues + .map((i) => `${i.path.join(".") || "$"}: ${i.message}`) + .join("; "), + { + error: "validation_error", + code: "validation_error", + issues: parsedBody.error.issues, + }, + ); + } + + const input = parsedBody.data; + const normalizedChannel = normalizeChannelPathOrThrow(input.channel, { + allowSubtreePrefix: false, + }); + const requestedStatus: IssueStatus = input.status ?? "backlog"; + const requiredAction = requestedStatus === "todo" ? "tasks.create" : "post"; + enforceHeadlessScopes(actor, { + action: requiredAction, + channelPath: normalizedChannel.path, + }); + + const mergedKvLabels = validateWritableKvLabelsOrThrow({ + ...(input.labels ?? {}), + ...(input.kvLabels ?? {}), + }); + + const combinedBlocks: SchemaBlock[] = [...(input.blocks ?? [])]; + if (input.schema) { + const parsedRef = parseSchemaRef(input.schema.ref); + combinedBlocks.push({ + schema: parsedRef.name, + version: parsedRef.version, + data: input.schema.data, + }); + } + const validatedBlocks = await validateSchemaBlocks(db, companyId, combinedBlocks); + + const resolvedResultSchemaRef = input.resultSchema + ? await assertSchemaExists(db, companyId, input.resultSchema) + : null; + + const originId = input.idempotencyKey + ? `headless:${input.idempotencyKey}` + : null; + + let resolvedTitle: string; + let resolvedDescription: string | null; + const trimmedTitle = input.title?.trim(); + if (trimmedTitle) { + resolvedTitle = trimmedTitle; + if (input.description !== undefined) { + resolvedDescription = input.description; + } else if (input.text !== undefined) { + resolvedDescription = input.text.trim() ? input.text : null; + } else if (validatedBlocks.length > 0) { + resolvedDescription = formatBlocksAsFencedJson(validatedBlocks); + } else { + resolvedDescription = null; + } + } else if ( + (input.text && input.text.trim().length > 0) || + (input.description && input.description.trim().length > 0) + ) { + const rawText = input.text ?? input.description ?? ""; + const split = splitMessageIntoTitleAndDescription(rawText); + resolvedTitle = split.title; + resolvedDescription = split.description; + } else if (validatedBlocks.length > 0) { + resolvedTitle = `[${validatedBlocks[0]!.schema}@${validatedBlocks[0]!.version}]`; + resolvedDescription = formatBlocksAsFencedJson(validatedBlocks); + } else { + throw badRequest("Post requires title, text, description, or blocks", { + error: "validation_error", + code: "validation_error", + }); + } + + const requestHash = originId + ? createHash("sha256") + .update( + JSON.stringify({ + channel: normalizedChannel.path, + status: requestedStatus, + title: resolvedTitle, + description: resolvedDescription, + projectId: input.projectId ?? null, + board: Boolean(input.board), + priority: input.priority ?? "medium", + for: input.for ?? null, + assigneeAgentId: input.assigneeAgentId ?? null, + kvLabels: mergedKvLabels, + tagLabels: input.tagLabels ?? [], + blocks: validatedBlocks, + resultSchema: resolvedResultSchemaRef, + }), + ) + .digest("hex") + : null; + + if (originId) { + const [existing] = await db + .select() + .from(issues) + .where( + and( + eq(issues.companyId, companyId), + eq(issues.originKind, "manual"), + eq(issues.originId, originId), + ), + ) + .limit(1); + if (existing) { + if (existing.channelId) { + const [ch] = await db + .select() + .from(channels) + .where(eq(channels.id, existing.channelId)) + .limit(1); + if (ch) await assertChannelAccess(db, ch, actor); + } + if (existing.originFingerprint && existing.originFingerprint !== requestHash) { + throw conflict( + "Idempotency key has already been used for a different payload", + { + error: "idempotency_conflict", + code: "idempotency_conflict", + }, + ); + } + const view = await loadHeadlessIssueView(db, existing.id); + return { issue: view, created: false }; + } + } + + const publications: ActivityPublication[] = []; + const committedEvents: BoardEventView[] = []; + + const txResult = await db.transaction(async (tx) => { + if (originId) { + await tx.execute( + sql`select pg_advisory_xact_lock(hashtext(${companyId}), hashtext(${"post:" + originId}))`, + ); + const [existingInTx] = await tx + .select() + .from(issues) + .where( + and( + eq(issues.companyId, companyId), + eq(issues.originKind, "manual"), + eq(issues.originId, originId), + ), + ) + .limit(1); + if (existingInTx) { + if (existingInTx.channelId) { + const [ch] = await tx + .select() + .from(channels) + .where(eq(channels.id, existingInTx.channelId)) + .limit(1); + if (ch) await assertChannelAccess(tx, ch, actor); + } + if ( + existingInTx.originFingerprint && + existingInTx.originFingerprint !== requestHash + ) { + throw conflict( + "Idempotency key has already been used for a different payload", + { + error: "idempotency_conflict", + code: "idempotency_conflict", + }, + ); + } + const view = await loadHeadlessIssueView(tx, existingInTx.id); + return { issue: view, created: false }; + } + } + + const channel = await ensureChannel(tx, companyId, actor, { + path: normalizedChannel.path, + }); + const now = new Date(); + + let projectId: string | null = channel.defaultProjectId ?? null; + if (input.projectId !== undefined) { + projectId = + input.projectId === null + ? null + : await resolveProjectReference(tx, companyId, input.projectId, actor); + } else if (projectId) { + await assertProjectReadAccess(tx, companyId, projectId, actor); + } + + const assigneeAgentId = await resolveAssigneeAgent(tx, companyId, { + assigneeAgentId: input.assigneeAgentId, + for: input.for, + }); + + const [maxRow] = await tx + .select({ + maxNum: sql`coalesce(max(${issues.issueNumber}), 0)`, + }) + .from(issues) + .where(eq(issues.companyId, companyId)); + const currentMax = Number(maxRow?.maxNum ?? 0); + + const [companyRow] = await tx + .update(companies) + .set({ + issueCounter: sql`greatest(${companies.issueCounter}, ${currentMax}) + 1`, + updatedAt: now, + }) + .where(eq(companies.id, companyId)) + .returning({ + issueCounter: companies.issueCounter, + issuePrefix: companies.issuePrefix, + }); + + const issueNumber = companyRow!.issueCounter; + const identifier = `${companyRow!.issuePrefix}-${issueNumber}`; + const scope: IssueScope = input.board ? "board" : "channel"; + const priority: IssuePriority = input.priority ?? "medium"; + let issueVisibility: "open" | "private" = + channel.visibility === "private" ? "private" : "open"; + if (projectId && issueVisibility !== "private") { + const [projRow] = await tx + .select({ visibility: projects.visibility }) + .from(projects) + .where(and(eq(projects.id, projectId), eq(projects.companyId, companyId))) + .limit(1); + if (projRow?.visibility === "private") { + issueVisibility = "private"; + } + } + const newIssueId = randomUUID(); + const privacyRootIssueId = issueVisibility === "private" ? newIssueId : null; + + const [inserted] = await tx + .insert(issues) + .values({ + id: newIssueId, + companyId, + projectId, + channelId: channel.id, + visibility: issueVisibility, + privacyRootIssueId, + title: resolvedTitle, + description: resolvedDescription, + status: requestedStatus, + scope, + priority, + assigneeAgentId, + createdByAgentId: actor.agentId, + createdByUserId: actor.agentId ? null : actor.userId, + createdByProfile: actor.actorProfile, + responsibleUserId: actor.responsibleUserId, + kvLabels: mergedKvLabels, + schemaBlocks: validatedBlocks, + resultSchemaRef: resolvedResultSchemaRef, + issueNumber, + identifier, + originKind: "manual", + originId, + originFingerprint: requestHash ?? "default", + createdAt: now, + updatedAt: now, + }) + .returning(); + + await tx + .update(channels) + .set({ lastActivityAt: now, updatedAt: now }) + .where(eq(channels.id, channel.id)); + + if (input.tagLabels && input.tagLabels.length > 0) { + await attachTagLabels(tx, companyId, inserted!.id, input.tagLabels); + } + + await logActivity( + tx as unknown as Db, + { + companyId, + actorType: actor.principalType === "agent" ? "agent" : "user", + actorId: + actor.principalType === "agent" + ? actor.agentId! + : (actor.userId ?? "local-board"), + agentId: actor.agentId, + issueId: inserted!.id, + responsibleUserIdOverride: actor.responsibleUserId, + action: + requestedStatus === "todo" ? "issue.created" : "channel.post_created", + entityType: "issue", + entityId: inserted!.id, + details: { + identifier, + channel: channel.path, + status: requestedStatus, + scope, + }, + }, + publications, + ); + + const isReadyTask = requestedStatus === "todo" && assigneeAgentId === null; + const primaryEvent = await appendBoardEvent(tx, { + companyId, + type: requestedStatus === "todo" ? "task.created" : "thread.posted", + channelId: channel.id, + channelPath: channel.path, + issueId: inserted!.id, + identifier, + actor, + payload: { + title: resolvedTitle, + ...(resolvedDescription ? { description: resolvedDescription.slice(0, 4000) } : {}), + blocks: validatedBlocks, + labels: mergedKvLabels, + ...(isReadyTask ? { ready: true } : {}), + }, + }); + committedEvents.push(primaryEvent); + + let lastCursor = primaryEvent.cursor; + if (isReadyTask) { + const readyEvent = await appendBoardEvent(tx, { + companyId, + type: "task.ready", + channelId: channel.id, + channelPath: channel.path, + issueId: inserted!.id, + identifier, + actor, + payload: {}, + }); + committedEvents.push(readyEvent); + lastCursor = readyEvent.cursor; + } + + const view = await loadHeadlessIssueView(tx, inserted!.id, lastCursor); + return { issue: view, created: true }; + }); + + for (const pub of publications) { + publishActivity(pub); + } + for (const evt of committedEvents) { + publishCommittedBoardEvent(evt); + } + + return txResult; +} + +export interface ListChannelThreadsQuery { + channel: string; + status?: string | string[]; + label?: string | string[]; + after?: string; + limit?: number; + readCondition?: SQL; +} + +function toStringArray(val: string | string[] | undefined): string[] { + if (val === undefined) return []; + const arr = Array.isArray(val) ? val : [val]; + return arr + .flatMap((item) => item.split(",")) + .map((s) => s.trim()) + .filter((s) => s.length > 0); +} + +export async function listChannelThreads( + db: Db, + companyId: string, + actor: HeadlessActorContext, + query: ListChannelThreadsQuery, +): Promise { + const normalized = normalizeChannelPathOrThrow(query.channel, { + allowSubtreePrefix: true, + }); + enforceHeadlessScopes(actor, { + action: "read", + channelPath: normalized.path, + }); + + const channelDisplay = normalized.isSubtreePrefix + ? `${normalized.path}/` + : normalized.path; + + const statusFilters = toStringArray(query.status); + const rawLabelFilters = toStringArray(query.label); + const parsedLabelFilters = rawLabelFilters.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" }, + ); + } + }); + + const rawLimit = query.limit ?? 50; + const limit = Math.max(1, Math.min(200, Math.floor(rawLimit))); + + const matchedChannels = await db + .select() + .from(channels) + .where( + and( + eq(channels.companyId, companyId), + isNull(channels.archivedAt), + normalized.isSubtreePrefix + ? channelSubtreeCondition(normalized.path) + : eq(channels.path, normalized.path), + ), + ); + + if (!normalized.isSubtreePrefix) { + const exact = matchedChannels[0]; + if (!exact) { + return { + kind: "channel", + channel: channelDisplay, + items: [], + cursor: await getLatestCompanyEventCursor(db, companyId), + }; + } + await assertChannelAccess(db, exact, actor); + } + + const accessibleChannelIds: string[] = []; + for (const ch of matchedChannels) { + if (!isChannelAllowedByScopes(actor, ch.path)) continue; + if (!(await canAccessChannel(db, ch, actor))) continue; + accessibleChannelIds.push(ch.id); + } + + if (accessibleChannelIds.length === 0) { + return { + kind: "channel", + channel: channelDisplay, + items: [], + cursor: await getLatestCompanyEventCursor(db, companyId), + }; + } + + const issueConditions = [ + eq(issues.companyId, companyId), + inArray(issues.channelId, accessibleChannelIds), + isNull(issues.hiddenAt), + ...(query.readCondition ? [query.readCondition] : []), + ]; + if (statusFilters.length > 0) { + issueConditions.push(inArray(issues.status, statusFilters)); + } + for (const expr of parsedLabelFilters) { + issueConditions.push(buildSqlIssueLabelFilterCondition(expr)); + } + + if (query.after && query.after.trim().length > 0) { + const afterTrimmed = query.after.trim(); + const afterSeq = parseEventCursor(afterTrimmed); + if (afterSeq !== null) { + const eventIssueRows = await db + .selectDistinct({ issueId: boardEvents.issueId }) + .from(boardEvents) + .where( + and( + eq(boardEvents.companyId, companyId), + gt(boardEvents.seq, afterSeq), + inArray(boardEvents.channelId, accessibleChannelIds), + ), + ); + const matchingIds = eventIssueRows + .map((r) => r.issueId) + .filter((id): id is string => Boolean(id)); + if (matchingIds.length === 0) { + return { + kind: "channel", + channel: channelDisplay, + items: [], + cursor: await getLatestCompanyEventCursor(db, companyId), + }; + } + issueConditions.push(inArray(issues.id, matchingIds)); + } else if (isUuidLike(afterTrimmed)) { + const refIssue = await resolveIssueByIdOrIdentifier( + db, + afterTrimmed, + companyId, + ); + issueConditions.push(gt(issues.createdAt, refIssue.createdAt)); + } else { + const parsedDate = Date.parse(afterTrimmed); + if (!Number.isFinite(parsedDate)) { + throw badRequest(`Invalid 'after' cursor '${afterTrimmed}'`, { + error: "invalid_cursor", + code: "invalid_cursor", + }); + } + issueConditions.push(gt(issues.updatedAt, new Date(parsedDate))); + } + } + + const snapshotCursor = await getLatestCompanyEventCursor(db, companyId); + + const candidateRows = await db + .select() + .from(issues) + .where(and(...issueConditions)) + .orderBy(desc(issues.createdAt), desc(issues.id)) + .limit(limit); + + const pageViews = await loadHeadlessIssueViews(db, candidateRows); + const pageIssueIds = pageViews.map((v) => v.id); + + const replyCounts = new Map(); + const latestReplies = new Map(); + + if (pageIssueIds.length > 0) { + const commentRows = await db + .select() + .from(issueComments) + .where( + and( + eq(issueComments.companyId, companyId), + inArray(issueComments.issueId, pageIssueIds), + isNull(issueComments.deletedAt), + ), + ) + .orderBy(desc(issueComments.createdAt), desc(issueComments.id)); + + const identifierByIssueId = new Map( + pageViews.map((v) => [v.id, v.identifier]), + ); + const cursorByIssueId = new Map(pageViews.map((v) => [v.id, v.cursor])); + + for (const c of commentRows) { + replyCounts.set(c.issueId, (replyCounts.get(c.issueId) ?? 0) + 1); + if (!latestReplies.has(c.issueId)) { + latestReplies.set( + c.issueId, + serializeCommentView( + c, + identifierByIssueId.get(c.issueId) ?? c.issueId, + cursorByIssueId.get(c.issueId) ?? "evt_0", + ), + ); + } + } + } + + const items: ChannelPage["items"] = pageViews.map((view) => ({ + ...view, + replyCount: replyCounts.get(view.id) ?? 0, + latestReply: latestReplies.get(view.id) ?? null, + })); + + return { + kind: "channel", + channel: channelDisplay, + items, + cursor: snapshotCursor, + }; +} diff --git a/server/src/services/headless-common.ts b/server/src/services/headless-common.ts new file mode 100644 index 00000000000..93d617bccee --- /dev/null +++ b/server/src/services/headless-common.ts @@ -0,0 +1,1208 @@ +import { EventEmitter } from "node:events"; +import type { Request } from "express"; +import { and, desc, eq, inArray, ne, or, sql, type SQL } from "drizzle-orm"; +import type { Db } from "@paperclipai/db"; +import { + agents, + boardApiKeys, + boardEvents, + channelAccessMembers, + channels, + companies, + issueLabels, + issues, + labels, + projects, +} from "@paperclipai/db"; +import { + clientScopesSchema, + deriveAgentUrlKey, + deriveProjectUrlKey, + formatEventCursor, + isUuidLike, + normalizeChannelPath, + normalizeIssueIdentifier, + type AgentApiKeyScope, + type AgentIdentityPolicy, + type BoardEventType, + type BoardEventView, + type ClientScopes, + type CommentView, + type DeploymentMode, + type HeadlessIssueView, + type IssuePriority, + type IssueScope, + type IssueStatus, + type LabelFilterExpr, + type SchemaBlock, +} from "@paperclipai/shared"; +import { badRequest, conflict, forbidden, notFound, unauthorized } from "../errors.js"; +import { + authorizationService, + issueReadSqlCondition, + type AuthorizationActor, +} from "./authorization.js"; +import { publishLiveEvent } from "./live-events.js"; +import { listIssueDependencyReadinessMap } from "./issues.js"; + +export type DbOrTx = Db | Parameters[0]>[0]; + +const boardEventEmitter = new EventEmitter(); +boardEventEmitter.setMaxListeners(0); + +export function subscribeCompanyBoardEvents( + companyId: string, + listener: (event: BoardEventView) => void, +): () => void { + boardEventEmitter.on(companyId, listener); + return () => boardEventEmitter.off(companyId, listener); +} + +export function publishCommittedBoardEvent(event: BoardEventView): void { + boardEventEmitter.emit(event.companyId, event); + publishLiveEvent({ + companyId: event.companyId, + type: "activity.logged", + payload: { + boardEventSeq: event.seq, + boardEventCursor: event.cursor, + boardEventType: event.type, + channel: event.channel, + issueId: event.issueId, + identifier: event.identifier, + }, + }); +} + +export function resolveCompanyAgentIdentityPolicy( + storedPolicy: AgentIdentityPolicy | null | undefined, + deploymentMode: DeploymentMode = "local_trusted", +): AgentIdentityPolicy { + if (storedPolicy) return storedPolicy; + return deploymentMode === "local_trusted" + ? "open_local_profiles" + : "strict_agent_keys"; +} + +export interface HeadlessActorContext { + companyId: string; + companyName: string; + companyPrefix: string; + agentIdentityPolicy: AgentIdentityPolicy; + principalType: "local_trusted" | "user" | "agent"; + userId: string | null; + agentId: string | null; + agentName: string | null; + agentRole: string | null; + actorProfile: string | null; + scopes: ClientScopes | null; + keyId?: string | null; + keyScope?: AgentApiKeyScope | null; + isInstanceAdmin: boolean; + responsibleUserId: string | null; +} + +function channelMatchesScopePattern(channelPath: string, pattern: string): boolean { + const trimmed = pattern.trim().toLowerCase().replace(/^#/, ""); + if (trimmed === "*" || trimmed === "**") return true; + if (trimmed.endsWith("/*")) { + const base = trimmed.slice(0, -2); + return channelPath === base || channelPath.startsWith(`${base}/`); + } + if (trimmed.endsWith("/")) { + const base = trimmed.slice(0, -1); + return channelPath === base || channelPath.startsWith(`${base}/`); + } + return channelPath === trimmed; +} + +export function actionMatchesScopePattern(action: string, pattern: string): boolean { + const trimmed = pattern.trim().toLowerCase(); + if (trimmed === "*") return true; + if (trimmed.endsWith("*")) { + return action.toLowerCase().startsWith(trimmed.slice(0, -1)); + } + return action.toLowerCase() === trimmed; +} + +export function channelScopePatternCovers(allowedPattern: string, candidatePattern: string): boolean { + const allowed = allowedPattern.trim().toLowerCase().replace(/^#/, ""); + const candidate = candidatePattern.trim().toLowerCase().replace(/^#/, ""); + if (allowed === "*" || allowed === "**") return true; + if (candidate === "*" || candidate === "**") return false; + const candidateIsSubtree = candidate.endsWith("/*") || candidate.endsWith("/"); + const candidateBase = candidate.replace(/\/\*?$/, ""); + if (candidateIsSubtree) { + const allowedIsSubtree = allowed.endsWith("/*") || allowed.endsWith("/"); + if (!allowedIsSubtree) return false; + const allowedBase = allowed.replace(/\/\*?$/, ""); + return candidateBase === allowedBase || candidateBase.startsWith(`${allowedBase}/`); + } + return channelMatchesScopePattern(candidateBase, allowed); +} + +export function actionScopePatternCovers(allowedPattern: string, candidatePattern: string): boolean { + const allowed = allowedPattern.trim().toLowerCase(); + const candidate = candidatePattern.trim().toLowerCase(); + if (allowed === "*") return true; + if (candidate === "*") return false; + if (candidate.endsWith("*")) { + if (!allowed.endsWith("*")) return false; + return candidate.slice(0, -1).startsWith(allowed.slice(0, -1)); + } + return actionMatchesScopePattern(candidate, allowed); +} + +function isReadOnlyHeadlessAction(action?: string): boolean { + if (!action) return true; + const normalized = action.trim().toLowerCase(); + return normalized === "read" || normalized.endsWith(".read"); +} + +function mergeClientScopes( + keyScopes: ClientScopes | null, + headerScopes: ClientScopes | null, +): ClientScopes | null { + if (!keyScopes && !headerScopes) return null; + if (!keyScopes) return headerScopes; + if (!headerScopes) return keyScopes; + + const merged: ClientScopes = {}; + if (keyScopes.channels && headerScopes.channels) { + merged.channels = headerScopes.channels.filter((ch) => + keyScopes.channels!.some((allowed) => channelScopePatternCovers(allowed, ch)), + ); + } else if (keyScopes.channels) { + merged.channels = keyScopes.channels; + } else if (headerScopes.channels) { + merged.channels = headerScopes.channels; + } + + if (keyScopes.actions && headerScopes.actions) { + merged.actions = headerScopes.actions.filter((act) => + keyScopes.actions!.some((allowed) => actionScopePatternCovers(allowed, act)), + ); + } else if (keyScopes.actions) { + merged.actions = keyScopes.actions; + } else if (headerScopes.actions) { + merged.actions = headerScopes.actions; + } + + return merged; +} + +export function enforceHeadlessScopes( + actor: Pick, + check: { action?: string; channelPath?: string }, +): void { + if (actor.keyScope && actor.keyScope.kind !== "standard") { + throw forbidden( + `Scoped '${actor.keyScope.kind}' agent keys cannot access headless channel or queue endpoints`, + { code: "scope_denied" }, + ); + } + if (!actor.scopes) return; + if (check.action && actor.scopes.actions) { + const allowed = actor.scopes.actions.some((pattern) => + actionMatchesScopePattern(check.action!, pattern), + ); + if (!allowed) { + throw forbidden(`Caller scopes do not allow action '${check.action}'`, { + code: "scope_denied", + action: check.action, + }); + } + } + if (check.channelPath && actor.scopes.channels) { + const normalized = normalizeChannelPath(check.channelPath, { + allowSubtreePrefix: true, + }).path; + const allowed = actor.scopes.channels.some((pattern) => + channelMatchesScopePattern(normalized, pattern), + ); + if (!allowed) { + throw forbidden( + `Caller scopes do not allow channel '${check.channelPath}'`, + { + code: "scope_denied", + channel: check.channelPath, + }, + ); + } + } +} + +export async function resolveHeadlessActor( + db: Db, + req: Request, + companyId: string, + opts: { + deploymentMode?: DeploymentMode; + requiredAction?: string; + requiredChannel?: string; + } = {}, +): Promise { + if (!req.actor || req.actor.type === "none") { + throw unauthorized("Authentication required"); + } + + const [company] = await db + .select({ + id: companies.id, + name: companies.name, + issuePrefix: companies.issuePrefix, + agentIdentityPolicy: companies.agentIdentityPolicy, + defaultResponsibleUserId: companies.defaultResponsibleUserId, + }) + .from(companies) + .where(eq(companies.id, companyId)); + + if (!company) { + throw notFound("Company not found"); + } + + const deploymentMode: DeploymentMode = + opts.deploymentMode ?? + (req.actor.source === "local_implicit" ? "local_trusted" : "authenticated"); + const policy = resolveCompanyAgentIdentityPolicy( + company.agentIdentityPolicy, + deploymentMode, + ); + + const rawProfileHeader = req.header("x-paperclip-actor-profile")?.trim() || null; + const rawScopesHeader = req.header("x-paperclip-actor-scopes")?.trim() || null; + let headerScopes: ClientScopes | null = null; + if (rawScopesHeader) { + let parsedJson: unknown; + try { + parsedJson = JSON.parse(rawScopesHeader); + } catch { + throw badRequest("Malformed X-Paperclip-Actor-Scopes header JSON"); + } + const parsed = clientScopesSchema.safeParse(parsedJson); + if (!parsed.success) { + throw badRequest("Invalid X-Paperclip-Actor-Scopes header"); + } + headerScopes = parsed.data; + } + + const isReadAction = isReadOnlyHeadlessAction(opts.requiredAction); + + if (req.actor.type === "agent") { + if (req.actor.keyScope && req.actor.keyScope.kind !== "standard") { + throw forbidden( + `Scoped '${req.actor.keyScope.kind}' agent keys cannot access headless channel or queue endpoints`, + { code: "scope_denied" }, + ); + } + const actorAgentId = req.actor.agentId; + if (!actorAgentId || req.actor.companyId !== companyId) { + throw forbidden("Agent does not belong to this company"); + } + const localBoardOnBehalf = + deploymentMode === "local_trusted" && req.actor.onBehalfOfUserId === "local-board"; + if (req.actor.onBehalfOfUserId?.trim() && !localBoardOnBehalf) { + const membership = req.actor.onBehalfOfMemberships?.find( + (item) => item.companyId === companyId && item.status === "active", + ); + if (!membership) { + throw forbidden("Responsible user is unavailable for this company", { + code: "RESPONSIBLE_USER_UNAVAILABLE", + }); + } + if (!isReadAction && membership.membershipRole === "viewer") { + throw forbidden("Responsible user is not authorized for write access", { + code: "RESPONSIBLE_USER_UNAUTHORIZED", + }); + } + } + const [agentRow] = await db + .select({ + id: agents.id, + name: agents.name, + role: agents.role, + status: agents.status, + }) + .from(agents) + .where(and(eq(agents.id, actorAgentId), eq(agents.companyId, companyId))); + + if (!agentRow || agentRow.status === "terminated" || agentRow.status === "pending_approval") { + throw unauthorized("Authenticated agent record is unavailable"); + } + + const derivedSlug = deriveAgentUrlKey(agentRow.name, agentRow.id); + if ( + rawProfileHeader && + rawProfileHeader.toLowerCase() !== agentRow.name.toLowerCase() && + rawProfileHeader.toLowerCase() !== derivedSlug.toLowerCase() + ) { + throw forbidden( + `Authenticated agent '@${agentRow.name}' cannot impersonate profile '${rawProfileHeader}'`, + { code: "profile_locked" }, + ); + } + + const ctx: HeadlessActorContext = { + companyId: company.id, + companyName: company.name, + companyPrefix: company.issuePrefix, + agentIdentityPolicy: policy, + principalType: "agent", + userId: req.actor.onBehalfOfUserId ?? null, + agentId: agentRow.id, + agentName: agentRow.name, + agentRole: agentRow.role, + actorProfile: agentRow.name, + scopes: headerScopes, + keyId: req.actor.keyId ?? null, + keyScope: req.actor.keyScope ?? null, + isInstanceAdmin: false, + responsibleUserId: + req.actor.onBehalfOfUserId ?? company.defaultResponsibleUserId ?? null, + }; + enforceHeadlessScopes(ctx, { + action: opts.requiredAction, + channelPath: opts.requiredChannel, + }); + return ctx; + } + + // Board actor (local_implicit, session, board_key, cloud_tenant, etc.) + const isLocalImplicit = req.actor.source === "local_implicit"; + if ( + !isLocalImplicit && + !req.actor.isInstanceAdmin && + !(req.actor.companyIds ?? []).includes(companyId) + ) { + throw forbidden("User does not have access to this company"); + } + if (!isLocalImplicit && !req.actor.isInstanceAdmin && Array.isArray(req.actor.memberships)) { + const membership = req.actor.memberships.find((item) => item.companyId === companyId); + if (!membership || membership.status !== "active") { + throw forbidden("User does not have active company access"); + } + if (!isReadAction && membership.membershipRole === "viewer") { + throw forbidden("Viewer access is read-only"); + } + } + + let keyScopes: ClientScopes | null = req.actor.keyScopes ?? null; + let lockedProfile: string | null = req.actor.keyLockedProfile?.trim() || null; + if (req.actor.source === "board_key" && req.actor.keyCompanyId && req.actor.keyCompanyId !== companyId) { + throw forbidden("Board API key is scoped to another company", { + code: "company_scope_denied", + }); + } + if (req.actor.source === "board_key" && req.actor.keyId) { + const [keyRow] = await db + .select({ + companyId: boardApiKeys.companyId, + lockedProfile: boardApiKeys.lockedProfile, + scopes: boardApiKeys.scopes, + }) + .from(boardApiKeys) + .where(eq(boardApiKeys.id, req.actor.keyId)); + + if (keyRow?.companyId && keyRow.companyId !== companyId) { + throw forbidden("Board API key is scoped to another company", { + code: "company_scope_denied", + }); + } + lockedProfile = keyRow?.lockedProfile?.trim() || lockedProfile; + keyScopes = keyRow?.scopes ?? keyScopes; + } + + if ( + lockedProfile && + rawProfileHeader && + rawProfileHeader.toLowerCase() !== lockedProfile.toLowerCase() + ) { + throw forbidden( + `Board API key is locked to profile '${lockedProfile}'`, + { code: "profile_locked" }, + ); + } + + const effectiveProfile = lockedProfile ?? rawProfileHeader; + + if (effectiveProfile) { + if (policy === "strict_agent_keys") { + throw forbidden( + `Company policy 'strict_agent_keys' requires a registered agent API key instead of ephemeral profile '${effectiveProfile}'`, + { + code: "agent_key_required", + next: [ + `paperclipai agent connect ${effectiveProfile}`, + `paperclipai agent login --name ${effectiveProfile}`, + ], + }, + ); + } + + // Check whether an active registered agent with this name or derived urlKey already exists. + const profileLower = effectiveProfile.toLowerCase(); + const companyAgents = await db + .select({ + id: agents.id, + name: agents.name, + }) + .from(agents) + .where( + and( + eq(agents.companyId, companyId), + ne(agents.status, "terminated"), + ), + ); + const registeredAgent = companyAgents.find( + (a) => + a.name.trim().toLowerCase() === profileLower || + deriveAgentUrlKey(a.name, a.id).toLowerCase() === profileLower, + ); + + if (registeredAgent) { + throw conflict( + `Profile '${effectiveProfile}' matches registered agent '@${registeredAgent.name}'. Use that agent's API key instead of an unverified profile header.`, + { + code: "profile_matches_registered_agent", + agentId: registeredAgent.id, + agentName: registeredAgent.name, + next: [ + `paperclipai agent connect ${registeredAgent.name}`, + `paperclipai agent login --name ${registeredAgent.name}`, + ], + }, + ); + } + } + + const scopes = mergeClientScopes(keyScopes, headerScopes); + const ctx: HeadlessActorContext = { + companyId: company.id, + companyName: company.name, + companyPrefix: company.issuePrefix, + agentIdentityPolicy: policy, + principalType: isLocalImplicit ? "local_trusted" : "user", + userId: req.actor.userId ?? null, + agentId: null, + agentName: null, + agentRole: null, + actorProfile: effectiveProfile, + scopes, + isInstanceAdmin: Boolean(req.actor.isInstanceAdmin), + responsibleUserId: + req.actor.userId && req.actor.userId !== "local-board" + ? req.actor.userId + : company.defaultResponsibleUserId ?? req.actor.userId ?? null, + }; + + enforceHeadlessScopes(ctx, { + action: opts.requiredAction, + channelPath: opts.requiredChannel, + }); + + return ctx; +} + +export function escapeSqlLikePattern(value: string): string { + return value.replace(/[\\%_]/g, "\\$&"); +} + +export function channelDescendantsCondition( + path: string, + column: typeof channels.path = channels.path, +): SQL { + const pattern = `${escapeSqlLikePattern(path)}/%`; + return sql`${column} LIKE ${pattern} ESCAPE '\\'`; +} + +export function channelSubtreeCondition( + path: string, + column: typeof channels.path = channels.path, +): SQL { + return or(eq(column, path), channelDescendantsCondition(path, column)) as SQL; +} + +export async function findInaccessibleChannelIds( + dbOrTx: DbOrTx, + companyId: string, + actor: HeadlessActorContext, + companyChannels: Array<{ + id: string; + companyId: string; + path: string; + visibility: string; + createdByUserId: string | null; + createdByAgentId: string | null; + }>, +): Promise { + if (companyChannels.length === 0) return []; + const bypassPrivacy = + actor.isInstanceAdmin || actor.principalType === "local_trusted"; + const privateChannelIds = !bypassPrivacy + ? companyChannels.filter((c) => c.visibility === "private").map((c) => c.id) + : []; + + const memberChannelIds = new Set(); + if (privateChannelIds.length > 0 && (actor.agentId || actor.userId)) { + const subjectConditions = []; + if (actor.agentId) { + subjectConditions.push( + and( + eq(channelAccessMembers.subjectType, "agent"), + eq(channelAccessMembers.subjectId, actor.agentId), + ), + ); + } + if (actor.userId) { + subjectConditions.push( + and( + eq(channelAccessMembers.subjectType, "user"), + eq(channelAccessMembers.subjectId, actor.userId), + ), + ); + } + const rows = await dbOrTx + .select({ channelId: channelAccessMembers.channelId }) + .from(channelAccessMembers) + .where( + and( + eq(channelAccessMembers.companyId, companyId), + inArray(channelAccessMembers.channelId, privateChannelIds), + or(...subjectConditions), + ), + ); + for (const r of rows) { + memberChannelIds.add(r.channelId); + } + } + + const inaccessible: string[] = []; + for (const ch of companyChannels) { + let scopeOk = true; + try { + enforceHeadlessScopes(actor, { channelPath: ch.path }); + } catch { + scopeOk = false; + } + if (!scopeOk) { + inaccessible.push(ch.id); + continue; + } + if (ch.visibility !== "private" || bypassPrivacy) continue; + const isCreator = + (actor.agentId && ch.createdByAgentId === actor.agentId) || + (actor.userId && ch.createdByUserId === actor.userId); + if (!isCreator && !memberChannelIds.has(ch.id)) { + inaccessible.push(ch.id); + } + } + return inaccessible; +} + +export async function canAccessChannel( + dbOrTx: DbOrTx, + channel: { + id: string; + companyId: string; + visibility: string; + createdByUserId: string | null; + createdByAgentId: string | null; + }, + actor: HeadlessActorContext, +): Promise { + if (channel.companyId !== actor.companyId) return false; + if (channel.visibility !== "private") return true; + if (actor.isInstanceAdmin || actor.principalType === "local_trusted") { + return true; + } + if (actor.agentId && channel.createdByAgentId === actor.agentId) return true; + if (actor.userId && channel.createdByUserId === actor.userId) return true; + + const subjectConditions = []; + if (actor.agentId) { + subjectConditions.push( + and( + eq(channelAccessMembers.subjectType, "agent"), + eq(channelAccessMembers.subjectId, actor.agentId), + ), + ); + } + if (actor.userId) { + subjectConditions.push( + and( + eq(channelAccessMembers.subjectType, "user"), + eq(channelAccessMembers.subjectId, actor.userId), + ), + ); + } + if (subjectConditions.length === 0) return false; + + const [member] = await dbOrTx + .select({ id: channelAccessMembers.id }) + .from(channelAccessMembers) + .where( + and( + eq(channelAccessMembers.channelId, channel.id), + or(...subjectConditions), + ), + ) + .limit(1); + + return Boolean(member); +} + +export async function assertCanonicalIssueAccessForActor( + dbOrTx: DbOrTx, + authActor: AuthorizationActor, + issue: { + id: string; + companyId: string; + projectId: string | null; + parentId: string | null; + assigneeAgentId: string | null; + assigneeUserId: string | null; + status: string; + }, + action: "issue:read" | "issue:comment" | "issue:mutate", +): Promise { + const access = authorizationService(dbOrTx as Db); + const resource = { + type: "issue" as const, + companyId: issue.companyId, + issueId: issue.id, + projectId: issue.projectId, + parentIssueId: issue.parentId, + assigneeAgentId: issue.assigneeAgentId, + assigneeUserId: issue.assigneeUserId, + status: issue.status, + }; + const scope = { + issueId: issue.id, + projectId: issue.projectId, + parentIssueId: issue.parentId, + assigneeAgentId: issue.assigneeAgentId, + assigneeUserId: issue.assigneeUserId, + }; + const readDecision = await access.decide({ + actor: authActor, + action: "issue:read", + resource, + scope, + }); + if (!readDecision.allowed) { + throw notFound("Issue not found"); + } + if (action !== "issue:read") { + const writeDecision = await access.decide({ + actor: authActor, + action, + resource, + scope, + }); + if (!writeDecision.allowed) { + throw forbidden(writeDecision.explanation ?? "Forbidden"); + } + } +} + +export async function assertCanonicalIssueAccess( + db: Db, + req: Request, + issue: { + id: string; + companyId: string; + projectId: string | null; + parentId: string | null; + assigneeAgentId: string | null; + assigneeUserId: string | null; + status: string; + }, + action: "issue:read" | "issue:comment" | "issue:mutate", +): Promise { + return assertCanonicalIssueAccessForActor(db, req.actor, issue, action); +} + +export async function resolveHeadlessIssueReadCondition(db: Db, req: Request) { + if ( + req.actor.type === "agent" && + req.actor.keyScope && + req.actor.keyScope.kind !== "standard" + ) { + return sql`false`; + } + return issueReadSqlCondition(db, req.actor); +} + +export async function assertChannelAccess( + dbOrTx: DbOrTx, + channel: { + id: string; + companyId: string; + path: string; + visibility: string; + createdByUserId: string | null; + createdByAgentId: string | null; + }, + actor: HeadlessActorContext, +): Promise { + enforceHeadlessScopes(actor, { channelPath: channel.path }); + const allowed = await canAccessChannel(dbOrTx, channel, actor); + if (!allowed) { + throw notFound(`Channel '${channel.path}' not found`); + } +} + +export function allowsUnchanneledScope( + actor: Pick, +): boolean { + const channelScopes = actor.scopes?.channels; + if (!channelScopes) return true; + return channelScopes.some((pattern) => { + const t = pattern.trim().toLowerCase(); + return t === "*" || t === "**"; + }); +} + +export async function assertIssueChannelScopeAccess( + dbOrTx: DbOrTx, + issue: { channelId: string | null }, + actor: HeadlessActorContext, +): Promise<{ channel: typeof channels.$inferSelect | null; channelPath: string | null }> { + if (issue.channelId) { + const [ch] = await dbOrTx + .select() + .from(channels) + .where(eq(channels.id, issue.channelId)) + .limit(1); + if (ch) { + await assertChannelAccess(dbOrTx, ch, actor); + return { channel: ch, channelPath: ch.path }; + } + return { channel: null, channelPath: null }; + } + if (!allowsUnchanneledScope(actor)) { + throw forbidden("Caller scopes do not allow accessing unchanneled issues", { + code: "scope_denied", + }); + } + return { channel: null, channelPath: null }; +} + +export function buildSqlIssueLabelFilterCondition(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 buildAuthActorFromHeadless( + actor: HeadlessActorContext, +): AuthorizationActor { + if (actor.principalType === "local_trusted") { + return { + type: "board", + userId: actor.userId ?? "local-board", + source: "local_implicit", + isInstanceAdmin: true, + }; + } + if (actor.principalType === "agent" && actor.agentId) { + return { + type: "agent", + agentId: actor.agentId, + companyId: actor.companyId, + source: "agent_key", + ...(actor.keyId ? { keyId: actor.keyId } : {}), + ...(actor.keyScope ? { keyScope: actor.keyScope } : {}), + ...(actor.userId ? { onBehalfOfUserId: actor.userId } : {}), + }; + } + return { + type: "board", + userId: actor.userId ?? undefined, + companyIds: [actor.companyId], + isInstanceAdmin: actor.isInstanceAdmin, + ignoreInstanceAdmin: !actor.isInstanceAdmin, + source: "session", + }; +} + +function toAuthActor( + actorOrAuth: HeadlessActorContext | AuthorizationActor, +): AuthorizationActor { + return "principalType" in actorOrAuth + ? buildAuthActorFromHeadless(actorOrAuth) + : actorOrAuth; +} + +export async function assertProjectReadAccess( + dbOrTx: DbOrTx, + companyId: string, + projectId: string, + actorOrAuth: HeadlessActorContext | AuthorizationActor, + displayRef = projectId, +): Promise { + const decision = await authorizationService(dbOrTx as unknown as Db).decide({ + actor: toAuthActor(actorOrAuth), + action: "project:read", + resource: { type: "project", companyId, projectId }, + scope: { projectId }, + }); + if (!decision.allowed) { + throw notFound(`Project '${displayRef}' not found`); + } +} + +export async function resolveProjectReference( + dbOrTx: DbOrTx, + companyId: string, + projectRef: string | null | undefined, + actorOrAuth?: HeadlessActorContext | AuthorizationActor, +): Promise { + if (projectRef === undefined || projectRef === null) return null; + const trimmed = projectRef.trim(); + if (!trimmed) return null; + + let resolvedId: string; + if (isUuidLike(trimmed)) { + const [row] = await dbOrTx + .select({ id: projects.id }) + .from(projects) + .where(and(eq(projects.companyId, companyId), eq(projects.id, trimmed))); + if (!row) throw notFound(`Project '${trimmed}' not found`); + resolvedId = row.id; + } else { + const companyProjects = await dbOrTx + .select({ id: projects.id, name: projects.name }) + .from(projects) + .where(eq(projects.companyId, companyId)); + + const lower = trimmed.toLowerCase(); + const match = + companyProjects.find( + (p) => deriveProjectUrlKey(p.name, p.id).toLowerCase() === lower, + ) ?? companyProjects.find((p) => p.name.trim().toLowerCase() === lower); + + if (!match) { + throw notFound(`Project '${trimmed}' not found`); + } + resolvedId = match.id; + } + + if (actorOrAuth) { + await assertProjectReadAccess(dbOrTx, companyId, resolvedId, actorOrAuth, trimmed); + } + return resolvedId; +} + +export async function resolveIssueByIdOrIdentifier( + dbOrTx: DbOrTx, + idOrIdentifier: string, + expectedCompanyId?: string, +) { + const trimmed = idOrIdentifier.trim(); + let row; + if (isUuidLike(trimmed)) { + [row] = await dbOrTx + .select() + .from(issues) + .where( + expectedCompanyId + ? and(eq(issues.id, trimmed), eq(issues.companyId, expectedCompanyId)) + : eq(issues.id, trimmed), + ); + } else { + const normalized = normalizeIssueIdentifier(trimmed) ?? trimmed.toUpperCase(); + [row] = await dbOrTx + .select() + .from(issues) + .where( + expectedCompanyId + ? and( + sql`upper(${issues.identifier}) = ${normalized.toUpperCase()}`, + eq(issues.companyId, expectedCompanyId), + ) + : sql`upper(${issues.identifier}) = ${normalized.toUpperCase()}`, + ); + } + if (!row) { + throw notFound(`Issue '${idOrIdentifier}' not found`); + } + return row; +} + +export async function appendBoardEvent( + dbOrTx: DbOrTx, + input: { + companyId: string; + type: BoardEventType; + channelId?: string | null; + channelPath?: string | null; + issueId?: string | null; + identifier?: string | null; + actor: Pick< + HeadlessActorContext, + "principalType" | "userId" | "agentId" | "agentName" | "actorProfile" + > | { + principalType: "system"; + userId?: null; + agentId?: null; + agentName?: null; + actorProfile?: string | null; + }; + payload?: Record; + }, +): Promise { + const actorType: "user" | "agent" | "system" = + input.actor.principalType === "agent" + ? "agent" + : input.actor.principalType === "system" + ? "system" + : "user"; + const actorId = + input.actor.principalType === "agent" + ? input.actor.agentId ?? null + : input.actor.principalType === "system" + ? "system" + : input.actor.userId ?? null; + const actorName = + input.actor.principalType === "agent" + ? input.actor.agentName ?? null + : null; + const actorProfile = input.actor.actorProfile ?? null; + + await dbOrTx.execute( + sql`SELECT pg_advisory_xact_lock(hashtext('board_events'), hashtext(${input.companyId}))`, + ); + + const [inserted] = await dbOrTx + .insert(boardEvents) + .values({ + companyId: input.companyId, + eventType: input.type, + channelId: input.channelId ?? null, + channelPath: input.channelPath ?? null, + issueId: input.issueId ?? null, + identifier: input.identifier ?? null, + actorType, + actorId, + actorName, + actorProfile, + payload: input.payload ?? {}, + }) + .returning(); + + const seq = Number(inserted!.seq); + return { + cursor: formatEventCursor(seq), + seq, + type: input.type, + companyId: input.companyId, + channel: input.channelPath ?? null, + issueId: input.issueId ?? null, + identifier: input.identifier ?? null, + actor: { + type: actorType, + id: actorId, + name: actorName, + profile: actorProfile, + }, + payload: (inserted!.payload ?? {}) as Record, + createdAt: inserted!.createdAt.toISOString(), + }; +} + +export async function getLatestCompanyEventCursor( + dbOrTx: DbOrTx, + companyId: string, +): Promise { + const [latest] = await dbOrTx + .select({ seq: boardEvents.seq }) + .from(boardEvents) + .where(eq(boardEvents.companyId, companyId)) + .orderBy(desc(boardEvents.seq)) + .limit(1); + return formatEventCursor(latest ? Number(latest.seq) : 0); +} + +export async function loadHeadlessIssueViews( + dbOrTx: DbOrTx, + issueRows: Array, + explicitCursor?: string, +): Promise { + if (issueRows.length === 0) return []; + const issueIds = issueRows.map((r) => r.id); + const channelIds = Array.from( + new Set(issueRows.map((r) => r.channelId).filter((x): x is string => Boolean(x))), + ); + const companyId = issueRows[0]!.companyId; + + const [channelRows, labelRows, readinessMap, latestEvents, fallbackCursor] = + await Promise.all([ + channelIds.length > 0 + ? dbOrTx + .select({ id: channels.id, path: channels.path }) + .from(channels) + .where(inArray(channels.id, channelIds)) + : Promise.resolve([]), + dbOrTx + .select({ + issueId: issueLabels.issueId, + name: labels.name, + }) + .from(issueLabels) + .innerJoin(labels, eq(issueLabels.labelId, labels.id)) + .where(inArray(issueLabels.issueId, issueIds)), + listIssueDependencyReadinessMap(dbOrTx as unknown as Db, companyId, issueIds, false), + explicitCursor + ? Promise.resolve([]) + : dbOrTx + .select({ + issueId: boardEvents.issueId, + maxSeq: sql`max(${boardEvents.seq})`, + }) + .from(boardEvents) + .where( + and( + eq(boardEvents.companyId, companyId), + inArray(boardEvents.issueId, issueIds), + ), + ) + .groupBy(boardEvents.issueId), + explicitCursor + ? Promise.resolve(explicitCursor) + : getLatestCompanyEventCursor(dbOrTx, companyId), + ]); + + const channelMap = new Map(channelRows.map((c) => [c.id, c.path])); + const tagMap = new Map(); + for (const row of labelRows) { + const arr = tagMap.get(row.issueId) ?? []; + arr.push(row.name); + tagMap.set(row.issueId, arr); + } + const blockerMap = new Map(); + for (const [issueId, readiness] of readinessMap) { + if (readiness.unresolvedBlockerIssueIds.length > 0) { + blockerMap.set(issueId, readiness.unresolvedBlockerIssueIds); + } + } + const seqMap = new Map(); + for (const row of latestEvents) { + if (row.issueId && row.maxSeq != null) { + seqMap.set(row.issueId, Number(row.maxSeq)); + } + } + + return issueRows.map((row) => { + const channelPath = row.channelId ? channelMap.get(row.channelId) ?? null : null; + const isPassivePost = + row.scope === "channel" && + row.status === "backlog" && + !row.assigneeAgentId && + !row.assigneeUserId; + const issueSeq = seqMap.get(row.id); + const cursor = + explicitCursor ?? + (issueSeq !== undefined ? formatEventCursor(issueSeq) : fallbackCursor); + + return { + id: row.id, + companyId: row.companyId, + identifier: row.identifier ?? row.id, + title: row.title, + description: row.description ?? null, + status: row.status as IssueStatus, + scope: row.scope as IssueScope, + priority: row.priority as IssuePriority, + channelId: row.channelId ?? null, + channel: channelPath, + projectId: row.projectId ?? null, + assigneeAgentId: row.assigneeAgentId ?? null, + assigneeUserId: row.assigneeUserId ?? null, + actorProfile: row.createdByProfile ?? null, + kvLabels: (row.kvLabels ?? {}) as Record, + tagLabels: tagMap.get(row.id) ?? [], + blocks: (row.schemaBlocks ?? []) as SchemaBlock[], + resultSchemaRef: row.resultSchemaRef ?? null, + blockedByIssueIds: blockerMap.get(row.id) ?? [], + isPassivePost, + claimEpoch: Number(row.claimEpoch ?? 0), + claimHolderProfile: row.claimHolderProfile ?? null, + claimHolderAgentId: row.claimHolderAgentId ?? null, + claimHolderUserId: row.claimHolderUserId ?? null, + claimLeaseExpiresAt: row.claimLeaseExpiresAt + ? row.claimLeaseExpiresAt.toISOString() + : null, + claimAttemptCount: row.claimAttemptCount ?? 0, + cursor, + createdAt: row.createdAt.toISOString(), + updatedAt: row.updatedAt.toISOString(), + }; + }); +} + +export async function loadHeadlessIssueView( + dbOrTx: DbOrTx, + issueId: string, + explicitCursor?: string, +): Promise { + const [row] = await dbOrTx.select().from(issues).where(eq(issues.id, issueId)); + if (!row) throw notFound("Issue not found"); + const views = await loadHeadlessIssueViews(dbOrTx, [row], explicitCursor); + return views[0]!; +} + +export function serializeCommentView( + row: { + id: string; + issueId: string; + body: string; + authorType?: string | null; + authorUserId?: string | null; + authorAgentId?: string | null; + actorProfile?: string | null; + kvLabels?: Record | null; + schemaBlocks?: SchemaBlock[] | null; + blocks?: SchemaBlock[] | null; + noSync?: boolean | null; + createdAt: Date; + }, + identifier: string, + cursor = "evt_0", +): CommentView { + const authorType: "user" | "agent" | "system" = + row.authorType === "agent" || row.authorAgentId + ? "agent" + : row.authorType === "system" + ? "system" + : "user"; + + return { + id: row.id, + issueId: row.issueId, + identifier, + body: row.body, + authorType, + authorUserId: row.authorUserId ?? null, + authorAgentId: row.authorAgentId ?? null, + actorProfile: row.actorProfile ?? null, + kvLabels: (row.kvLabels ?? {}) as Record, + blocks: (row.schemaBlocks ?? row.blocks ?? []) as SchemaBlock[], + internal: Boolean(row.noSync), + cursor, + createdAt: row.createdAt.toISOString(), + }; +} diff --git a/server/src/services/headless-events-schedules-interactions.ts b/server/src/services/headless-events-schedules-interactions.ts new file mode 100644 index 00000000000..f0866f81cbe --- /dev/null +++ b/server/src/services/headless-events-schedules-interactions.ts @@ -0,0 +1,2456 @@ +import { randomUUID } from "node:crypto"; +import { and, asc, desc, eq, gt, inArray, isNull, ne, sql } from "drizzle-orm"; +import { z } from "zod"; +import type { Db } from "@paperclipai/db"; +import { + activityLog, + agents, + boardEvents, + channels, + companies, + issueComments, + issueLabels, + issues, + issueThreadInteractions, + labels, + projects, + scheduledBoardPosts, +} from "@paperclipai/db"; +import { + boardEventTypeSchema, + deriveAgentUrlKey, + formatEventCursor, + isUuidLike, + matchesLabelFilter, + normalizeChannelPath, + normalizeIssueIdentifier, + OneLineAskSchema, + OneLineConfirmSchema, + parseDurationMs, + parseEventCursor, + parseLabelFilterExpr, + parseSchemaRef, + SchedulePostSchema, + splitMessageIntoTitleAndDescription, + type AskUserQuestionsPayload, + type AskUserQuestionsResult, + type BoardEventType, + type BoardEventView, + type InteractionView, + type IssueThreadInteractionPayload, + type IssueThreadInteractionResult, + type LabelFilterExpr, + type RequestConfirmationPayload, + type RequestConfirmationResult, + type SchemaBlock, + type ScheduleView, +} from "@paperclipai/shared"; +import { badRequest, conflict, forbidden, notFound, unprocessable } from "../errors.js"; +import { logActivity, publishActivity, type ActivityPublication } from "./activity-log.js"; +import { issueReadSqlCondition, type AuthorizationActor } from "./authorization.js"; +import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; +import { ensureChannel } from "./headless-channels.js"; +import { heartbeatService } from "./heartbeat.js"; +import { listIssueDependencyReadinessMap } from "./issues.js"; +import { logger } from "../middleware/logger.js"; +import { + allowsUnchanneledScope, + appendBoardEvent, + assertCanonicalIssueAccessForActor, + assertChannelAccess, + assertIssueChannelScopeAccess, + buildAuthActorFromHeadless, + canAccessChannel, + enforceHeadlessScopes, + getLatestCompanyEventCursor, + publishCommittedBoardEvent, + resolveIssueByIdOrIdentifier, + subscribeCompanyBoardEvents, + type DbOrTx, + type HeadlessActorContext, +} from "./headless-common.js"; +import { extractClaimToken, verifyClaimToken } from "./headless-task-queue.js"; + +const ISSUE_REF_RE = /^[A-Z][A-Z0-9]*-\d+$/i; + +function isIssueReferenceTarget(target: string): boolean { + const trimmed = target.trim(); + 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 interface BoardEventFilterInput { + channel?: string; + issueId?: string; + event?: BoardEventType[]; + label?: string[]; + mentions?: string; + schema?: string; + after?: string; +} + +export interface ParsedBoardEventFilters { + afterSeq: number; + hasExplicitAfter: boolean; + channelNorm: { path: string; isSubtreePrefix: boolean } | null; + issueUuid: string | null; + issueIdentifierUpper: string | null; + eventTypes: Set | null; + labelExprs: LabelFilterExpr[]; + mentionsName: string | null; + schemaFilter: { name: string; version: number | null } | null; +} + +function escapeRegExp(input: string): string { + return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +function isChannelAllowedByScopes( + actor: HeadlessActorContext, + channelPath: string, +): boolean { + try { + enforceHeadlessScopes(actor, { channelPath }); + return true; + } catch { + return false; + } +} + +function serializeInteractionRow( + row: typeof issueThreadInteractions.$inferSelect, + identifier: string, + cursor: string, +): InteractionView { + const kind = + row.kind === "request_confirmation" + ? "request_confirmation" + : "ask_user_questions"; + let prompt = row.title ?? ""; + let choices: string[] | undefined; + + if (kind === "ask_user_questions") { + const payload = row.payload as AskUserQuestionsPayload; + const firstQ = payload?.questions?.[0]; + if (firstQ?.prompt) { + prompt = firstQ.prompt; + } + const optionLabels = (firstQ?.options ?? []).map((o) => o.label).filter(Boolean); + if (optionLabels.length > 0) { + choices = optionLabels; + } + } else { + const payload = row.payload as RequestConfirmationPayload; + if (payload?.prompt) { + prompt = payload.prompt; + } + } + + let answer: string | null | undefined; + let note: string | null | undefined; + if (row.result) { + if (kind === "ask_user_questions") { + const res = row.result as AskUserQuestionsResult; + answer = res.summaryMarkdown ?? res.answers?.[0]?.otherText ?? res.reason ?? null; + note = res.reason ?? null; + } else { + const res = row.result as RequestConfirmationResult; + note = res.reason ?? null; + } + } + + return { + id: row.id, + issueId: row.issueId, + identifier, + kind, + status: row.status as InteractionView["status"], + prompt, + ...(choices ? { choices } : {}), + resolverPolicy: row.effectiveResolverPolicy as InteractionView["resolverPolicy"], + continuationPolicy: row.continuationPolicy, + ...(answer !== undefined ? { answer } : {}), + ...(note !== undefined ? { note } : {}), + cursor, + createdAt: row.createdAt.toISOString(), + resolvedAt: row.resolvedAt ? row.resolvedAt.toISOString() : null, + }; +} + +function serializeScheduleRow( + row: typeof scheduledBoardPosts.$inferSelect, + cursor?: string, +): ScheduleView { + return { + id: row.id, + companyId: row.companyId, + target: row.target, + message: row.message, + nextRunAt: row.nextRunAt.toISOString(), + intervalMs: row.intervalMs ?? null, + untilAt: row.untilAt ? row.untilAt.toISOString() : null, + post: row.postOnly, + status: row.status, + ...(cursor ? { cursor } : {}), + createdAt: row.createdAt.toISOString(), + }; +} + +async function resolveAddresseeAgentId( + dbOrTx: DbOrTx, + companyId: string, + agentRef: string, +): Promise { + const trimmed = agentRef.trim(); + if (isUuidLike(trimmed)) { + const [row] = await dbOrTx + .select({ id: agents.id }) + .from(agents) + .where( + and( + eq(agents.companyId, companyId), + eq(agents.id, trimmed), + ne(agents.status, "terminated"), + ), + ); + if (!row) { + throw notFound(`Agent '${agentRef}' not found`); + } + return row.id; + } + + const companyAgents = await dbOrTx + .select({ id: agents.id, name: agents.name }) + .from(agents) + .where(and(eq(agents.companyId, companyId), ne(agents.status, "terminated"))); + + const lower = trimmed.replace(/^@/, "").toLowerCase(); + const match = companyAgents.find( + (a) => + a.name.trim().toLowerCase() === lower || + deriveAgentUrlKey(a.name, a.id).toLowerCase() === lower, + ); + if (!match) { + throw notFound(`Agent '${agentRef}' not found`); + } + return match.id; +} + +export async function askOnIssue( + db: Db, + issueId: string, + actor: HeadlessActorContext, + rawInput: unknown, + headerToken?: string, +): Promise { + enforceHeadlessScopes(actor, { action: "interactions.create" }); + const input = OneLineAskSchema.parse(rawInput ?? {}); + const token = extractClaimToken(input.claimToken, headerToken); + + const committed = await db.transaction(async (tx) => { + await tx.execute( + sql`SELECT id FROM issues WHERE id = ${issueId} AND company_id = ${actor.companyId} FOR UPDATE`, + ); + const [issue] = await tx + .select() + .from(issues) + .where(and(eq(issues.id, issueId), eq(issues.companyId, actor.companyId))); + if (!issue) { + throw notFound("Issue not found"); + } + + const { channel: targetChannel } = await assertIssueChannelScopeAccess( + tx, + issue, + actor, + ); + + if (input.idempotencyKey) { + const [existing] = await tx + .select() + .from(issueThreadInteractions) + .where( + and( + eq(issueThreadInteractions.companyId, issue.companyId), + eq(issueThreadInteractions.issueId, issue.id), + eq(issueThreadInteractions.idempotencyKey, input.idempotencyKey), + ), + ) + .limit(1); + if (existing) { + const cursor = await getLatestCompanyEventCursor(tx, issue.companyId); + return { + events: [] as BoardEventView[], + view: serializeInteractionRow( + existing, + issue.identifier ?? issue.id, + cursor, + ), + }; + } + } + + if (issue.claimTokenHash !== null) { + const epochMatches = + input.claimEpoch === undefined || Number(issue.claimEpoch ?? 0) === input.claimEpoch; + if (!token || !verifyClaimToken(issue.claimTokenHash, token) || !epochMatches) { + throw conflict("claim_lost", { + code: "claim_lost", + currentEpoch: Number(issue.claimEpoch ?? 0), + status: issue.status, + }); + } + } else if (token !== undefined) { + throw conflict("claim_lost", { + code: "claim_lost", + currentEpoch: Number(issue.claimEpoch ?? 0), + status: issue.status, + }); + } + + const addresseeAgentId = input.agent + ? await resolveAddresseeAgentId(tx, issue.companyId, input.agent) + : null; + + const isClaimedPoolTask = + issue.claimTokenHash !== null && issue.assigneeAgentId === null; + const isUnassignedTask = + issue.assigneeAgentId === null && + issue.assigneeUserId === null && + issue.status !== "backlog"; + const continuationPolicy = + input.continuationPolicy ?? + (isClaimedPoolTask || isUnassignedTask ? "requeue_on_resolve" : "wake_assignee"); + const resolverPolicy = input.humanOnly ? "human_only" : "anyone"; + + const payload: AskUserQuestionsPayload = { + version: 1, + title: null, + questions: [ + { + id: "q1", + prompt: input.question, + selectionMode: "single", + required: true, + allowOther: true, + options: (input.choices ?? []).map((choice, idx) => ({ + id: `opt_${idx + 1}`, + label: choice, + })), + }, + ], + }; + + const [comment] = await tx + .insert(issueComments) + .values({ + companyId: issue.companyId, + issueId: issue.id, + body: input.question, + authorType: actor.principalType === "agent" ? "agent" : "user", + authorAgentId: actor.agentId ?? null, + authorUserId: actor.agentId ? null : (actor.userId ?? null), + actorProfile: actor.actorProfile ?? null, + }) + .returning(); + + const [interaction] = await tx + .insert(issueThreadInteractions) + .values({ + companyId: issue.companyId, + issueId: issue.id, + kind: "ask_user_questions", + status: "pending", + continuationPolicy, + requestedResolverPolicy: resolverPolicy, + effectiveResolverPolicy: resolverPolicy, + resolverPolicyProvenance: "inherited", + effectiveResolverPolicySource: "requested", + idempotencyKey: input.idempotencyKey ?? null, + sourceCommentId: comment!.id, + title: input.question.slice(0, 140), + createdByAgentId: actor.agentId ?? null, + createdByUserId: actor.agentId ? null : (actor.userId ?? null), + addresseeAgentId, + payload: payload as IssueThreadInteractionPayload, + }) + .returning(); + + const now = new Date(); + if (isClaimedPoolTask) { + await notifyDeliveryWork(tx, DELIVERY_QUEUES.claimLeaseExpiry, issue.id); + await tx + .update(issues) + .set({ + status: "blocked", + blockedTransitionAt: now, + claimEpoch: Number(issue.claimEpoch ?? 0) + 1, + claimTokenHash: null, + claimLeasedAt: null, + claimLeaseExpiresAt: null, + claimHolderAgentId: null, + claimHolderUserId: null, + claimHolderProfile: null, + claimAttemptCount: Math.max(0, (issue.claimAttemptCount ?? 0) - 1), + updatedAt: now, + }) + .where(eq(issues.id, issue.id)); + } else if (issue.status !== "blocked") { + await tx + .update(issues) + .set({ + status: "blocked", + blockedTransitionAt: now, + updatedAt: now, + }) + .where(eq(issues.id, issue.id)); + } + + await tx.insert(activityLog).values({ + companyId: issue.companyId, + actorType: actor.principalType === "agent" ? "agent" : "user", + actorId: + actor.principalType === "agent" + ? actor.agentId ?? "unknown-agent" + : actor.userId ?? "board", + agentId: actor.agentId ?? null, + responsibleUserId: actor.responsibleUserId ?? null, + action: "issue.thread_interaction_created", + entityType: "issue", + entityId: issue.id, + details: { + interactionId: interaction!.id, + kind: interaction!.kind, + resolverPolicy, + continuationPolicy, + }, + }); + + const events: BoardEventView[] = []; + const createdEvent = await appendBoardEvent(tx, { + companyId: issue.companyId, + type: "interaction.created", + channelId: issue.channelId, + channelPath: targetChannel?.path ?? null, + issueId: issue.id, + identifier: issue.identifier ?? issue.id, + actor, + payload: { + interactionId: interaction!.id, + kind: "ask_user_questions", + resolverPolicy, + continuationPolicy, + question: input.question, + }, + }); + events.push(createdEvent); + + const blockedEvent = await appendBoardEvent(tx, { + companyId: issue.companyId, + type: "task.blocked", + channelId: issue.channelId, + channelPath: targetChannel?.path ?? null, + issueId: issue.id, + identifier: issue.identifier ?? issue.id, + actor, + payload: { + reason: "awaiting_interaction", + interactionId: interaction!.id, + }, + }); + events.push(blockedEvent); + + return { + events, + view: serializeInteractionRow( + interaction!, + issue.identifier ?? issue.id, + blockedEvent.cursor, + ), + }; + }); + + for (const ev of committed.events) { + publishCommittedBoardEvent(ev); + } + return committed.view; +} + +export async function confirmOnIssue( + db: Db, + issueId: string, + actor: HeadlessActorContext, + rawInput: unknown, + headerToken?: string, +): Promise { + enforceHeadlessScopes(actor, { action: "interactions.create" }); + const input = OneLineConfirmSchema.parse(rawInput ?? {}); + const token = extractClaimToken(input.claimToken, headerToken); + + const committed = await db.transaction(async (tx) => { + await tx.execute( + sql`SELECT id FROM issues WHERE id = ${issueId} AND company_id = ${actor.companyId} FOR UPDATE`, + ); + const [issue] = await tx + .select() + .from(issues) + .where(and(eq(issues.id, issueId), eq(issues.companyId, actor.companyId))); + if (!issue) { + throw notFound("Issue not found"); + } + + const { channel: targetChannel } = await assertIssueChannelScopeAccess( + tx, + issue, + actor, + ); + + if (input.idempotencyKey) { + const [existing] = await tx + .select() + .from(issueThreadInteractions) + .where( + and( + eq(issueThreadInteractions.companyId, issue.companyId), + eq(issueThreadInteractions.issueId, issue.id), + eq(issueThreadInteractions.idempotencyKey, input.idempotencyKey), + ), + ) + .limit(1); + if (existing) { + const cursor = await getLatestCompanyEventCursor(tx, issue.companyId); + return { + events: [] as BoardEventView[], + view: serializeInteractionRow( + existing, + issue.identifier ?? issue.id, + cursor, + ), + }; + } + } + + if (issue.claimTokenHash !== null) { + const epochMatches = + input.claimEpoch === undefined || Number(issue.claimEpoch ?? 0) === input.claimEpoch; + if (!token || !verifyClaimToken(issue.claimTokenHash, token) || !epochMatches) { + throw conflict("claim_lost", { + code: "claim_lost", + currentEpoch: Number(issue.claimEpoch ?? 0), + status: issue.status, + }); + } + } else if (token !== undefined) { + throw conflict("claim_lost", { + code: "claim_lost", + currentEpoch: Number(issue.claimEpoch ?? 0), + status: issue.status, + }); + } + + const isClaimedPoolTask = + issue.claimTokenHash !== null && issue.assigneeAgentId === null; + const isUnassignedTask = + issue.assigneeAgentId === null && + issue.assigneeUserId === null && + issue.status !== "backlog"; + const continuationPolicy = + input.continuationPolicy ?? + (input.wakeOnAccept + ? "wake_assignee_on_accept" + : isClaimedPoolTask || isUnassignedTask + ? "requeue_on_resolve" + : "wake_assignee"); + const resolverPolicy = input.humanOnly ? "human_only" : "anyone"; + + const payload: RequestConfirmationPayload = { + version: 1, + prompt: input.prompt, + allowDeclineReason: true, + }; + + const [comment] = await tx + .insert(issueComments) + .values({ + companyId: issue.companyId, + issueId: issue.id, + body: input.prompt, + authorType: actor.principalType === "agent" ? "agent" : "user", + authorAgentId: actor.agentId ?? null, + authorUserId: actor.agentId ? null : (actor.userId ?? null), + actorProfile: actor.actorProfile ?? null, + }) + .returning(); + + const [interaction] = await tx + .insert(issueThreadInteractions) + .values({ + companyId: issue.companyId, + issueId: issue.id, + kind: "request_confirmation", + status: "pending", + continuationPolicy, + requestedResolverPolicy: resolverPolicy, + effectiveResolverPolicy: resolverPolicy, + resolverPolicyProvenance: "inherited", + effectiveResolverPolicySource: "requested", + idempotencyKey: input.idempotencyKey ?? null, + sourceCommentId: comment!.id, + title: input.prompt.slice(0, 140), + createdByAgentId: actor.agentId ?? null, + createdByUserId: actor.agentId ? null : (actor.userId ?? null), + payload: payload as IssueThreadInteractionPayload, + }) + .returning(); + + const now = new Date(); + if (isClaimedPoolTask) { + await notifyDeliveryWork(tx, DELIVERY_QUEUES.claimLeaseExpiry, issue.id); + await tx + .update(issues) + .set({ + status: "blocked", + blockedTransitionAt: now, + claimEpoch: Number(issue.claimEpoch ?? 0) + 1, + claimTokenHash: null, + claimLeasedAt: null, + claimLeaseExpiresAt: null, + claimHolderAgentId: null, + claimHolderUserId: null, + claimHolderProfile: null, + claimAttemptCount: Math.max(0, (issue.claimAttemptCount ?? 0) - 1), + updatedAt: now, + }) + .where(eq(issues.id, issue.id)); + } else if (issue.status !== "blocked") { + await tx + .update(issues) + .set({ + status: "blocked", + blockedTransitionAt: now, + updatedAt: now, + }) + .where(eq(issues.id, issue.id)); + } + + await tx.insert(activityLog).values({ + companyId: issue.companyId, + actorType: actor.principalType === "agent" ? "agent" : "user", + actorId: + actor.principalType === "agent" + ? actor.agentId ?? "unknown-agent" + : actor.userId ?? "board", + agentId: actor.agentId ?? null, + responsibleUserId: actor.responsibleUserId ?? null, + action: "issue.thread_interaction_created", + entityType: "issue", + entityId: issue.id, + details: { + interactionId: interaction!.id, + kind: interaction!.kind, + resolverPolicy, + continuationPolicy, + }, + }); + + const events: BoardEventView[] = []; + const createdEvent = await appendBoardEvent(tx, { + companyId: issue.companyId, + type: "interaction.created", + channelId: issue.channelId, + channelPath: targetChannel?.path ?? null, + issueId: issue.id, + identifier: issue.identifier ?? issue.id, + actor, + payload: { + interactionId: interaction!.id, + kind: "request_confirmation", + resolverPolicy, + continuationPolicy, + prompt: input.prompt, + }, + }); + events.push(createdEvent); + + const blockedEvent = await appendBoardEvent(tx, { + companyId: issue.companyId, + type: "task.blocked", + channelId: issue.channelId, + channelPath: targetChannel?.path ?? null, + issueId: issue.id, + identifier: issue.identifier ?? issue.id, + actor, + payload: { + reason: "awaiting_confirmation", + interactionId: interaction!.id, + }, + }); + events.push(blockedEvent); + + return { + events, + view: serializeInteractionRow( + interaction!, + issue.identifier ?? issue.id, + blockedEvent.cursor, + ), + }; + }); + + for (const ev of committed.events) { + publishCommittedBoardEvent(ev); + } + return committed.view; +} + +async function resolveInteractionOnIssue( + db: Db, + issueId: string, + actor: HeadlessActorContext, + rawInput: unknown, + decision: "approve" | "reject", + opts: { + onWakeAssignee?: (input: { + companyId: string; + issueId: string; + assigneeAgentId: string; + interactionId: string; + interactionKind: string; + interactionStatus: string; + sourceCommentId: string | null; + actor: HeadlessActorContext; + }) => Promise; + } = {}, +): Promise { + enforceHeadlessScopes(actor, { action: "interactions.resolve" }); + const input = ResolveInteractionInputSchema.parse(rawInput ?? {}); + + const committed = await db.transaction(async (tx) => { + await tx.execute( + sql`SELECT id FROM issues WHERE id = ${issueId} AND company_id = ${actor.companyId} FOR UPDATE`, + ); + const [issue] = await tx + .select() + .from(issues) + .where(and(eq(issues.id, issueId), eq(issues.companyId, actor.companyId))); + if (!issue) { + throw notFound("Issue not found"); + } + + const { channel: targetChannel } = await assertIssueChannelScopeAccess( + tx, + issue, + actor, + ); + + let interaction: typeof issueThreadInteractions.$inferSelect | undefined; + if (input.interactionId) { + [interaction] = await tx + .select() + .from(issueThreadInteractions) + .where( + and( + eq(issueThreadInteractions.companyId, issue.companyId), + eq(issueThreadInteractions.issueId, issue.id), + eq(issueThreadInteractions.id, input.interactionId), + ), + ); + if (!interaction) { + throw notFound("Interaction not found"); + } + if (interaction.status !== "pending") { + throw conflict("Interaction is already resolved", { + code: "interaction_already_resolved", + status: interaction.status, + }); + } + } else { + [interaction] = await tx + .select() + .from(issueThreadInteractions) + .where( + and( + eq(issueThreadInteractions.companyId, issue.companyId), + eq(issueThreadInteractions.issueId, issue.id), + eq(issueThreadInteractions.status, "pending"), + ), + ) + .orderBy(desc(issueThreadInteractions.createdAt)) + .limit(1); + if (!interaction) { + throw notFound("No pending interaction found on issue"); + } + } + + if ( + interaction.kind !== "ask_user_questions" && + interaction.kind !== "request_confirmation" + ) { + throw unprocessable( + `One-line ${decision} only supports questions and confirmation requests (got '${interaction.kind}')`, + ); + } + + const rawPayload = + interaction.payload && typeof interaction.payload === "object" + ? (interaction.payload as unknown as Record) + : {}; + const isGovernedAction = + interaction.kind === "request_confirmation" && + (rawPayload.toolAction !== undefined || rawPayload.secretProposal !== undefined); + + if ( + isGovernedAction || + (interaction.effectiveResolverPolicy === "human_only" && + actor.principalType === "agent") + ) { + throw forbidden("This interaction requires a human resolver", { + code: "human_resolver_required", + }); + } + + if (interaction.addresseeUserId) { + if (actor.agentId || !actor.userId || actor.userId !== interaction.addresseeUserId) { + throw forbidden("Only the addressed user may resolve this interaction", { + code: "interaction_addressee_mismatch", + }); + } + } + if (interaction.addresseeAgentId && actor.agentId) { + if (actor.agentId !== interaction.addresseeAgentId) { + throw forbidden("Only the addressed agent or a board user may resolve this interaction", { + code: "interaction_addressee_mismatch", + }); + } + } + + if (interaction.effectiveResolverPolicy === "not_creator") { + const sameAgent = + actor.agentId && interaction.createdByAgentId === actor.agentId; + const sameUser = + !actor.agentId && actor.userId && interaction.createdByUserId === actor.userId; + if (sameAgent || sameUser) { + throw forbidden("Interaction creator cannot resolve their own request", { + code: "creator_cannot_resolve", + }); + } + } + + const now = new Date(); + const isAsk = interaction.kind === "ask_user_questions"; + const nextStatus = + decision === "approve" ? (isAsk ? "answered" : "accepted") : "rejected"; + + const resolutionText = + decision === "approve" + ? input.answer ?? input.note ?? null + : input.reason ?? input.note ?? null; + + let result: IssueThreadInteractionResult; + if (isAsk) { + const questions = Array.isArray((interaction.payload as AskUserQuestionsPayload)?.questions) + ? (interaction.payload as AskUserQuestionsPayload).questions + : []; + if (decision === "approve" && questions.length > 1) { + throw unprocessable( + "Multi-question asks cannot be resolved with a single one-line answer; respond through /api/issues/:id/interactions/:interactionId/respond", + ); + } + const singleQuestionId = questions[0]?.id ?? "q1"; + result = + decision === "approve" + ? ({ + version: 1, + answers: resolutionText + ? [ + { + questionId: singleQuestionId, + optionIds: [], + otherText: resolutionText, + }, + ] + : [], + summaryMarkdown: resolutionText, + } satisfies AskUserQuestionsResult) + : ({ + version: 1, + outcome: "skipped", + reason: resolutionText, + answers: [], + } satisfies AskUserQuestionsResult); + } else { + result = ({ + version: 1, + outcome: decision === "approve" ? "accepted" : "rejected", + reason: resolutionText, + } satisfies RequestConfirmationResult); + } + + const commentBody = + decision === "approve" + ? resolutionText ?? "Approved" + : resolutionText + ? `Rejected: ${resolutionText}` + : "Rejected"; + + const [comment] = await tx + .insert(issueComments) + .values({ + companyId: issue.companyId, + issueId: issue.id, + body: commentBody, + authorType: actor.principalType === "agent" ? "agent" : "user", + authorAgentId: actor.agentId ?? null, + authorUserId: actor.agentId ? null : (actor.userId ?? null), + actorProfile: actor.actorProfile ?? null, + }) + .returning(); + + const resultWithComment = { + ...result, + commentId: comment!.id, + } as IssueThreadInteractionResult; + + const [updatedInteraction] = await tx + .update(issueThreadInteractions) + .set({ + status: nextStatus, + result: resultWithComment, + resolvedByAgentId: actor.agentId ?? null, + resolvedByUserId: actor.agentId ? null : (actor.userId ?? null), + resolvedAt: now, + updatedAt: now, + }) + .where( + and( + eq(issueThreadInteractions.id, interaction.id), + eq(issueThreadInteractions.status, "pending"), + ), + ) + .returning(); + + if (!updatedInteraction) { + throw conflict("Interaction is already resolved", { + code: "interaction_already_resolved", + }); + } + + await tx.insert(activityLog).values({ + companyId: issue.companyId, + actorType: actor.principalType === "agent" ? "agent" : "user", + actorId: + actor.principalType === "agent" + ? actor.agentId ?? "unknown-agent" + : actor.userId ?? "board", + agentId: actor.agentId ?? null, + responsibleUserId: actor.responsibleUserId ?? null, + action: + decision === "approve" + ? isAsk + ? "issue.thread_interaction_answered" + : "issue.thread_interaction_accepted" + : "issue.thread_interaction_rejected", + entityType: "issue", + entityId: issue.id, + details: { + interactionId: updatedInteraction.id, + kind: updatedInteraction.kind, + status: nextStatus, + decision, + }, + }); + + const events: BoardEventView[] = []; + const resolvedEvent = await appendBoardEvent(tx, { + companyId: issue.companyId, + type: "interaction.resolved", + channelId: issue.channelId, + channelPath: targetChannel?.path ?? null, + issueId: issue.id, + identifier: issue.identifier ?? issue.id, + actor, + payload: { + interactionId: updatedInteraction.id, + kind: updatedInteraction.kind, + status: nextStatus, + decision, + ...(resolutionText ? { note: resolutionText } : {}), + }, + }); + events.push(resolvedEvent); + + const policyAllowsRequeue = + decision === "approve" && + interaction.continuationPolicy === "requeue_on_resolve"; + const policyAllowsAssigneeResume = + Boolean(issue.assigneeAgentId) && + (interaction.continuationPolicy === "wake_assignee" || + (interaction.continuationPolicy === "wake_assignee_on_accept" && + decision === "approve")); + + let wakeAssigneeAgentId: string | null = null; + if ((policyAllowsRequeue || policyAllowsAssigneeResume) && issue.status === "blocked") { + const [otherPending] = await tx + .select({ id: issueThreadInteractions.id }) + .from(issueThreadInteractions) + .where( + and( + eq(issueThreadInteractions.companyId, issue.companyId), + eq(issueThreadInteractions.issueId, issue.id), + eq(issueThreadInteractions.status, "pending"), + ), + ) + .limit(1); + + const readiness = ( + await listIssueDependencyReadinessMap( + tx as unknown as Db, + issue.companyId, + [issue.id], + false, + ) + ).get(issue.id); + + if (!otherPending && (!readiness || readiness.isDependencyReady)) { + await tx + .update(issues) + .set({ + status: "todo", + updatedAt: now, + }) + .where(eq(issues.id, issue.id)); + + events.push( + await appendBoardEvent(tx, { + companyId: issue.companyId, + type: "task.unblocked", + channelId: issue.channelId, + channelPath: targetChannel?.path ?? null, + issueId: issue.id, + identifier: issue.identifier ?? issue.id, + actor, + payload: { + interactionId: updatedInteraction.id, + kvLabels: issue.kvLabels ?? {}, + }, + }), + ); + events.push( + await appendBoardEvent(tx, { + companyId: issue.companyId, + type: "task.ready", + channelId: issue.channelId, + channelPath: targetChannel?.path ?? null, + issueId: issue.id, + identifier: issue.identifier ?? issue.id, + actor, + payload: { + interactionId: updatedInteraction.id, + kvLabels: issue.kvLabels ?? {}, + }, + }), + ); + } + } + + if (policyAllowsAssigneeResume && issue.assigneeAgentId && issue.status !== "done" && issue.status !== "cancelled") { + wakeAssigneeAgentId = issue.assigneeAgentId; + } + + const lastCursor = events[events.length - 1]!.cursor; + return { + events, + wakeAssigneeAgentId, + interactionId: updatedInteraction.id, + interactionKind: updatedInteraction.kind, + interactionStatus: updatedInteraction.status, + sourceCommentId: updatedInteraction.sourceCommentId ?? null, + companyId: issue.companyId, + issueId: issue.id, + view: serializeInteractionRow( + updatedInteraction, + issue.identifier ?? issue.id, + lastCursor, + ), + }; + }); + + for (const ev of committed.events) { + publishCommittedBoardEvent(ev); + } + if (committed.wakeAssigneeAgentId && opts.onWakeAssignee) { + try { + await opts.onWakeAssignee({ + companyId: committed.companyId, + issueId: committed.issueId, + assigneeAgentId: committed.wakeAssigneeAgentId, + interactionId: committed.interactionId, + interactionKind: committed.interactionKind, + interactionStatus: committed.interactionStatus, + sourceCommentId: committed.sourceCommentId, + actor, + }); + } catch (err) { + logger.warn({ err, issueId: committed.issueId }, "Failed to wake assignee after interaction resolution"); + } + } + return committed.view; +} + +export async function approveOnIssue( + db: Db, + issueId: string, + actor: HeadlessActorContext, + rawInput: unknown, + opts?: Parameters[5], +): Promise { + return resolveInteractionOnIssue(db, issueId, actor, rawInput, "approve", opts); +} + +export async function rejectOnIssue( + db: Db, + issueId: string, + actor: HeadlessActorContext, + rawInput: unknown, + opts?: Parameters[5], +): Promise { + return resolveInteractionOnIssue(db, issueId, actor, rawInput, "reject", opts); +} + +export function parseBoardEventFilters( + filters: BoardEventFilterInput, +): ParsedBoardEventFilters { + let afterSeq = 0; + let hasExplicitAfter = false; + if (filters.after !== undefined && filters.after.trim() !== "") { + const parsed = parseEventCursor(filters.after); + if (parsed === null) { + throw badRequest( + `Invalid cursor "${filters.after}": expected evt_`, + ); + } + afterSeq = parsed; + hasExplicitAfter = true; + } + + let channelNorm: { path: string; isSubtreePrefix: boolean } | null = null; + if (filters.channel && filters.channel.trim() !== "") { + try { + channelNorm = normalizeChannelPath(filters.channel, { + allowSubtreePrefix: true, + }); + } catch (err) { + throw badRequest(err instanceof Error ? err.message : "Invalid channel"); + } + } + + let issueUuid: string | null = null; + let issueIdentifierUpper: string | null = null; + if (filters.issueId && filters.issueId.trim() !== "") { + const trimmed = filters.issueId.trim(); + if (isUuidLike(trimmed)) { + issueUuid = trimmed.toLowerCase(); + } else { + issueIdentifierUpper = ( + normalizeIssueIdentifier(trimmed) ?? trimmed + ).toUpperCase(); + } + } + + let eventTypes: Set | null = null; + if (filters.event && filters.event.length > 0) { + eventTypes = new Set(); + for (const raw of filters.event) { + const parsed = boardEventTypeSchema.safeParse(raw); + if (!parsed.success) { + throw badRequest(`Invalid board event type "${raw}"`); + } + eventTypes.add(parsed.data); + } + } + + const labelExprs: LabelFilterExpr[] = []; + if (filters.label && filters.label.length > 0) { + for (const raw of filters.label) { + try { + labelExprs.push(parseLabelFilterExpr(raw)); + } catch (err) { + throw badRequest( + err instanceof Error ? err.message : "Invalid label filter", + ); + } + } + } + + let mentionsName: string | null = null; + if (filters.mentions && filters.mentions.trim() !== "") { + mentionsName = filters.mentions.trim().replace(/^@/, "").toLowerCase(); + } + + let schemaFilter: { name: string; version: number | null } | null = null; + if (filters.schema && filters.schema.trim() !== "") { + const rawSchema = filters.schema.trim(); + if (rawSchema.includes("@")) { + try { + const parsed = parseSchemaRef(rawSchema); + schemaFilter = { name: parsed.name, version: parsed.version }; + } catch (err) { + throw badRequest( + err instanceof Error ? err.message : "Invalid schema filter", + ); + } + } else { + schemaFilter = { name: rawSchema, version: null }; + } + } + + return { + afterSeq, + hasExplicitAfter, + channelNorm, + issueUuid, + issueIdentifierUpper, + eventTypes, + labelExprs, + mentionsName, + schemaFilter, + }; +} + +export async function getCurrentCompanyMaxEventSeq( + dbOrTx: DbOrTx, + companyId: string, +): Promise { + const cursor = await getLatestCompanyEventCursor(dbOrTx, companyId); + return parseEventCursor(cursor) ?? 0; +} + +function serializeBoardEventRow( + row: typeof boardEvents.$inferSelect, +): BoardEventView { + const seq = Number(row.seq); + return { + cursor: formatEventCursor(seq), + seq, + type: row.eventType, + companyId: row.companyId, + channel: row.channelPath ?? null, + issueId: row.issueId ?? null, + identifier: row.identifier ?? null, + actor: { + type: row.actorType, + id: row.actorId ?? null, + name: row.actorName ?? null, + profile: row.actorProfile ?? null, + }, + payload: (row.payload ?? {}) as Record, + createdAt: row.createdAt.toISOString(), + }; +} + +function matchesNonDbEventFilters( + ev: BoardEventView, + parsed: ParsedBoardEventFilters, +): boolean { + if (ev.seq <= parsed.afterSeq) return false; + + if (parsed.eventTypes && !parsed.eventTypes.has(ev.type)) { + return false; + } + + if (parsed.channelNorm) { + if (!ev.channel) return false; + if (parsed.channelNorm.isSubtreePrefix) { + if ( + ev.channel !== parsed.channelNorm.path && + !ev.channel.startsWith(`${parsed.channelNorm.path}/`) + ) { + return false; + } + } else if (ev.channel !== parsed.channelNorm.path) { + return false; + } + } + + if (parsed.issueUuid) { + if (!ev.issueId || ev.issueId.toLowerCase() !== parsed.issueUuid) { + return false; + } + } else if (parsed.issueIdentifierUpper) { + if ( + !ev.identifier || + ev.identifier.toUpperCase() !== parsed.issueIdentifierUpper + ) { + return false; + } + } + + if (parsed.mentionsName) { + const mentionRegex = new RegExp( + `(^|\\s)@${escapeRegExp(parsed.mentionsName)}(\\b|$)`, + "i", + ); + const candidateTexts = [ + ev.payload.text, + ev.payload.body, + ev.payload.title, + ev.payload.message, + ev.payload.description, + ].filter((v): v is string => typeof v === "string"); + if (!candidateTexts.some((txt) => mentionRegex.test(txt))) { + return false; + } + } + + if (parsed.schemaFilter) { + const blocks = Array.isArray(ev.payload.blocks) + ? (ev.payload.blocks as Array>) + : []; + const matched = blocks.some( + (b) => + b && + b.schema === parsed.schemaFilter!.name && + (parsed.schemaFilter!.version === null || + b.version === parsed.schemaFilter!.version), + ); + if (!matched) { + return false; + } + } + + return true; +} + +async function canActorAccessEventChannel( + db: Db, + companyId: string, + actor: HeadlessActorContext, + channelPath: string | null, + cache?: Map, +): Promise { + if (!channelPath) return true; + if (!isChannelAllowedByScopes(actor, channelPath)) return false; + + const cached = cache?.get(channelPath); + if (cached !== undefined) return cached; + + const [ch] = await db + .select({ + id: channels.id, + companyId: channels.companyId, + visibility: channels.visibility, + createdByUserId: channels.createdByUserId, + createdByAgentId: channels.createdByAgentId, + }) + .from(channels) + .where(and(eq(channels.companyId, companyId), eq(channels.path, channelPath))) + .limit(1); + + const allowed = ch ? await canAccessChannel(db, ch, actor) : true; + cache?.set(channelPath, allowed); + return allowed; +} + +async function eventMatchesLabelFilters( + db: Db, + ev: BoardEventView, + labelExprs: LabelFilterExpr[], + issueLabelCache: Map< + string, + { kvLabels: Record; tagLabels: string[] } + >, +): Promise { + if (ev.type === "labels.changed" && ev.issueId) { + issueLabelCache.delete(ev.issueId); + } + if (labelExprs.length === 0) return true; + + let kvLabels = + ev.payload.kvLabels && + typeof ev.payload.kvLabels === "object" && + !Array.isArray(ev.payload.kvLabels) + ? (ev.payload.kvLabels as Record) + : ev.payload.current && + typeof ev.payload.current === "object" && + !Array.isArray(ev.payload.current) + ? (ev.payload.current as Record) + : null; + let tagLabels = Array.isArray(ev.payload.tagLabels) + ? (ev.payload.tagLabels.filter((x): x is string => typeof x === "string")) + : undefined; + + if ( + !ev.payload.kvLabels && + !( + ev.payload.current && + typeof ev.payload.current === "object" && + !Array.isArray(ev.payload.current) + ) && + ev.issueId + ) { + // Re-check issue labels if not carried on payload + let cached = issueLabelCache.get(ev.issueId); + if (!cached) { + const [issueRow] = await db + .select({ kvLabels: issues.kvLabels }) + .from(issues) + .where(eq(issues.id, ev.issueId)) + .limit(1); + const tagRows = await db + .select({ name: labels.name }) + .from(issueLabels) + .innerJoin(labels, eq(issueLabels.labelId, labels.id)) + .where(eq(issueLabels.issueId, ev.issueId)); + cached = { + kvLabels: (issueRow?.kvLabels ?? {}) as Record, + tagLabels: tagRows.map((t) => t.name), + }; + issueLabelCache.set(ev.issueId, cached); + } + kvLabels = cached.kvLabels; + tagLabels = cached.tagLabels; + } + + const effectiveKv = kvLabels ?? {}; + return labelExprs.every((expr) => + matchesLabelFilter(effectiveKv, tagLabels, expr), + ); +} + +export async function eventMatchesFiltersAndAccess( + db: Db, + companyId: string, + actor: HeadlessActorContext, + ev: BoardEventView, + parsed: ParsedBoardEventFilters, + channelCache?: Map, + issueLabelCache = new Map< + string, + { kvLabels: Record; tagLabels: string[] } + >(), + readableIssueIds?: Set, + authActor?: AuthorizationActor, +): Promise { + if (ev.type === "labels.changed" && ev.issueId) { + issueLabelCache.delete(ev.issueId); + } + if (!matchesNonDbEventFilters(ev, parsed)) return false; + if (!(await canActorAccessEventChannel(db, companyId, actor, ev.channel, channelCache))) { + return false; + } + if (ev.issueId) { + if (readableIssueIds) { + if (!readableIssueIds.has(ev.issueId)) { + return false; + } + } else { + const effectiveAuthActor = authActor ?? buildAuthActorFromHeadless(actor); + const readCondition = await issueReadSqlCondition(db, effectiveAuthActor); + const [readable] = await db + .select({ id: issues.id }) + .from(issues) + .where( + and( + eq(issues.companyId, companyId), + eq(issues.id, ev.issueId), + readCondition, + ), + ) + .limit(1); + if (!readable) { + return false; + } + } + } + if (!(await eventMatchesLabelFilters(db, ev, parsed.labelExprs, issueLabelCache))) { + return false; + } + return true; +} + +export async function queryBoardEventsAfter( + db: Db, + companyId: string, + actor: HeadlessActorContext, + filtersOrParsed: BoardEventFilterInput | ParsedBoardEventFilters, + opts: { limit?: number; authActor?: AuthorizationActor } = {}, +): Promise { + enforceHeadlessScopes(actor, { action: "events.read" }); + const parsed = + "afterSeq" in filtersOrParsed + ? filtersOrParsed + : parseBoardEventFilters(filtersOrParsed); + const limit = Math.min(Math.max(1, opts.limit ?? 100), 500); + const effectiveAuthActor = opts.authActor ?? buildAuthActorFromHeadless(actor); + const channelCache = new Map(); + const issueLabelCache = new Map< + string, + { kvLabels: Record; tagLabels: string[] } + >(); + + const results: BoardEventView[] = []; + let cursorSeq = parsed.afterSeq; + const batchSize = 200; + + while (results.length < limit) { + const conditions = [ + eq(boardEvents.companyId, companyId), + gt(boardEvents.seq, cursorSeq), + ]; + if (parsed.eventTypes && parsed.eventTypes.size > 0) { + conditions.push(inArray(boardEvents.eventType, Array.from(parsed.eventTypes))); + } + if (parsed.issueUuid) { + conditions.push(eq(boardEvents.issueId, parsed.issueUuid)); + } + + const rows = await db + .select() + .from(boardEvents) + .where(and(...conditions)) + .orderBy(asc(boardEvents.seq)) + .limit(batchSize); + + if (rows.length === 0) break; + + const batchIssueIds = Array.from( + new Set(rows.map((r) => r.issueId).filter((id): id is string => Boolean(id))), + ); + const readableIssueIds = new Set(); + if (batchIssueIds.length > 0) { + const readCondition = await issueReadSqlCondition(db, effectiveAuthActor); + const readableRows = await db + .select({ id: issues.id }) + .from(issues) + .where( + and( + eq(issues.companyId, companyId), + inArray(issues.id, batchIssueIds), + readCondition, + ), + ); + for (const r of readableRows) { + readableIssueIds.add(r.id); + } + } + + for (const row of rows) { + const ev = serializeBoardEventRow(row); + cursorSeq = Math.max(cursorSeq, ev.seq); + if ( + await eventMatchesFiltersAndAccess( + db, + companyId, + actor, + ev, + parsed, + channelCache, + issueLabelCache, + readableIssueIds, + effectiveAuthActor, + ) + ) { + results.push(ev); + if (results.length >= limit) break; + } + } + + if (rows.length < batchSize) break; + } + + return results; +} + +export async function waitForBoardEvent( + db: Db, + companyId: string, + actor: HeadlessActorContext, + filters: BoardEventFilterInput, + opts: { + timeoutMs?: number; + signal?: AbortSignal; + authActor?: AuthorizationActor; + onResolvedCursor?: (cursor: string) => void; + } = {}, +): Promise { + enforceHeadlessScopes(actor, { action: "events.read" }); + const parsed = parseBoardEventFilters(filters); + const timeoutMs = Math.min(Math.max(0, opts.timeoutMs ?? 30_000), 120_000); + const effectiveAuthActor = opts.authActor ?? buildAuthActorFromHeadless(actor); + const channelCache = new Map(); + const issueLabelCache = new Map< + string, + { kvLabels: Record; tagLabels: string[] } + >(); + + const buffered: BoardEventView[] = []; + let checkingInitial = true; + let resolveWaiter: ((ev: BoardEventView | null) => void) | null = null; + + const unsubscribe = subscribeCompanyBoardEvents(companyId, (ev) => { + if (checkingInitial) { + buffered.push(ev); + return; + } + if (ev.seq <= parsed.afterSeq) return; + void eventMatchesFiltersAndAccess( + db, + companyId, + actor, + ev, + parsed, + channelCache, + issueLabelCache, + undefined, + effectiveAuthActor, + ) + .then((ok) => { + if (ok && resolveWaiter) { + const resolveFn = resolveWaiter; + resolveWaiter = null; + resolveFn(ev); + } + }) + .catch(() => {}); + }); + + try { + if (parsed.hasExplicitAfter) { + opts.onResolvedCursor?.(formatEventCursor(parsed.afterSeq)); + const existing = await queryBoardEventsAfter(db, companyId, actor, parsed, { + limit: 1, + authActor: effectiveAuthActor, + }); + if (existing.length > 0) { + return existing[0]!; + } + } else { + parsed.afterSeq = await getCurrentCompanyMaxEventSeq(db, companyId); + opts.onResolvedCursor?.(formatEventCursor(parsed.afterSeq)); + } + + // Drain any events buffered during the initial query while keeping + // checkingInitial=true so newly arriving events keep buffering until we + // synchronously install resolveWaiter below (zero missed-event window). + while (buffered.length > 0) { + const ev = buffered.shift()!; + if ( + await eventMatchesFiltersAndAccess( + db, + companyId, + actor, + ev, + parsed, + channelCache, + issueLabelCache, + undefined, + effectiveAuthActor, + ) + ) { + return ev; + } + } + + if (timeoutMs <= 0 || opts.signal?.aborted) { + return null; + } + + return await new Promise((resolve) => { + let settled = false; + const finish = (result: BoardEventView | null) => { + if (settled) return; + settled = true; + clearTimeout(timer); + opts.signal?.removeEventListener("abort", onAbort); + resolveWaiter = null; + resolve(result); + }; + const onAbort = () => finish(null); + resolveWaiter = finish; + checkingInitial = false; + const timer = setTimeout(() => finish(null), timeoutMs); + opts.signal?.addEventListener("abort", onAbort, { once: true }); + }); + } finally { + unsubscribe(); + } +} + +export async function createSchedule( + db: Db, + companyId: string, + actor: HeadlessActorContext, + rawInput: unknown, + opts: { authActor?: AuthorizationActor } = {}, +): Promise { + const input = SchedulePostSchema.parse(rawInput ?? {}); + enforceHeadlessScopes(actor, { action: "schedules.create" }); + + let intervalMs: number | null = null; + if (input.every !== undefined) { + try { + intervalMs = parseDurationMs(input.every); + } catch (err) { + throw badRequest(err instanceof Error ? err.message : "Invalid 'every' duration"); + } + if (intervalMs <= 0) { + throw badRequest("'every' interval must be positive"); + } + } + + let nextRunAt: Date; + if (input.in !== undefined) { + let delayMs: number; + try { + delayMs = parseDurationMs(input.in); + } catch (err) { + throw badRequest(err instanceof Error ? err.message : "Invalid 'in' duration"); + } + nextRunAt = new Date(Date.now() + delayMs); + } else if (input.at !== undefined) { + const ms = Date.parse(input.at); + if (!Number.isFinite(ms)) { + throw badRequest(`Invalid 'at' timestamp "${input.at}"`); + } + nextRunAt = new Date(ms); + } else { + nextRunAt = new Date(Date.now() + intervalMs!); + } + + let untilAt: Date | null = null; + if (input.until !== undefined) { + const ms = Date.parse(input.until); + if (!Number.isFinite(ms)) { + throw badRequest(`Invalid 'until' timestamp "${input.until}"`); + } + untilAt = new Date(ms); + } + + const row = await db.transaction(async (tx) => { + let targetChannelId: string | null = null; + let targetIssueId: string | null = null; + let normalizedTarget: string; + + if (isIssueReferenceTarget(input.target)) { + const issue = await resolveIssueByIdOrIdentifier(tx, input.target, companyId); + const effectiveAuthActor = opts.authActor ?? buildAuthActorFromHeadless(actor); + await assertCanonicalIssueAccessForActor( + tx, + effectiveAuthActor, + issue, + "issue:comment", + ); + await assertIssueChannelScopeAccess(tx, issue, actor); + targetIssueId = issue.id; + normalizedTarget = issue.identifier ?? issue.id; + } else { + let path: string; + try { + path = normalizeChannelPath(input.target, { + allowSubtreePrefix: false, + }).path; + } catch (err) { + throw badRequest(err instanceof Error ? err.message : "Invalid target channel"); + } + enforceHeadlessScopes(actor, { channelPath: path }); + const ch = await ensureChannel(tx, companyId, actor, { path }); + targetChannelId = ch.id; + normalizedTarget = ch.path; + } + + await notifyDeliveryWork(tx, DELIVERY_QUEUES.scheduledBoardPosts, companyId); + + const [inserted] = await tx + .insert(scheduledBoardPosts) + .values({ + companyId, + target: normalizedTarget, + channelId: targetChannelId, + issueId: targetIssueId, + message: input.message, + postOnly: Boolean(input.post), + kvLabels: input.labels ?? {}, + schemaBlocks: (input.blocks ?? []) as SchemaBlock[], + intervalMs, + untilAt, + nextRunAt, + status: "scheduled", + authorUserId: actor.agentId ? null : (actor.userId ?? null), + authorAgentId: actor.agentId ?? null, + authorProfile: actor.actorProfile ?? null, + }) + .returning(); + + await tx.insert(activityLog).values({ + companyId, + actorType: actor.principalType === "agent" ? "agent" : "user", + actorId: + actor.principalType === "agent" + ? actor.agentId ?? "unknown-agent" + : actor.userId ?? "board", + agentId: actor.agentId ?? null, + responsibleUserId: actor.responsibleUserId ?? null, + action: "schedule.created", + entityType: "scheduled_board_post", + entityId: inserted!.id, + details: { + target: normalizedTarget, + nextRunAt: nextRunAt.toISOString(), + intervalMs, + }, + }); + + const cursor = await getLatestCompanyEventCursor(tx, companyId); + return { row: inserted!, cursor }; + }); + + return serializeScheduleRow(row.row, row.cursor); +} + +export async function listSchedules( + db: Db, + companyId: string, + actor: HeadlessActorContext, + filters: { target?: string } = {}, + opts: { authActor?: AuthorizationActor } = {}, +): Promise { + enforceHeadlessScopes(actor, { action: "schedules.read" }); + const effectiveAuthActor = opts.authActor ?? buildAuthActorFromHeadless(actor); + const readCondition = await issueReadSqlCondition(db, effectiveAuthActor); + + const conditions = [eq(scheduledBoardPosts.companyId, companyId)]; + if (filters.target?.trim()) { + const trimmed = filters.target.trim(); + if (isIssueReferenceTarget(trimmed)) { + const issue = await resolveIssueByIdOrIdentifier(db, trimmed, companyId); + const [readable] = await db + .select({ id: issues.id }) + .from(issues) + .where(and(eq(issues.id, issue.id), readCondition)) + .limit(1); + if (!readable) { + throw notFound(`Issue '${trimmed}' not found`); + } + if (issue.channelId) { + const [ch] = await db + .select() + .from(channels) + .where(eq(channels.id, issue.channelId)) + .limit(1); + if (ch) { + await assertChannelAccess(db, ch, actor); + } + } else if (!allowsUnchanneledScope(actor)) { + throw notFound(`Issue '${trimmed}' not found`); + } + conditions.push(eq(scheduledBoardPosts.issueId, issue.id)); + } else { + const path = normalizeChannelPath(trimmed, { + allowSubtreePrefix: false, + }).path; + conditions.push(eq(scheduledBoardPosts.target, path)); + } + } + + const rows = await db + .select() + .from(scheduledBoardPosts) + .where(and(...conditions)) + .orderBy(asc(scheduledBoardPosts.nextRunAt)); + + const issueIds = Array.from( + new Set( + rows.map((r) => r.issueId).filter((id): id is string => Boolean(id)), + ), + ); + const readableIssueRows = + issueIds.length > 0 + ? await db + .select({ id: issues.id, channelId: issues.channelId }) + .from(issues) + .where( + and( + eq(issues.companyId, companyId), + inArray(issues.id, issueIds), + readCondition, + ), + ) + : []; + const readableIssueMap = new Map(readableIssueRows.map((i) => [i.id, i])); + + const channelIds = Array.from( + new Set([ + ...rows.map((r) => r.channelId).filter((id): id is string => Boolean(id)), + ...readableIssueRows + .map((i) => i.channelId) + .filter((id): id is string => Boolean(id)), + ]), + ); + const channelRows = + channelIds.length > 0 + ? await db + .select() + .from(channels) + .where(inArray(channels.id, channelIds)) + : []; + const channelMap = new Map(channelRows.map((c) => [c.id, c])); + + const visible: ScheduleView[] = []; + for (const row of rows) { + if (row.channelId) { + const ch = channelMap.get(row.channelId); + if (!ch) continue; + if (!isChannelAllowedByScopes(actor, ch.path)) continue; + if (!(await canAccessChannel(db, ch, actor))) continue; + } + if (row.issueId) { + const targetIssue = readableIssueMap.get(row.issueId); + if (!targetIssue) continue; + if (targetIssue.channelId) { + const issueChannel = channelMap.get(targetIssue.channelId); + if (!issueChannel) continue; + if (!isChannelAllowedByScopes(actor, issueChannel.path)) continue; + if (!(await canAccessChannel(db, issueChannel, actor))) continue; + } else if (!allowsUnchanneledScope(actor)) { + continue; + } + } + visible.push(serializeScheduleRow(row)); + } + + return visible; +} + +export async function cancelSchedule( + db: Db, + companyId: string, + actor: HeadlessActorContext, + scheduleId: string, + opts: { authActor?: AuthorizationActor } = {}, +): Promise<{ cancelled: boolean }> { + enforceHeadlessScopes(actor, { action: "schedules.cancel" }); + const effectiveAuthActor = opts.authActor ?? buildAuthActorFromHeadless(actor); + + await db.transaction(async (tx) => { + const [row] = await tx + .select() + .from(scheduledBoardPosts) + .where( + and( + eq(scheduledBoardPosts.id, scheduleId), + eq(scheduledBoardPosts.companyId, companyId), + ), + ); + if (!row) { + throw notFound("Schedule not found"); + } + if (row.channelId) { + const [ch] = await tx + .select() + .from(channels) + .where(eq(channels.id, row.channelId)); + if (!ch) { + throw notFound("Schedule not found"); + } + await assertChannelAccess(tx, ch, actor); + } + if (row.issueId) { + const readCondition = await issueReadSqlCondition( + tx as unknown as Db, + effectiveAuthActor, + ); + const [readableIssue] = await tx + .select({ id: issues.id, channelId: issues.channelId }) + .from(issues) + .where( + and( + eq(issues.id, row.issueId), + eq(issues.companyId, companyId), + readCondition, + ), + ) + .limit(1); + if (!readableIssue) { + throw notFound("Schedule not found"); + } + if (readableIssue.channelId) { + const [ch] = await tx + .select() + .from(channels) + .where(eq(channels.id, readableIssue.channelId)) + .limit(1); + if (!ch) { + throw notFound("Schedule not found"); + } + await assertChannelAccess(tx, ch, actor); + } else if (!allowsUnchanneledScope(actor)) { + throw notFound("Schedule not found"); + } + } + + await notifyDeliveryWork(tx, DELIVERY_QUEUES.scheduledBoardPosts, companyId); + + await tx + .update(scheduledBoardPosts) + .set({ + status: "cancelled", + updatedAt: new Date(), + }) + .where(eq(scheduledBoardPosts.id, row.id)); + + await tx.insert(activityLog).values({ + companyId, + actorType: actor.principalType === "agent" ? "agent" : "user", + actorId: + actor.principalType === "agent" + ? actor.agentId ?? "unknown-agent" + : actor.userId ?? "board", + agentId: actor.agentId ?? null, + responsibleUserId: actor.responsibleUserId ?? null, + action: "schedule.cancelled", + entityType: "scheduled_board_post", + entityId: row.id, + details: { + target: row.target, + }, + }); + }); + + return { cancelled: true }; +} + +export interface ScheduledPostWakeup { + companyId: string; + issueId: string; + assigneeAgentId: string; + scheduleId: string; + commentId: string; + authorType: "agent" | "user" | "system"; + authorAgentId: string | null; + authorUserId: string | null; +} + +export function createScheduledBoardPostsWorker( + db: Db, + opts: { + onWakeAssignee?: (wake: ScheduledPostWakeup) => Promise; + } = {}, +) { + const heartbeat = opts.onWakeAssignee ? null : heartbeatService(db); + let cachedNextDueMs: number | null = null; + + async function refreshNextDueAt(): Promise { + const result = await db.execute<{ min_due: Date | string | null }>(sql` + SELECT MIN(next_run_at) AS min_due + FROM scheduled_board_posts + WHERE status = 'scheduled' + `); + const raw = result[0]?.min_due ?? null; + if (!raw) { + cachedNextDueMs = null; + return null; + } + const ms = raw instanceof Date ? raw.getTime() : Date.parse(String(raw)); + cachedNextDueMs = Number.isFinite(ms) ? ms : null; + return cachedNextDueMs; + } + + async function runDueScheduledPosts(signal?: AbortSignal): Promise { + let totalExecuted = 0; + const batchLimit = 25; + + while (!signal?.aborted) { + const committed = await db.transaction(async (tx) => { + const dueResult = await tx.execute<{ id: string }>(sql` + SELECT id + FROM scheduled_board_posts + WHERE status = 'scheduled' + AND next_run_at <= now() + ORDER BY next_run_at ASC + LIMIT ${batchLimit} + FOR UPDATE OF scheduled_board_posts SKIP LOCKED + `); + + const dueIds = Array.from(dueResult).map((r) => r.id); + if (dueIds.length === 0) { + return { + executedCount: 0, + events: [] as BoardEventView[], + wakeups: [] as ScheduledPostWakeup[], + }; + } + + const dueRows = await tx + .select() + .from(scheduledBoardPosts) + .where(inArray(scheduledBoardPosts.id, dueIds)) + .orderBy(asc(scheduledBoardPosts.nextRunAt)); + + const now = new Date(); + const events: BoardEventView[] = []; + const wakeups: ScheduledPostWakeup[] = []; + + for (const row of dueRows) { + const scheduleActor = row.authorAgentId + ? { + principalType: "agent" as const, + userId: null, + agentId: row.authorAgentId, + agentName: row.authorProfile ?? null, + actorProfile: row.authorProfile ?? null, + } + : row.authorUserId + ? { + principalType: "user" as const, + userId: row.authorUserId, + agentId: null, + agentName: null, + actorProfile: row.authorProfile ?? null, + } + : { + principalType: "system" as const, + actorProfile: row.authorProfile ?? "scheduler", + }; + + if (row.issueId) { + const [issue] = await tx + .select() + .from(issues) + .where( + and( + eq(issues.id, row.issueId), + eq(issues.companyId, row.companyId), + ), + ); + + if (issue) { + let channelPath: string | null = null; + if (issue.channelId) { + const [ch] = await tx + .select({ path: channels.path }) + .from(channels) + .where(eq(channels.id, issue.channelId)); + channelPath = ch?.path ?? null; + } + + const [comment] = await tx + .insert(issueComments) + .values({ + companyId: row.companyId, + issueId: issue.id, + body: row.message, + kvLabels: row.kvLabels ?? {}, + schemaBlocks: row.schemaBlocks ?? [], + authorType: row.authorAgentId + ? "agent" + : row.authorUserId + ? "user" + : "system", + authorAgentId: row.authorAgentId ?? null, + authorUserId: row.authorAgentId ? null : (row.authorUserId ?? null), + actorProfile: row.authorProfile ?? null, + }) + .returning(); + + events.push( + await appendBoardEvent(tx, { + companyId: row.companyId, + type: "comment.posted", + channelId: issue.channelId, + channelPath, + issueId: issue.id, + identifier: issue.identifier ?? issue.id, + actor: scheduleActor, + payload: { + commentId: comment!.id, + body: comment!.body, + kvLabels: comment!.kvLabels ?? {}, + blocks: comment!.schemaBlocks ?? [], + scheduleId: row.id, + }, + }), + ); + + if ( + !row.postOnly && + issue.assigneeAgentId && + issue.status !== "done" && + issue.status !== "cancelled" + ) { + wakeups.push({ + companyId: row.companyId, + issueId: issue.id, + assigneeAgentId: issue.assigneeAgentId, + scheduleId: row.id, + commentId: comment!.id, + authorType: row.authorAgentId + ? "agent" + : row.authorUserId + ? "user" + : "system", + authorAgentId: row.authorAgentId ?? null, + authorUserId: row.authorAgentId ? null : (row.authorUserId ?? null), + }); + } + } + } else if (row.channelId) { + const [ch] = await tx + .select() + .from(channels) + .where(eq(channels.id, row.channelId)); + + if (ch) { + const [maxRow] = await tx + .select({ + maxNum: sql`coalesce(max(${issues.issueNumber}), 0)`, + }) + .from(issues) + .where(eq(issues.companyId, row.companyId)); + const currentMax = Number(maxRow?.maxNum ?? 0); + + const [company] = await tx + .update(companies) + .set({ + issueCounter: sql`greatest(${companies.issueCounter}, ${currentMax}) + 1`, + }) + .where(eq(companies.id, row.companyId)) + .returning({ + issueCounter: companies.issueCounter, + issuePrefix: companies.issuePrefix, + }); + + const issueNumber = company!.issueCounter; + const identifier = `${company!.issuePrefix}-${issueNumber}`; + const { title, description } = splitMessageIntoTitleAndDescription( + row.message, + ); + const status = row.postOnly ? "backlog" : "todo"; + let issueVisibility: "open" | "private" = + ch.visibility === "private" ? "private" : "open"; + if (ch.defaultProjectId && issueVisibility !== "private") { + const [projRow] = await tx + .select({ visibility: projects.visibility }) + .from(projects) + .where( + and( + eq(projects.id, ch.defaultProjectId), + eq(projects.companyId, row.companyId), + ), + ) + .limit(1); + if (projRow?.visibility === "private") { + issueVisibility = "private"; + } + } + const newIssueId = randomUUID(); + + const [createdIssue] = await tx + .insert(issues) + .values({ + id: newIssueId, + companyId: row.companyId, + channelId: ch.id, + projectId: ch.defaultProjectId ?? null, + visibility: issueVisibility, + privacyRootIssueId: + issueVisibility === "private" ? newIssueId : null, + title, + description, + status, + scope: "channel", + priority: "medium", + issueNumber, + identifier, + kvLabels: row.kvLabels ?? {}, + schemaBlocks: row.schemaBlocks ?? [], + createdByAgentId: row.authorAgentId ?? null, + createdByUserId: row.authorAgentId + ? null + : (row.authorUserId ?? null), + createdByProfile: row.authorProfile ?? null, + originKind: "scheduled_post", + originId: row.id, + }) + .returning(); + + await tx + .update(channels) + .set({ lastActivityAt: now, updatedAt: now }) + .where(eq(channels.id, ch.id)); + + if (row.postOnly) { + events.push( + await appendBoardEvent(tx, { + companyId: row.companyId, + type: "thread.posted", + channelId: ch.id, + channelPath: ch.path, + issueId: createdIssue!.id, + identifier, + actor: scheduleActor, + payload: { + title, + body: row.message, + kvLabels: row.kvLabels ?? {}, + blocks: row.schemaBlocks ?? [], + scheduleId: row.id, + }, + }), + ); + } else { + events.push( + await appendBoardEvent(tx, { + companyId: row.companyId, + type: "task.created", + channelId: ch.id, + channelPath: ch.path, + issueId: createdIssue!.id, + identifier, + actor: scheduleActor, + payload: { + title, + body: row.message, + kvLabels: row.kvLabels ?? {}, + blocks: row.schemaBlocks ?? [], + scheduleId: row.id, + }, + }), + ); + events.push( + await appendBoardEvent(tx, { + companyId: row.companyId, + type: "task.ready", + channelId: ch.id, + channelPath: ch.path, + issueId: createdIssue!.id, + identifier, + actor: scheduleActor, + payload: { + kvLabels: row.kvLabels ?? {}, + scheduleId: row.id, + }, + }), + ); + } + } + } + + const nextCount = (row.runCount ?? 0) + 1; + if (row.intervalMs && row.intervalMs > 0) { + const nextRun = new Date(now.getTime() + row.intervalMs); + if (!row.untilAt || nextRun.getTime() <= row.untilAt.getTime()) { + await tx + .update(scheduledBoardPosts) + .set({ + lastRunAt: now, + runCount: nextCount, + nextRunAt: nextRun, + updatedAt: now, + }) + .where(eq(scheduledBoardPosts.id, row.id)); + } else { + await tx + .update(scheduledBoardPosts) + .set({ + lastRunAt: now, + runCount: nextCount, + status: "completed", + updatedAt: now, + }) + .where(eq(scheduledBoardPosts.id, row.id)); + } + } else { + await tx + .update(scheduledBoardPosts) + .set({ + lastRunAt: now, + runCount: nextCount, + status: "completed", + updatedAt: now, + }) + .where(eq(scheduledBoardPosts.id, row.id)); + } + } + + return { executedCount: dueRows.length, events, wakeups }; + }); + + for (const ev of committed.events) { + publishCommittedBoardEvent(ev); + } + + for (const wake of committed.wakeups) { + try { + if (opts.onWakeAssignee) { + await opts.onWakeAssignee(wake); + } else if (heartbeat) { + await heartbeat.wakeup(wake.assigneeAgentId, { + source: "automation", + triggerDetail: "system", + reason: "scheduled_monitor", + payload: { + issueId: wake.issueId, + scheduleId: wake.scheduleId, + commentId: wake.commentId, + mutation: "schedule", + }, + idempotencyKey: `schedule:${wake.scheduleId}:${wake.commentId}`, + requestedByActorType: wake.authorType, + requestedByActorId: + wake.authorType === "agent" + ? wake.authorAgentId ?? "unknown-agent" + : wake.authorType === "user" + ? wake.authorUserId ?? "board" + : "scheduler", + contextSnapshot: { + issueId: wake.issueId, + taskId: wake.issueId, + scheduleId: wake.scheduleId, + wakeReason: "scheduled_monitor", + }, + }); + } + } catch (err) { + logger.warn( + { err, scheduleId: wake.scheduleId, issueId: wake.issueId }, + "Failed to wake assignee for scheduled issue monitor", + ); + } + } + + totalExecuted += committed.executedCount; + if (committed.executedCount < batchLimit) break; + } + + await refreshNextDueAt(); + return totalExecuted; + } + + return { + runDueScheduledPosts, + refreshNextDueAt, + nextRunAt: () => cachedNextDueMs, + deliveryTask: { + retryMs: 5_000, + coalesceMs: 50, + pausePassiveMaintenance: true, + run: async (signal: AbortSignal) => { + await runDueScheduledPosts(signal); + }, + hasPending: async (runAllowed = true) => { + if (!runAllowed) return false; + return cachedNextDueMs !== null && cachedNextDueMs <= Date.now(); + }, + nextRunAt: () => cachedNextDueMs, + nextRunAtOnError: () => cachedNextDueMs, + }, + }; +} diff --git a/server/src/services/headless-identity.ts b/server/src/services/headless-identity.ts new file mode 100644 index 00000000000..20eb997be60 --- /dev/null +++ b/server/src/services/headless-identity.ts @@ -0,0 +1,587 @@ +import { createHash, randomBytes } from "node:crypto"; +import type { Request } from "express"; +import { and, asc, eq, inArray, ne, sql } from "drizzle-orm"; +import type { Db } from "@paperclipai/db"; +import { agentApiKeys, agents, boardApiKeys, companies } from "@paperclipai/db"; +import { + AGENT_ROLES, + deriveAgentUrlKey, + isUuidLike, + type AgentIdentityPolicy, + type AgentRole, + type CompanyResolutionView, + type DeploymentMode, + type WhoAmIView, +} from "@paperclipai/shared"; +import { conflict, forbidden, notFound, unauthorized } from "../errors.js"; +import { assertCompanyAccess, boardAccessRequired, getActorInfo } from "../routes/authz.js"; +import { logActivity, publishActivity, type ActivityPublication } from "./activity-log.js"; +import { createHeadlessAgentInTransaction } from "./agent-lifecycle.js"; +import { authorizationService } from "./authorization.js"; +import { + actionMatchesScopePattern, + resolveHeadlessActor, + resolveCompanyAgentIdentityPolicy, +} from "./headless-common.js"; +import { pickAvailableIssuePrefix } from "./issue-prefix.js"; +import { logger } from "../middleware/logger.js"; + +function normalizeAgentRole(rawRole?: string | null): AgentRole { + const candidate = rawRole?.trim().toLowerCase() ?? ""; + if ((AGENT_ROLES as readonly string[]).includes(candidate)) { + return candidate as AgentRole; + } + return "general"; +} + +function hashAgentToken(token: string): string { + return createHash("sha256").update(token).digest("hex"); +} + +function createHeadlessAgentToken(): string { + return `pcp_${randomBytes(24).toString("base64url")}`; +} + +function deriveRequestApiBase(req: Request): string { + const forwardedProto = req.header("x-forwarded-proto")?.split(",")[0]?.trim(); + const proto = forwardedProto || req.protocol || "http"; + const forwardedHost = req.header("x-forwarded-host")?.split(",")[0]?.trim(); + const host = forwardedHost || req.get("host") || "127.0.0.1:3100"; + return `${proto}://${host}`; +} + +export function headlessIdentityService( + db: Db, + opts: { deploymentMode?: DeploymentMode } = {}, +) { + function resolveDeploymentMode(req: Request): DeploymentMode { + return ( + opts.deploymentMode ?? + (req.actor?.source === "local_implicit" ? "local_trusted" : "authenticated") + ); + } + + async function resolveBoardKeyCompanyScope(req: Request): Promise { + if (req.actor?.type === "board" && req.actor.source === "board_key" && req.actor.keyId) { + const [keyRow] = await db + .select({ companyId: boardApiKeys.companyId }) + .from(boardApiKeys) + .where(eq(boardApiKeys.id, req.actor.keyId)); + return keyRow?.companyId ?? null; + } + return null; + } + + async function resolveDefaultCompany( + req: Request, + companyQuery?: string | null, + ): Promise { + if (!req.actor || req.actor.type === "none") { + throw unauthorized("Authentication required"); + } + + const deploymentMode = resolveDeploymentMode(req); + const trimmedQuery = companyQuery?.trim() || null; + + type CompanyRow = { + id: string; + name: string; + issuePrefix: string; + agentIdentityPolicy: AgentIdentityPolicy | null; + createdAt: Date; + }; + + let accessible: CompanyRow[] = []; + let keyCompanyId: string | null = null; + + if (req.actor.type === "agent") { + if (req.actor.keyScope && req.actor.keyScope.kind !== "standard") { + throw forbidden( + `Scoped '${req.actor.keyScope.kind}' agent keys cannot access headless company resolution`, + { code: "scope_denied" }, + ); + } + if (req.actor.companyId) { + accessible = await db + .select({ + id: companies.id, + name: companies.name, + issuePrefix: companies.issuePrefix, + agentIdentityPolicy: companies.agentIdentityPolicy, + createdAt: companies.createdAt, + }) + .from(companies) + .where( + and( + eq(companies.id, req.actor.companyId), + eq(companies.status, "active"), + ), + ) + .orderBy(asc(companies.createdAt)); + } + } else { + keyCompanyId = await resolveBoardKeyCompanyScope(req); + const isLocalImplicit = req.actor.source === "local_implicit"; + const isUnrestrictedAdmin = isLocalImplicit || Boolean(req.actor.isInstanceAdmin); + + if (keyCompanyId) { + if (isUnrestrictedAdmin || (req.actor.companyIds ?? []).includes(keyCompanyId)) { + accessible = await db + .select({ + id: companies.id, + name: companies.name, + issuePrefix: companies.issuePrefix, + agentIdentityPolicy: companies.agentIdentityPolicy, + createdAt: companies.createdAt, + }) + .from(companies) + .where(and(eq(companies.id, keyCompanyId), eq(companies.status, "active"))) + .orderBy(asc(companies.createdAt)); + } + } else if (isUnrestrictedAdmin) { + accessible = await db + .select({ + id: companies.id, + name: companies.name, + issuePrefix: companies.issuePrefix, + agentIdentityPolicy: companies.agentIdentityPolicy, + createdAt: companies.createdAt, + }) + .from(companies) + .where(eq(companies.status, "active")) + .orderBy(asc(companies.createdAt)); + } else { + const companyIds = req.actor.companyIds ?? []; + if (companyIds.length > 0) { + accessible = await db + .select({ + id: companies.id, + name: companies.name, + issuePrefix: companies.issuePrefix, + agentIdentityPolicy: companies.agentIdentityPolicy, + createdAt: companies.createdAt, + }) + .from(companies) + .where( + and(inArray(companies.id, companyIds), eq(companies.status, "active")), + ) + .orderBy(asc(companies.createdAt)); + } + } + + if ( + accessible.length === 0 && + !trimmedQuery && + !keyCompanyId && + (deploymentMode === "local_trusted" || req.actor.source === "local_implicit") + ) { + const autoCreated = await db.transaction(async (tx) => { + await tx.execute( + sql`select pg_advisory_xact_lock(hashtext('paperclip:auto-default-company'))`, + ); + const existing = await tx + .select({ + id: companies.id, + name: companies.name, + issuePrefix: companies.issuePrefix, + agentIdentityPolicy: companies.agentIdentityPolicy, + createdAt: companies.createdAt, + }) + .from(companies) + .where(eq(companies.status, "active")) + .orderBy(asc(companies.createdAt)); + if (existing.length > 0) { + return existing[0]!; + } + const prefix = (await pickAvailableIssuePrefix(tx, "PC")) ?? "PC"; + const [inserted] = await tx + .insert(companies) + .values({ + name: "Workspace", + issuePrefix: prefix, + status: "active", + defaultResponsibleUserId: "local-board", + }) + .returning({ + id: companies.id, + name: companies.name, + issuePrefix: companies.issuePrefix, + agentIdentityPolicy: companies.agentIdentityPolicy, + createdAt: companies.createdAt, + }); + return inserted!; + }); + accessible = [autoCreated]; + } + } + + let selected: CompanyRow | undefined; + if (trimmedQuery) { + const lowerQuery = trimmedQuery.toLowerCase(); + selected = isUuidLike(trimmedQuery) + ? accessible.find((c) => c.id.toLowerCase() === lowerQuery) + : accessible.find((c) => c.issuePrefix.toLowerCase() === lowerQuery) ?? + accessible.find((c) => c.name.trim().toLowerCase() === lowerQuery); + if (!selected) { + throw notFound(`Company '${trimmedQuery}' not found`, { + code: "no_company_found", + }); + } + } else { + selected = accessible[0]; + if (!selected) { + throw notFound("no_company_found", { code: "no_company_found" }); + } + } + + return { + id: selected.id, + name: selected.name, + issuePrefix: selected.issuePrefix, + agentIdentityPolicy: resolveCompanyAgentIdentityPolicy( + selected.agentIdentityPolicy, + deploymentMode, + ), + }; + } + + async function whoami( + req: Request, + companyIdQuery?: string | null, + ): Promise { + if (!req.actor || req.actor.type === "none") { + throw unauthorized("Authentication required"); + } + const deploymentMode = resolveDeploymentMode(req); + const trimmed = companyIdQuery?.trim() || null; + const companyId = + trimmed && isUuidLike(trimmed) + ? trimmed + : (await resolveDefaultCompany(req, trimmed)).id; + + const actor = await resolveHeadlessActor(db, req, companyId, { + deploymentMode, + }); + + return { + apiBase: deriveRequestApiBase(req), + companyId: actor.companyId, + companyPrefix: actor.companyPrefix, + companyName: actor.companyName, + principalType: actor.principalType, + userId: actor.userId, + agentId: actor.agentId, + agentName: actor.agentName, + actorProfile: actor.actorProfile, + agentIdentityPolicy: actor.agentIdentityPolicy, + scopes: actor.scopes, + }; + } + + async function connectAgent( + req: Request, + companyId: string, + input: { name: string; role?: string; ttlSec?: number }, + ) { + if (!req.actor || req.actor.type === "none") { + throw unauthorized("Authentication required"); + } + if (req.actor.type !== "board") { + throw boardAccessRequired(req); + } + if (!isUuidLike(companyId)) { + throw notFound("Company not found"); + } + const headlessActor = await resolveHeadlessActor(db, req, companyId, { + deploymentMode: resolveDeploymentMode(req), + requiredAction: "agents.connect", + }); + if (headlessActor.actorProfile && req.actor.source === "board_key") { + throw forbidden("Profile-locked credentials cannot mint registered agent API keys", { + code: "profile_locked", + }); + } + if (headlessActor.scopes?.channels && headlessActor.scopes.channels.length >= 0) { + throw forbidden("Channel-scoped credentials cannot mint unrestricted agent API keys", { + code: "scope_denied", + }); + } + if ( + headlessActor.scopes?.actions && + !headlessActor.scopes.actions.some((pattern) => + actionMatchesScopePattern("agents.connect", pattern), + ) + ) { + throw forbidden("Caller scopes do not allow connecting agents", { + code: "scope_denied", + }); + } + assertCompanyAccess(req, companyId); + + const trimmedName = input.name.trim(); + if (!trimmedName) { + throw conflict("Agent name cannot be empty"); + } + + const publications: ActivityPublication[] = []; + const result = await db.transaction(async (tx) => { + const [company] = await tx + .select({ + id: companies.id, + defaultResponsibleUserId: companies.defaultResponsibleUserId, + requireBoardApprovalForNewAgents: companies.requireBoardApprovalForNewAgents, + }) + .from(companies) + .where(eq(companies.id, companyId)); + + if (!company) { + throw notFound("Company not found"); + } + + const authz = authorizationService(tx as unknown as Db); + const createDecision = await authz.decide({ + actor: req.actor, + action: "agents:create", + resource: { type: "company", companyId }, + }); + if (!createDecision.allowed) { + throw forbidden( + createDecision.explanation ?? "Missing permission: agents:create", + { code: "forbidden", reason: createDecision.reason }, + ); + } + + const targetLower = trimmedName.toLowerCase(); + const existingAgents = await tx + .select() + .from(agents) + .where(and(eq(agents.companyId, companyId), ne(agents.status, "terminated"))); + + let agent = existingAgents.find( + (a) => + a.name.trim().toLowerCase() === targetLower || + deriveAgentUrlKey(a.name, a.id).toLowerCase() === targetLower, + ); + + if (agent) { + if (agent.status === "pending_approval") { + throw conflict( + "Agent is pending board approval and cannot receive an API key until approved.", + { code: "board_approval_required" }, + ); + } + const configureDecision = await authz.decide({ + actor: req.actor, + action: "agent_config:update", + resource: { type: "agent", companyId, agentId: agent.id }, + }); + if (!configureDecision.allowed) { + throw forbidden( + configureDecision.explanation ?? + "Missing permission to manage the target agent", + { code: "forbidden", reason: configureDecision.reason }, + ); + } + } else { + if (company.requireBoardApprovalForNewAgents) { + throw conflict( + "Direct agent creation requires board approval. Use POST /api/companies/:companyId/agent-hires to create a pending hire approval.", + { code: "board_approval_required" }, + ); + } + agent = await createHeadlessAgentInTransaction(tx as unknown as Db, { + companyId, + name: trimmedName, + role: normalizeAgentRole(input.role), + createdByUserId: req.actor.userId ?? null, + }); + } + + const rawToken = createHeadlessAgentToken(); + const keyHash = hashAgentToken(rawToken); + const responsibleUserId = + req.actor.userId && req.actor.userId !== "local-board" + ? req.actor.userId + : company.defaultResponsibleUserId ?? "local-board"; + const keyName = `cli-${trimmedName}-${new Date().toISOString().replaceAll(":", "-")}`; + const expiresAt = + input.ttlSec !== undefined ? new Date(Date.now() + input.ttlSec * 1000) : null; + + const [keyRow] = await tx + .insert(agentApiKeys) + .values({ + agentId: agent.id, + companyId, + name: keyName, + keyHash, + responsibleUserId, + expiresAt, + }) + .returning(); + + const actorInfo = getActorInfo(req); + await logActivity( + tx as unknown as Db, + { + companyId, + actorType: actorInfo.actorType, + actorId: actorInfo.actorId, + agentId: actorInfo.agentId, + runId: actorInfo.runId, + action: "agent_api_key.created", + entityType: "agent", + entityId: agent.id, + details: { + agentId: agent.id, + agentName: agent.name, + agentApiKeyId: keyRow!.id, + name: keyRow!.name, + }, + }, + publications, + ); + + return { + agent, + agentId: agent.id, + agentName: agent.name, + companyId, + apiKey: rawToken, + token: rawToken, + key: { + id: keyRow!.id, + name: keyRow!.name, + token: rawToken, + createdAt: keyRow!.createdAt.toISOString(), + expiresAt: keyRow!.expiresAt ? keyRow!.expiresAt.toISOString() : null, + }, + }; + }); + + for (const publication of publications) { + try { + publishActivity(publication); + } catch (err) { + logger.warn({ err }, "Failed to publish agent_api_key.created activity"); + } + } + + return result; + } + + async function updateAgentIdentityPolicy( + req: Request, + companyId: string, + agentIdentityPolicy: AgentIdentityPolicy, + ) { + if (!req.actor || req.actor.type === "none") { + throw unauthorized("Authentication required"); + } + if (req.actor.type !== "board") { + throw boardAccessRequired(req); + } + if (!isUuidLike(companyId)) { + throw notFound("Company not found"); + } + const headlessActor = await resolveHeadlessActor(db, req, companyId, { + deploymentMode: resolveDeploymentMode(req), + requiredAction: "company.policy.update", + }); + if (headlessActor.actorProfile && req.actor.source === "board_key") { + throw forbidden("Profile-locked credentials cannot update company identity policy", { + code: "profile_locked", + }); + } + if (headlessActor.scopes?.channels) { + throw forbidden("Channel-scoped credentials cannot update company identity policy", { + code: "scope_denied", + }); + } + if ( + headlessActor.scopes?.actions && + !headlessActor.scopes.actions.some((pattern) => + actionMatchesScopePattern("company.policy.update", pattern), + ) + ) { + throw forbidden("Caller scopes do not allow updating company identity policy", { + code: "scope_denied", + }); + } + if ( + req.actor.source !== "local_implicit" && + !req.actor.isInstanceAdmin && + Array.isArray(req.actor.memberships) + ) { + const membership = req.actor.memberships.find((item) => item.companyId === companyId); + if ( + !membership || + membership.status !== "active" || + (membership.membershipRole !== "owner" && membership.membershipRole !== "admin") + ) { + throw forbidden("Owner or admin membership required to update identity policy"); + } + } + assertCompanyAccess(req, companyId); + + const publications: ActivityPublication[] = []; + const updated = await db.transaction(async (tx) => { + const [row] = await tx + .update(companies) + .set({ + agentIdentityPolicy, + updatedAt: new Date(), + }) + .where(eq(companies.id, companyId)) + .returning({ + id: companies.id, + agentIdentityPolicy: companies.agentIdentityPolicy, + }); + + if (!row) { + throw notFound("Company not found"); + } + + const actorInfo = getActorInfo(req); + await logActivity( + tx as unknown as Db, + { + companyId, + actorType: actorInfo.actorType, + actorId: actorInfo.actorId, + agentId: actorInfo.agentId, + runId: actorInfo.runId, + action: "company.agent_identity_policy_updated", + entityType: "company", + entityId: companyId, + details: { agentIdentityPolicy }, + }, + publications, + ); + + return row; + }); + + for (const publication of publications) { + try { + publishActivity(publication); + } catch (err) { + logger.warn( + { err }, + "Failed to publish company.agent_identity_policy_updated activity", + ); + } + } + + return { + id: updated.id, + agentIdentityPolicy: updated.agentIdentityPolicy, + }; + } + + return { + resolveDefaultCompany, + whoami, + connectAgent, + updateAgentIdentityPolicy, + }; +} diff --git a/server/src/services/headless-labels-batch.ts b/server/src/services/headless-labels-batch.ts new file mode 100644 index 00000000000..e8674bb3d8f --- /dev/null +++ b/server/src/services/headless-labels-batch.ts @@ -0,0 +1,663 @@ +import { createHash, randomUUID } from "node:crypto"; +import { and, eq, inArray, sql } from "drizzle-orm"; +import type { Db } from "@paperclipai/db"; +import { + channels, + companies, + issueBatchIdempotencyKeys, + issueRelations, + issues, + projects, +} from "@paperclipai/db"; +import { + applyKvLabelMutation, + KvLabelMutationSchema, + validateAndSortBatchPlan, + type BatchCreatedTaskItem, + type BatchCreateIssuesResult, + type BoardEventView, + type IssueScope, +} from "@paperclipai/shared"; +import { badRequest, conflict, unprocessable } from "../errors.js"; +import { + logActivity, + publishActivity, + type ActivityPublication, +} from "./activity-log.js"; +import { + attachTagLabels, + ensureChannel, + resolveAssigneeAgent, +} from "./headless-channels.js"; +import { + appendBoardEvent, + assertIssueChannelScopeAccess, + assertProjectReadAccess, + enforceHeadlessScopes, + loadHeadlessIssueView, + loadHeadlessIssueViews, + publishCommittedBoardEvent, + resolveIssueByIdOrIdentifier, + resolveProjectReference, + type HeadlessActorContext, +} from "./headless-common.js"; +import { + assertSchemaExists, + formatBlocksAsFencedJson, + validateSchemaBlocks, +} from "./headless-schemas.js"; + +function canonicalizeValue(value: unknown): unknown { + if (Array.isArray(value)) { + return value.map(canonicalizeValue); + } + if (typeof value === "object" && value !== null) { + const obj = value as Record; + const sorted: Record = {}; + for (const key of Object.keys(obj).sort()) { + const v = obj[key]; + if (v !== undefined) { + sorted[key] = canonicalizeValue(v); + } + } + return sorted; + } + return value; +} + +function hashCanonicalRequest(rawInput: unknown): string { + const canonical = JSON.stringify(canonicalizeValue(rawInput)); + return createHash("sha256").update(canonical).digest("hex"); +} + +function assertNoReservedLabelKeys(rawMutation: unknown): void { + if (!rawMutation || typeof rawMutation !== "object") return; + const mut = rawMutation as Record; + if (mut.set && typeof mut.set === "object" && !Array.isArray(mut.set)) { + for (const key of Object.keys(mut.set)) { + if (key.startsWith("paperclip.")) { + throw badRequest("Label keys starting with 'paperclip.' are reserved", { + error: "reserved_label", + code: "reserved_label", + key, + }); + } + } + } + if (Array.isArray(mut.unset)) { + for (const key of mut.unset) { + if (typeof key === "string" && key.startsWith("paperclip.")) { + throw badRequest("Label keys starting with 'paperclip.' are reserved", { + error: "reserved_label", + code: "reserved_label", + key, + }); + } + } + } +} + +export async function mutateIssueKvLabels( + db: Db, + issueRef: string, + actor: HeadlessActorContext, + rawMutation: unknown, +): Promise<{ id: string; kvLabels: Record; cursor: string }> { + enforceHeadlessScopes(actor, { action: "label" }); + assertNoReservedLabelKeys(rawMutation); + + const parsed = KvLabelMutationSchema.safeParse(rawMutation); + if (!parsed.success) { + throw badRequest( + parsed.error.issues + .map((i) => `${i.path.join(".") || "$"}: ${i.message}`) + .join("; "), + { + error: "validation_error", + code: "validation_error", + issues: parsed.error.issues, + }, + ); + } + + const target = await resolveIssueByIdOrIdentifier(db, issueRef, actor.companyId); + + const publications: ActivityPublication[] = []; + let committedEvent!: BoardEventView; + + const result = await db.transaction(async (tx) => { + const [locked] = await tx + .select() + .from(issues) + .where(and(eq(issues.id, target.id), eq(issues.companyId, actor.companyId))) + .for("update"); + + if (!locked) { + throw conflict("Issue disappeared during transaction"); + } + + const { channelPath } = await assertIssueChannelScopeAccess(tx, locked, actor); + if (!locked.channelId) { + enforceHeadlessScopes(actor, { action: "label" }); + } + + const currentKvLabels = (locked.kvLabels ?? {}) as Record; + const applied = applyKvLabelMutation(currentKvLabels, parsed.data); + if (!applied.ok) { + throw conflict("Label Compare-And-Swap precondition failed", { + error: "label_conflict", + code: "label_conflict", + conflictingKeys: applied.conflictingKeys, + currentLabels: currentKvLabels, + }); + } + + const now = new Date(); + await tx + .update(issues) + .set({ + kvLabels: applied.labels, + updatedAt: now, + }) + .where(eq(issues.id, locked.id)); + + if (locked.channelId) { + await tx + .update(channels) + .set({ lastActivityAt: now, updatedAt: now }) + .where(eq(channels.id, locked.channelId)); + } + + await logActivity( + tx as unknown as Db, + { + companyId: actor.companyId, + actorType: actor.principalType === "agent" ? "agent" : "user", + actorId: + actor.principalType === "agent" + ? actor.agentId! + : (actor.userId ?? "local-board"), + agentId: actor.agentId, + issueId: locked.id, + responsibleUserIdOverride: actor.responsibleUserId, + action: "issue.kv_labels_updated", + entityType: "issue", + entityId: locked.id, + details: { + previous: currentKvLabels, + current: applied.labels, + }, + }, + publications, + ); + + committedEvent = await appendBoardEvent(tx, { + companyId: actor.companyId, + type: "labels.changed", + channelId: locked.channelId, + channelPath, + issueId: locked.id, + identifier: locked.identifier ?? locked.id, + actor, + payload: { + previous: currentKvLabels, + current: applied.labels, + }, + }); + + return { + id: locked.id, + kvLabels: applied.labels, + cursor: committedEvent.cursor, + }; + }); + + for (const pub of publications) { + publishActivity(pub); + } + publishCommittedBoardEvent(committedEvent); + + return result; +} + +export async function createBatchIssuesPlan( + db: Db, + companyId: string, + actor: HeadlessActorContext, + rawInput: unknown, +): Promise { + const plan = validateAndSortBatchPlan(rawInput); + if (!plan.ok) { + const { ok: _ok, message: _msg, ...planDetails } = plan; + throw unprocessable(plan.message, { + error: plan.code, + ...planDetails, + }); + } + + enforceHeadlessScopes(actor, { + action: "tasks.create", + channelPath: plan.channel, + }); + + const requestHash = hashCanonicalRequest(rawInput); + const publications: ActivityPublication[] = []; + const committedEvents: BoardEventView[] = []; + + const result = await db.transaction(async (tx) => { + if (plan.idempotencyKey) { + // Serialize concurrent requests sharing the same (companyId, idempotencyKey) + // before reading or writing any tasks so losers never commit duplicates. + await tx.execute( + sql`SELECT pg_advisory_xact_lock(hashtext(${companyId}), hashtext(${plan.idempotencyKey}))`, + ); + const [existingIdemp] = await tx + .select() + .from(issueBatchIdempotencyKeys) + .where( + and( + eq(issueBatchIdempotencyKeys.companyId, companyId), + eq(issueBatchIdempotencyKeys.idempotencyKey, plan.idempotencyKey), + ), + ) + .limit(1); + + if (existingIdemp) { + if (existingIdemp.requestHash === requestHash) { + return { + ...(existingIdemp.responsePayload as unknown as BatchCreateIssuesResult), + idempotentReplay: true, + }; + } + throw conflict("Idempotency key already used with a different plan payload", { + error: "idempotency_conflict", + code: "idempotency_conflict", + idempotencyKey: plan.idempotencyKey, + }); + } + } + + const channel = plan.channel + ? await ensureChannel(tx, companyId, actor, { path: plan.channel }) + : null; + + let planDefaultProjectId: string | null = channel?.defaultProjectId ?? null; + if (plan.projectId !== undefined) { + planDefaultProjectId = + plan.projectId === null + ? null + : await resolveProjectReference(tx, companyId, plan.projectId, actor); + } else if (planDefaultProjectId) { + await assertProjectReadAccess(tx, companyId, planDefaultProjectId, actor); + } + + // Pre-resolve external dependencies + const externalIssueByRef = new Map(); + for (const task of plan.tasks) { + for (const extRef of task.externalNeeds) { + if (!externalIssueByRef.has(extRef)) { + const extIssue = await resolveIssueByIdOrIdentifier( + tx, + extRef, + companyId, + ); + await assertIssueChannelScopeAccess(tx, extIssue, actor); + externalIssueByRef.set(extRef, extIssue); + } + } + } + + // Validate blocks, resultSchema, projectId, and assignees for all tasks before writing + const resolvedTaskConfigs: Array<{ + projectId: string | null; + assigneeAgentId: string | null; + resultSchemaRef: string | null; + }> = []; + + for (const task of plan.tasks) { + await validateSchemaBlocks(tx, companyId, task.blocks); + const resultSchemaRef = task.resultSchema + ? await assertSchemaExists(tx, companyId, task.resultSchema) + : null; + + let taskProjectId = planDefaultProjectId; + if (task.projectId === null) { + taskProjectId = null; + } else if (task.projectId !== undefined) { + taskProjectId = await resolveProjectReference( + tx, + companyId, + task.projectId, + actor, + ); + } + + const assigneeAgentId = await resolveAssigneeAgent(tx, companyId, { + assigneeAgentId: task.assigneeAgentId, + for: task.for, + }); + + resolvedTaskConfigs.push({ + projectId: taskProjectId, + assigneeAgentId, + resultSchemaRef, + }); + } + + // Atomically allocate issue numbers for the batch + const now = new Date(); + const [maxRow] = await tx + .select({ + maxNum: sql`coalesce(max(${issues.issueNumber}), 0)`, + }) + .from(issues) + .where(eq(issues.companyId, companyId)); + const currentMax = Number(maxRow?.maxNum ?? 0); + + const [companyRow] = await tx + .update(companies) + .set({ + issueCounter: sql`greatest(${companies.issueCounter}, ${currentMax}) + ${plan.tasks.length}`, + updatedAt: now, + }) + .where(eq(companies.id, companyId)) + .returning({ + issueCounter: companies.issueCounter, + issuePrefix: companies.issuePrefix, + }); + + const firstIssueNumber = companyRow!.issueCounter - plan.tasks.length + 1; + + const createdByKey = new Map(); + const createdRows: Array = []; + const pendingEvents: Array<{ + issueId: string; + identifier: string; + key: string | null; + type: "task.created" | "task.ready"; + payload: Record; + isTaskCreated?: boolean; + }> = []; + const cursorByIssueId = new Map(); + const keyByIssueId = new Map(); + + // Pre-fetch private project visibility for all referenced projects + const referencedProjectIds = Array.from( + new Set( + resolvedTaskConfigs + .map((c) => c.projectId) + .filter((id): id is string => Boolean(id)), + ), + ); + const privateProjectIds = new Set(); + if (referencedProjectIds.length > 0) { + const projRows = await tx + .select({ id: projects.id, visibility: projects.visibility }) + .from(projects) + .where( + and( + eq(projects.companyId, companyId), + inArray(projects.id, referencedProjectIds), + ), + ); + for (const p of projRows) { + if (p.visibility === "private") privateProjectIds.add(p.id); + } + } + + for (let i = 0; i < plan.tasks.length; i += 1) { + const task = plan.tasks[i]!; + const cfg = resolvedTaskConfigs[i]!; + const issueNumber = firstIssueNumber + i; + const identifier = `${companyRow!.issuePrefix}-${issueNumber}`; + const scope: IssueScope = + (task.board ?? plan.board) ? "board" : channel ? "channel" : "board"; + const description = + task.description !== null + ? task.description + : task.blocks.length > 0 + ? formatBlocksAsFencedJson(task.blocks) + : null; + const taskVisibility: "open" | "private" = + channel?.visibility === "private" || + (cfg.projectId !== null && privateProjectIds.has(cfg.projectId)) + ? "private" + : "open"; + const taskIssueId = randomUUID(); + const privacyRootIssueId = taskVisibility === "private" ? taskIssueId : null; + + const [inserted] = await tx + .insert(issues) + .values({ + id: taskIssueId, + companyId, + projectId: cfg.projectId, + channelId: channel?.id ?? null, + visibility: taskVisibility, + privacyRootIssueId, + title: task.title, + description, + status: "todo", + scope, + priority: task.priority, + assigneeAgentId: cfg.assigneeAgentId, + createdByAgentId: actor.agentId, + createdByUserId: actor.agentId ? null : actor.userId, + createdByProfile: actor.actorProfile, + responsibleUserId: actor.responsibleUserId, + kvLabels: task.labels, + schemaBlocks: task.blocks, + resultSchemaRef: cfg.resultSchemaRef, + issueNumber, + identifier, + originKind: "manual", + createdAt: now, + updatedAt: now, + }) + .returning(); + + createdRows.push(inserted!); + keyByIssueId.set(inserted!.id, task.key); + if (task.key) { + createdByKey.set(task.key, inserted!); + } + + if (task.tagLabels.length > 0) { + await attachTagLabels(tx, companyId, inserted!.id, task.tagLabels); + } + + const blockerIds: string[] = []; + let hasOpenBlocker = false; + + for (const localKey of task.localNeeds) { + const blocker = createdByKey.get(localKey)!; + blockerIds.push(blocker.id); + hasOpenBlocker = true; + } + for (const extRef of task.externalNeeds) { + const ext = externalIssueByRef.get(extRef)!; + if (!blockerIds.includes(ext.id)) { + blockerIds.push(ext.id); + } + if (ext.status !== "done" && ext.status !== "cancelled") { + hasOpenBlocker = true; + } + } + + if (blockerIds.length > 0) { + await tx + .insert(issueRelations) + .values( + blockerIds.map((blockerId) => ({ + companyId, + issueId: blockerId, + relatedIssueId: inserted!.id, + type: "blocks" as const, + createdByAgentId: actor.agentId, + createdByUserId: actor.agentId ? null : actor.userId, + })), + ) + .onConflictDoNothing({ + target: [ + issueRelations.companyId, + issueRelations.issueId, + issueRelations.relatedIssueId, + issueRelations.type, + ], + }); + } + + await logActivity( + tx as unknown as Db, + { + companyId, + actorType: actor.principalType === "agent" ? "agent" : "user", + actorId: + actor.principalType === "agent" + ? actor.agentId! + : (actor.userId ?? "local-board"), + agentId: actor.agentId, + issueId: inserted!.id, + responsibleUserIdOverride: actor.responsibleUserId, + action: "issue.created", + entityType: "issue", + entityId: inserted!.id, + details: { + identifier, + channel: channel?.path ?? null, + batchKey: task.key, + blockedByIssueIds: blockerIds, + }, + }, + publications, + ); + + pendingEvents.push({ + issueId: inserted!.id, + identifier, + key: task.key ?? null, + type: "task.created", + isTaskCreated: true, + payload: { + key: task.key, + title: task.title, + ...(description ? { description: description.slice(0, 4000) } : {}), + blockedByIssueIds: blockerIds, + }, + }); + + if (!hasOpenBlocker && cfg.assigneeAgentId === null) { + pendingEvents.push({ + issueId: inserted!.id, + identifier, + key: task.key ?? null, + type: "task.ready", + payload: { key: task.key }, + }); + } + } + + if (channel) { + await tx + .update(channels) + .set({ lastActivityAt: now, updatedAt: now }) + .where(eq(channels.id, channel.id)); + } + + for (const evInput of pendingEvents) { + const evt = await appendBoardEvent(tx, { + companyId, + type: evInput.type, + channelId: channel?.id ?? null, + channelPath: channel?.path ?? null, + issueId: evInput.issueId, + identifier: evInput.identifier, + actor, + payload: evInput.payload, + }); + committedEvents.push(evt); + cursorByIssueId.set(evInput.issueId, evt.cursor); + } + + const issueViews = await loadHeadlessIssueViews(tx, createdRows); + const items: BatchCreatedTaskItem[] = issueViews.map((issueView) => { + const cursor = cursorByIssueId.get(issueView.id) ?? issueView.cursor; + return { + key: keyByIssueId.get(issueView.id) ?? null, + id: issueView.id, + identifier: issueView.identifier, + cursor, + issue: { + ...issueView, + cursor, + }, + }; + }); + + const latestCursor = + committedEvents[committedEvents.length - 1]?.cursor ?? "evt_0"; + const batchResult: BatchCreateIssuesResult = { + tasks: items, + cursor: latestCursor, + idempotentReplay: false, + }; + + if (plan.idempotencyKey) { + const [insertedKey] = await tx + .insert(issueBatchIdempotencyKeys) + .values({ + companyId, + idempotencyKey: plan.idempotencyKey, + requestHash, + responsePayload: batchResult as unknown as Record, + }) + .onConflictDoNothing({ + target: [ + issueBatchIdempotencyKeys.companyId, + issueBatchIdempotencyKeys.idempotencyKey, + ], + }) + .returning(); + + if (!insertedKey) { + const [raced] = await tx + .select() + .from(issueBatchIdempotencyKeys) + .where( + and( + eq(issueBatchIdempotencyKeys.companyId, companyId), + eq(issueBatchIdempotencyKeys.idempotencyKey, plan.idempotencyKey), + ), + ) + .limit(1); + if (raced && raced.requestHash === requestHash) { + return { + ...(raced.responsePayload as unknown as BatchCreateIssuesResult), + idempotentReplay: true, + }; + } + throw conflict( + "Idempotency key already used with a different plan payload", + { + error: "idempotency_conflict", + code: "idempotency_conflict", + idempotencyKey: plan.idempotencyKey, + }, + ); + } + } + + return batchResult; + }); + + if (!result.idempotentReplay) { + for (const pub of publications) { + publishActivity(pub); + } + for (const evt of committedEvents) { + publishCommittedBoardEvent(evt); + } + } + + return result; +} diff --git a/server/src/services/headless-schemas.ts b/server/src/services/headless-schemas.ts new file mode 100644 index 00000000000..cddfa66165e --- /dev/null +++ b/server/src/services/headless-schemas.ts @@ -0,0 +1,454 @@ +import { and, asc, eq } from "drizzle-orm"; +import { z } from "zod"; +import type { Db } from "@paperclipai/db"; +import { companySchemas } from "@paperclipai/db"; +import { + assertSafeRegexPattern, + BUILT_IN_COMPANY_SCHEMAS, + canonicalizeJsonSchema, + createCompanySchemaInputSchema, + parseSchemaRef, + schemaBlockSchema, + validateAgainstJsonSchema, + type CompanySchemaView, + type JsonSchemaObject, + type SchemaBlock, +} from "@paperclipai/shared"; +import { badRequest, conflict, notFound, unprocessable } from "../errors.js"; +import { logActivity, publishActivity, type ActivityPublication } from "./activity-log.js"; +import { enforceHeadlessScopes, type DbOrTx, type HeadlessActorContext } from "./headless-common.js"; + +const BUILT_IN_CREATED_AT = "1970-01-01T00:00:00.000Z"; + +function builtInSchemaToView( + entry: (typeof BUILT_IN_COMPANY_SCHEMAS)[number], +): CompanySchemaView { + return { + id: `builtin:${entry.ref}`, + companyId: null, + name: entry.name, + version: entry.version, + ref: entry.ref, + description: entry.description, + jsonSchema: entry.jsonSchema, + builtIn: true, + createdAt: BUILT_IN_CREATED_AT, + }; +} + +function customSchemaRowToView( + row: typeof companySchemas.$inferSelect, +): CompanySchemaView { + return { + id: row.id, + companyId: row.companyId, + name: row.name, + version: row.version, + ref: `${row.name}@${row.version}`, + description: row.description ?? null, + jsonSchema: row.jsonSchema as JsonSchemaObject, + builtIn: false, + createdAt: row.createdAt.toISOString(), + }; +} + +function findBuiltInSchema(name: string, version: number): CompanySchemaView | null { + const match = BUILT_IN_COMPANY_SCHEMAS.find( + (b) => b.name === name && b.version === version, + ); + return match ? builtInSchemaToView(match) : null; +} + +async function findCustomSchema( + dbOrTx: DbOrTx, + companyId: string, + name: string, + version: number, +): Promise { + const [row] = await dbOrTx + .select() + .from(companySchemas) + .where( + and( + eq(companySchemas.companyId, companyId), + eq(companySchemas.name, name), + eq(companySchemas.version, version), + ), + ) + .limit(1); + return row ? customSchemaRowToView(row) : null; +} + +async function resolveSchemaView( + dbOrTx: DbOrTx, + companyId: string, + name: string, + version: number, +): Promise { + const custom = await findCustomSchema(dbOrTx, companyId, name, version); + if (custom) return custom; + return findBuiltInSchema(name, version); +} + +export function formatBlocksAsFencedJson(blocks: SchemaBlock[]): string { + return blocks + .map( + (b) => + `\`\`\`json\n${JSON.stringify( + { schema: `${b.schema}@${b.version}`, data: b.data }, + null, + 2, + )}\n\`\`\``, + ) + .join("\n\n"); +} + +export async function listCompanySchemas( + dbOrTx: DbOrTx, + companyId: string, + actor?: HeadlessActorContext, +): Promise { + if (actor) { + enforceHeadlessScopes(actor, { action: "read" }); + } + const rows = await dbOrTx + .select() + .from(companySchemas) + .where(eq(companySchemas.companyId, companyId)) + .orderBy(asc(companySchemas.name), asc(companySchemas.version)); + + const customViews = rows.map(customSchemaRowToView); + const customRefs = new Set(customViews.map((s) => s.ref)); + const combined: CompanySchemaView[] = [ + ...customViews, + ...BUILT_IN_COMPANY_SCHEMAS.filter((b) => !customRefs.has(b.ref)).map( + builtInSchemaToView, + ), + ]; + + combined.sort((a, b) => { + const nameCmp = a.name.localeCompare(b.name); + if (nameCmp !== 0) return nameCmp; + return a.version - b.version; + }); + + return combined; +} + +export async function getCompanySchema( + dbOrTx: DbOrTx, + companyId: string, + ref: string, + actor?: HeadlessActorContext, +): Promise { + if (actor) { + enforceHeadlessScopes(actor, { action: "read" }); + } + let parsed: ReturnType; + try { + parsed = parseSchemaRef(ref); + } catch (err) { + throw badRequest( + err instanceof Error ? err.message : `Invalid schema ref "${ref}"`, + { error: "invalid_schema_ref", code: "invalid_schema_ref", ref }, + ); + } + + const found = await resolveSchemaView( + dbOrTx, + companyId, + parsed.name, + parsed.version, + ); + if (!found) { + throw notFound(`Schema '${parsed.ref}' not found`, { + error: "schema_not_found", + code: "schema_not_found", + ref: parsed.ref, + }); + } + return found; +} + +function assertSafeJsonSchemaPatterns(node: unknown, path = "$"): void { + if (Array.isArray(node)) { + for (let i = 0; i < node.length; i += 1) { + assertSafeJsonSchemaPatterns(node[i], `${path}[${i}]`); + } + return; + } + if (!node || typeof node !== "object") return; + const rec = node as Record; + if (typeof rec.pattern === "string") { + try { + assertSafeRegexPattern(rec.pattern); + } catch (err) { + throw badRequest( + `${path}.pattern: ${err instanceof Error ? err.message : "Invalid or unsafe regex pattern"}`, + { + error: "validation_error", + code: "validation_error", + }, + ); + } + } + if (rec.properties && typeof rec.properties === "object" && !Array.isArray(rec.properties)) { + for (const [k, v] of Object.entries(rec.properties as Record)) { + assertSafeJsonSchemaPatterns(v, `${path}.properties.${k}`); + } + } + if (rec.items !== undefined) { + assertSafeJsonSchemaPatterns(rec.items, `${path}.items`); + } + if (rec.additionalProperties && typeof rec.additionalProperties === "object") { + assertSafeJsonSchemaPatterns(rec.additionalProperties, `${path}.additionalProperties`); + } +} + +export async function createCompanySchema( + db: Db, + companyId: string, + actor: HeadlessActorContext, + rawInput: unknown, +): Promise<{ schema: CompanySchemaView; created: boolean }> { + enforceHeadlessScopes(actor, { action: "post" }); + const parsedInput = createCompanySchemaInputSchema.safeParse(rawInput); + if (!parsedInput.success) { + throw badRequest( + parsedInput.error.issues + .map((issue) => `${issue.path.join(".") || "$"}: ${issue.message}`) + .join("; "), + { + error: "validation_error", + code: "validation_error", + issues: parsedInput.error.issues, + }, + ); + } + + const input = parsedInput.data; + assertSafeJsonSchemaPatterns(input.jsonSchema); + const parsedRef = input.ref + ? parseSchemaRef(input.ref) + : parseSchemaRef(`${input.name!}@${input.version!}`); + + if ( + input.ref && + ((input.name && input.name !== parsedRef.name) || + (input.version !== undefined && input.version !== parsedRef.version)) + ) { + throw badRequest("Schema 'ref' disagrees with 'name' or 'version'", { + error: "validation_error", + code: "validation_error", + }); + } + + const incomingCanonical = canonicalizeJsonSchema(input.jsonSchema); + const builtIn = findBuiltInSchema(parsedRef.name, parsedRef.version); + if (builtIn) { + if (canonicalizeJsonSchema(builtIn.jsonSchema) === incomingCanonical) { + return { schema: builtIn, created: false }; + } + throw conflict( + `Built-in schema '${parsedRef.ref}' is immutable; register ${parsedRef.name}@${parsedRef.version + 1} instead`, + { + error: "schema_version_immutable", + code: "schema_version_immutable", + ref: parsedRef.ref, + }, + ); + } + + const publications: ActivityPublication[] = []; + const outcome = await db.transaction(async (tx) => { + const existing = await findCustomSchema( + tx, + companyId, + parsedRef.name, + parsedRef.version, + ); + if (existing) { + if (canonicalizeJsonSchema(existing.jsonSchema) === incomingCanonical) { + return { schema: existing, created: false }; + } + throw conflict( + `Schema '${parsedRef.ref}' already exists with a different definition; register ${parsedRef.name}@${parsedRef.version + 1} instead`, + { + error: "schema_version_immutable", + code: "schema_version_immutable", + ref: parsedRef.ref, + }, + ); + } + + const [inserted] = await tx + .insert(companySchemas) + .values({ + companyId, + name: parsedRef.name, + version: parsedRef.version, + description: input.description ?? null, + jsonSchema: input.jsonSchema, + createdByAgentId: actor.agentId, + createdByUserId: actor.agentId ? null : actor.userId, + createdByProfile: actor.actorProfile, + }) + .onConflictDoNothing({ + target: [ + companySchemas.companyId, + companySchemas.name, + companySchemas.version, + ], + }) + .returning(); + + if (!inserted) { + const raced = await findCustomSchema( + tx, + companyId, + parsedRef.name, + parsedRef.version, + ); + if (raced && canonicalizeJsonSchema(raced.jsonSchema) === incomingCanonical) { + return { schema: raced, created: false }; + } + throw conflict( + `Schema '${parsedRef.ref}' already exists with a different definition; register ${parsedRef.name}@${parsedRef.version + 1} instead`, + { + error: "schema_version_immutable", + code: "schema_version_immutable", + ref: parsedRef.ref, + }, + ); + } + + await logActivity( + tx as unknown as Db, + { + companyId, + actorType: actor.principalType === "agent" ? "agent" : "user", + actorId: + actor.principalType === "agent" + ? actor.agentId! + : (actor.userId ?? "local-board"), + agentId: actor.agentId, + responsibleUserIdOverride: actor.responsibleUserId, + action: "schema.created", + entityType: "company_schema", + entityId: inserted.id, + details: { + ref: parsedRef.ref, + name: parsedRef.name, + version: parsedRef.version, + }, + }, + publications, + ); + + return { schema: customSchemaRowToView(inserted), created: true }; + }); + + for (const pub of publications) { + publishActivity(pub); + } + + return outcome; +} + +const schemaBlockArraySchema = z.array(schemaBlockSchema); + +export async function validateSchemaBlocks( + dbOrTx: DbOrTx, + companyId: string, + blocks?: SchemaBlock[], +): Promise { + if (!blocks || blocks.length === 0) return []; + + const parsedBlocks = schemaBlockArraySchema.safeParse(blocks); + if (!parsedBlocks.success) { + throw unprocessable( + parsedBlocks.error.issues + .map((issue) => `${issue.path.join(".") || "$"}: ${issue.message}`) + .join("; "), + { + error: "schema_validation_failed", + code: "schema_validation_failed", + details: parsedBlocks.error.issues.map((i) => i.message), + }, + ); + } + + const cache = new Map(); + for (const block of parsedBlocks.data) { + const ref = `${block.schema}@${block.version}`; + let schemaView = cache.get(ref); + if (!schemaView) { + const resolved = await resolveSchemaView( + dbOrTx, + companyId, + block.schema, + block.version, + ); + if (!resolved) { + throw unprocessable(`Unknown schema '${ref}'`, { + error: "schema_validation_failed", + code: "schema_validation_failed", + schema: ref, + details: [`Unknown schema '${ref}'`], + }); + } + schemaView = resolved; + cache.set(ref, schemaView); + } + + const check = validateAgainstJsonSchema(schemaView.jsonSchema, block.data); + if (!check.valid) { + throw unprocessable( + `Block '${ref}' failed schema validation: ${check.errors.join("; ")}`, + { + error: "schema_validation_failed", + code: "schema_validation_failed", + schema: ref, + details: check.errors, + }, + ); + } + } + + return parsedBlocks.data; +} + +export async function assertSchemaExists( + dbOrTx: DbOrTx, + companyId: string, + ref: string, +): Promise { + let parsed: ReturnType; + try { + parsed = parseSchemaRef(ref); + } catch (err) { + throw unprocessable( + err instanceof Error ? err.message : `Invalid schema ref '${ref}'`, + { + error: "invalid_schema_ref", + code: "invalid_schema_ref", + ref, + }, + ); + } + + const found = await resolveSchemaView( + dbOrTx, + companyId, + parsed.name, + parsed.version, + ); + if (!found) { + throw unprocessable(`Unknown schema '${parsed.ref}'`, { + error: "schema_not_found", + code: "schema_not_found", + ref: parsed.ref, + }); + } + return parsed.ref; +} diff --git a/server/src/services/headless-task-queue.ts b/server/src/services/headless-task-queue.ts new file mode 100644 index 00000000000..680c828b00b --- /dev/null +++ b/server/src/services/headless-task-queue.ts @@ -0,0 +1,1865 @@ +import { createHash, randomBytes, timingSafeEqual } from "node:crypto"; +import { and, eq, gte, inArray, isNull, ne, sql, type SQL } from "drizzle-orm"; +import type { Db } from "@paperclipai/db"; +import { + activityLog, + boardEvents, + channels, + companySchemas, + issueComments, + issueLabels, + issueRelations, + issues, + issueWorkProducts, + labels, + projects, + toolActionRequests, +} from "@paperclipai/db"; +import { + BUILT_IN_COMPANY_SCHEMAS, + normalizeChannelPath, + parseDurationMs, + parseLabelFilterExpr, + parseSchemaRef, + TaskClaimRequestSchema, + TaskCompleteSchema, + TaskFailSchema, + TaskReleaseSchema, + TaskRenewSchema, + validateAgainstJsonSchema, + type BoardEventType, + type BoardEventView, + type ChannelQueueConfig, + type HeadlessIssueView, + type LabelFilterExpr, + type SchemaBlock, + type TaskClaimView, +} from "@paperclipai/shared"; +import { badRequest, conflict, forbidden, notFound, unprocessable } from "../errors.js"; +import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; +import { issueTreeControlService } from "./issue-tree-control.js"; +import { listIssueDependencyReadinessMap } from "./issues.js"; +import { assertRequiredQualityReviewComplete } from "./required-quality-review.js"; +import { + validateSchemaBlocks, +} from "./headless-schemas.js"; +import { + allowsUnchanneledScope, + appendBoardEvent, + assertChannelAccess, + assertIssueChannelScopeAccess, + canAccessChannel, + enforceHeadlessScopes, + loadHeadlessIssueView, + publishCommittedBoardEvent, + resolveIssueByIdOrIdentifier, + resolveProjectReference, + subscribeCompanyBoardEvents, + type DbOrTx, + type HeadlessActorContext, +} from "./headless-common.js"; + +const CLAIM_WAKE_EVENTS = new Set([ + "task.created", + "task.ready", + "task.lease_released", + "task.lease_expired_requeued", + "task.unblocked", + "interaction.resolved", + "labels.changed", +]); + +const DEFAULT_LEASE_SEC = 300; +const DEFAULT_MAX_LEASE_SEC = 3600; +const DEFAULT_MAX_CLAIM_ATTEMPTS = 3; + +export function generateClaimToken(): string { + return `clm_${randomBytes(24).toString("base64url")}`; +} + +export function hashClaimToken(token: string): string { + return createHash("sha256").update(token, "utf8").digest("hex"); +} + +export function verifyClaimToken( + storedHash: string | null | undefined, + incomingToken: string | null | undefined, +): boolean { + if (!storedHash || !incomingToken) return false; + const incomingHash = hashClaimToken(incomingToken); + const storedBuf = Buffer.from(storedHash, "utf8"); + const incomingBuf = Buffer.from(incomingHash, "utf8"); + if (storedBuf.length !== incomingBuf.length) return false; + return timingSafeEqual(storedBuf, incomingBuf); +} + +export function extractClaimToken( + bodyToken?: string | null, + headerToken?: string | null, +): string | undefined { + const headerVal = headerToken?.trim(); + if (headerVal) return headerVal; + const bodyVal = bodyToken?.trim(); + if (bodyVal) return bodyVal; + return undefined; +} + +function formatBlocksAsFencedJson(blocks: SchemaBlock[]): string { + return blocks + .map( + (b) => + `\`\`\`json schema=${b.schema}@${b.version}\n${JSON.stringify(b.data, null, 2)}\n\`\`\``, + ) + .join("\n\n"); +} + +function isChannelAllowedByScopes( + actor: HeadlessActorContext, + channelPath: string, +): boolean { + try { + enforceHeadlessScopes(actor, { channelPath }); + return true; + } catch { + return false; + } +} + +function checkChannelQueueEligibility( + queueConfig: ChannelQueueConfig | null | undefined, + actor: HeadlessActorContext, +): { ok: true } | { ok: false; code: string; message: string } { + if (!queueConfig) return { ok: true }; + if (queueConfig.allowedAgentIds && queueConfig.allowedAgentIds.length > 0) { + if (!actor.agentId || !queueConfig.allowedAgentIds.includes(actor.agentId)) { + return { + ok: false, + code: "channel_agent_denied", + message: "Caller agent is not in channel queueConfig.allowedAgentIds", + }; + } + } + if (queueConfig.allowedRoles && queueConfig.allowedRoles.length > 0) { + if (!actor.agentRole || !queueConfig.allowedRoles.includes(actor.agentRole)) { + return { + ok: false, + code: "channel_role_denied", + message: "Caller role is not in channel queueConfig.allowedRoles", + }; + } + } + return { ok: true }; +} + +function computeEffectiveLeaseSec( + requestedLeaseSec: number | undefined, + queueConfig: ChannelQueueConfig | null | undefined, +): number { + const defaultLeaseSec = queueConfig?.defaultLeaseSec ?? DEFAULT_LEASE_SEC; + const maxLeaseSec = queueConfig?.maxLeaseSec ?? DEFAULT_MAX_LEASE_SEC; + if (requestedLeaseSec !== undefined) { + return Math.max(1, Math.min(requestedLeaseSec, maxLeaseSec)); + } + return Math.max(1, Math.min(defaultLeaseSec, maxLeaseSec)); +} + +async function resolveJsonSchemaForRef( + dbOrTx: DbOrTx, + companyId: string, + schemaRef: string, +): Promise | null> { + const parsed = parseSchemaRef(schemaRef); + const [custom] = await dbOrTx + .select({ jsonSchema: companySchemas.jsonSchema }) + .from(companySchemas) + .where( + and( + eq(companySchemas.companyId, companyId), + eq(companySchemas.name, parsed.name), + eq(companySchemas.version, parsed.version), + ), + ) + .limit(1); + + if (custom) { + return custom.jsonSchema as Record; + } + + const builtIn = BUILT_IN_COMPANY_SCHEMAS.find( + (s) => s.name === parsed.name && s.version === parsed.version, + ); + return builtIn ? (builtIn.jsonSchema as Record) : null; +} + +function buildSqlLabelFilterCondition(expr: LabelFilterExpr) { + switch (expr.kind) { + case "equals": + return sql`i.kv_labels->>${expr.key} = ${expr.value}`; + case "in": + return sql`i.kv_labels->>${expr.key} IN (${sql.join( + expr.values.map((v) => sql`${v}`), + sql`, `, + )})`; + case "exists": + return sql`(jsonb_exists(i.kv_labels, ${expr.key}) OR EXISTS ( + SELECT 1 + FROM ${issueLabels} il + INNER JOIN ${labels} l ON l.id = il.label_id + WHERE il.issue_id = i.id AND l.name = ${expr.key} + ))`; + } +} + +function activityActorFields(actor: HeadlessActorContext) { + return { + actorType: actor.principalType === "agent" ? ("agent" as const) : ("user" as const), + actorId: + actor.principalType === "agent" + ? actor.agentId ?? "unknown-agent" + : actor.userId ?? "board", + agentId: actor.agentId ?? null, + responsibleUserId: actor.responsibleUserId ?? null, + }; +} + +function commentAuthorFields(actor: HeadlessActorContext) { + return { + authorType: actor.principalType === "agent" ? ("agent" as const) : ("user" as const), + authorAgentId: actor.agentId ?? null, + authorUserId: actor.agentId ? null : (actor.userId ?? null), + actorProfile: actor.actorProfile ?? null, + }; +} + +export async function claimTask( + db: Db, + companyId: string, + actor: HeadlessActorContext, + rawReq: unknown, + signal?: AbortSignal, + opts?: { readCondition?: SQL }, +): Promise { + const parsed = TaskClaimRequestSchema.parse(rawReq ?? {}); + + enforceHeadlessScopes(actor, { + action: "tasks.claim", + ...(parsed.channel ? { channelPath: parsed.channel } : {}), + }); + + if (!parsed.issueId && parsed.ready === false) { + throw badRequest("Either issueId or ready=true must be provided"); + } + + let requestedLeaseSec: number | undefined; + if (parsed.leaseSec !== undefined) { + requestedLeaseSec = parsed.leaseSec; + } else if (parsed.lease !== undefined) { + try { + requestedLeaseSec = Math.max(1, Math.round(parseDurationMs(parsed.lease) / 1000)); + } catch (err) { + throw badRequest(err instanceof Error ? err.message : "Invalid lease duration"); + } + } + + let waitMs = 0; + if (parsed.waitSec !== undefined) { + waitMs = Math.max(0, Math.floor(parsed.waitSec * 1000)); + } else if (parsed.wait !== undefined) { + try { + waitMs = Math.max(0, parseDurationMs(parsed.wait)); + } catch (err) { + throw badRequest(err instanceof Error ? err.message : "Invalid wait duration"); + } + } + + let labelExprs: LabelFilterExpr[] = []; + if (parsed.labels && parsed.labels.length > 0) { + try { + labelExprs = parsed.labels.map((expr) => parseLabelFilterExpr(expr)); + } catch (err) { + throw badRequest(err instanceof Error ? err.message : "Invalid label filter"); + } + } + + let normalizedChannel: { path: string; isSubtreePrefix: boolean } | null = null; + if (parsed.channel) { + try { + normalizedChannel = normalizeChannelPath(parsed.channel, { + allowSubtreePrefix: true, + }); + } catch (err) { + throw badRequest(err instanceof Error ? err.message : "Invalid channel path"); + } + } + + const projectIdFilter = parsed.projectId + ? await resolveProjectReference(db, companyId, parsed.projectId, actor) + : null; + + const tryClaimOnce = async (): Promise => { + const committed = await db.transaction(async (tx) => { + let lockedIssue: typeof issues.$inferSelect | undefined; + let targetChannel: typeof channels.$inferSelect | null = null; + + if (parsed.issueId) { + const resolved = await resolveIssueByIdOrIdentifier( + tx, + parsed.issueId, + companyId, + ); + if (opts?.readCondition) { + const [readable] = await tx + .select({ id: issues.id }) + .from(issues) + .where(and(eq(issues.id, resolved.id), opts.readCondition)) + .limit(1); + if (!readable) { + throw notFound("Issue not found"); + } + } + await tx.execute( + sql`SELECT id FROM issues WHERE id = ${resolved.id} AND company_id = ${companyId} FOR UPDATE`, + ); + const [fresh] = await tx + .select() + .from(issues) + .where(and(eq(issues.id, resolved.id), eq(issues.companyId, companyId))); + if (!fresh || fresh.hiddenAt !== null) { + throw conflict("task_not_claimable", { + code: "task_not_claimable", + status: fresh?.status ?? "hidden", + }); + } + + if (fresh.channelId) { + const [ch] = await tx + .select() + .from(channels) + .where(eq(channels.id, fresh.channelId)); + if (ch) { + targetChannel = ch; + await assertChannelAccess(tx, ch, actor); + const eligibility = checkChannelQueueEligibility(ch.queueConfig, actor); + if (!eligibility.ok) { + throw forbidden(eligibility.message, { code: eligibility.code }); + } + } + } else if (!allowsUnchanneledScope(actor)) { + throw forbidden("Caller scopes do not allow claiming unchanneled tasks", { + code: "scope_denied", + }); + } + + if ( + fresh.assigneeAgentId && + fresh.assigneeAgentId !== actor.agentId + ) { + throw conflict("task_not_claimable", { + code: "task_not_claimable", + status: fresh.status, + reason: "assigned_to_other_agent", + }); + } + if (fresh.assigneeUserId && fresh.assigneeUserId !== actor.userId) { + throw conflict("task_not_claimable", { + code: "task_not_claimable", + status: fresh.status, + reason: "assigned_to_other_user", + }); + } + if (fresh.status !== "todo") { + throw conflict("task_not_claimable", { + code: "task_not_claimable", + status: fresh.status, + }); + } + + const readiness = ( + await listIssueDependencyReadinessMap( + tx as unknown as Db, + companyId, + [fresh.id], + false, + ) + ).get(fresh.id); + + if (readiness && !readiness.isDependencyReady) { + throw conflict("task_not_claimable", { + code: "task_not_claimable", + status: fresh.status, + reason: "blocked_by_dependencies", + }); + } + + const activePauseHold = await issueTreeControlService(db).getActivePauseHoldGate( + companyId, + fresh.id, + ); + if (activePauseHold) { + throw conflict("Issue tree is currently paused", { + code: "issue_paused", + holdId: activePauseHold.holdId, + rootIssueId: activePauseHold.rootIssueId, + }); + } + + if (fresh.projectId) { + const [projectRow] = await tx + .select({ + id: projects.id, + pausedAt: projects.pausedAt, + pauseReason: projects.pauseReason, + }) + .from(projects) + .where(and(eq(projects.id, fresh.projectId), eq(projects.companyId, companyId))) + .limit(1); + if (projectRow?.pausedAt) { + throw conflict( + projectRow.pauseReason === "budget" + ? "Project is paused because its budget hard-stop was reached" + : "Project is paused", + { + code: "project_paused", + projectId: projectRow.id, + }, + ); + } + } + + lockedIssue = fresh; + } else { + // Ready pool pop via FOR UPDATE SKIP LOCKED + const companyChannels = await tx + .select() + .from(channels) + .where(and(eq(channels.companyId, companyId), isNull(channels.archivedAt))); + + const channelById = new Map(companyChannels.map((c) => [c.id, c])); + let eligibleChannelIds: string[] | null = null; + let inaccessibleChannelIds: string[] = []; + let strictFifo = false; + + if (normalizedChannel) { + const matchingChannels = companyChannels.filter((c) => + normalizedChannel.isSubtreePrefix + ? c.path === normalizedChannel.path || + c.path.startsWith(`${normalizedChannel.path}/`) + : c.path === normalizedChannel.path, + ); + const accessible: Array = []; + for (const ch of matchingChannels) { + if (!isChannelAllowedByScopes(actor, ch.path)) continue; + if (!(await canAccessChannel(tx, ch, actor))) continue; + if (!checkChannelQueueEligibility(ch.queueConfig, actor).ok) continue; + accessible.push(ch); + } + if (accessible.length === 0) { + return null; + } + eligibleChannelIds = accessible.map((c) => c.id); + if ( + !normalizedChannel.isSubtreePrefix && + accessible.length === 1 && + accessible[0]!.queueConfig?.ordering === "strict_fifo" + ) { + strictFifo = true; + } + } else { + for (const ch of companyChannels) { + const allowedScope = isChannelAllowedByScopes(actor, ch.path); + const allowedMember = await canAccessChannel(tx, ch, actor); + const allowedQueue = checkChannelQueueEligibility( + ch.queueConfig, + actor, + ).ok; + if (!allowedScope || !allowedMember || !allowedQueue) { + inaccessibleChannelIds.push(ch.id); + } + } + } + + const conditions = [ + sql`i.company_id = ${companyId}`, + sql`i.status = 'todo'`, + sql`i.assignee_agent_id IS NULL`, + sql`i.assignee_user_id IS NULL`, + sql`i.hidden_at IS NULL`, + sql`i.conversation_agent_id IS NULL`, + sql`NOT EXISTS ( + SELECT 1 + FROM issue_relations ir + INNER JOIN issues bi ON bi.id = ir.issue_id + WHERE ir.company_id = i.company_id + AND ir.related_issue_id = i.id + AND ir.type = 'blocks' + AND bi.status <> 'done' + )`, + sql`NOT EXISTS ( + WITH RECURSIVE tree_anc(id, parent_id, depth) AS ( + SELECT i.id, i.parent_id, 1 + UNION ALL + SELECT p.id, p.parent_id, tree_anc.depth + 1 + FROM tree_anc + JOIN issues p ON p.id = tree_anc.parent_id AND p.company_id = i.company_id + WHERE tree_anc.depth < 32 + ) + SELECT 1 + FROM tree_anc + JOIN issue_tree_holds h ON h.root_issue_id = tree_anc.id + WHERE h.company_id = i.company_id + AND h.status = 'active' + AND h.mode = 'pause' + )`, + ]; + + if (eligibleChannelIds !== null) { + conditions.push( + sql`i.channel_id IN (${sql.join( + eligibleChannelIds.map((id) => sql`${id}`), + sql`, `, + )})`, + ); + } else { + if (!allowsUnchanneledScope(actor)) { + conditions.push(sql`i.channel_id IS NOT NULL`); + } + if (inaccessibleChannelIds.length > 0) { + conditions.push( + sql`(i.channel_id IS NULL OR i.channel_id NOT IN (${sql.join( + inaccessibleChannelIds.map((id) => sql`${id}`), + sql`, `, + )}))`, + ); + } + } + + if (projectIdFilter) { + conditions.push(sql`i.project_id = ${projectIdFilter}`); + } + if (opts?.readCondition) { + conditions.push( + sql`EXISTS (SELECT 1 FROM issues WHERE issues.id = i.id AND ${opts.readCondition})`, + ); + } + conditions.push( + sql`(i.project_id IS NULL OR NOT EXISTS ( + SELECT 1 FROM projects p + WHERE p.id = i.project_id + AND p.company_id = i.company_id + AND p.paused_at IS NOT NULL + ))`, + ); + + if (parsed.includeUntrusted !== true) { + conditions.push( + sql`(i.source_trust IS NULL OR (COALESCE(i.source_trust->>'level', '') <> 'untrusted' AND COALESCE(i.source_trust->>'disposition', '') <> 'quarantined'))`, + ); + } + + for (const expr of labelExprs) { + conditions.push(buildSqlLabelFilterCondition(expr)); + } + + const orderClause = strictFifo + ? sql`i.created_at ASC` + : sql`CASE i.priority + WHEN 'critical' THEN 0 + WHEN 'high' THEN 1 + WHEN 'medium' THEN 2 + WHEN 'low' THEN 3 + ELSE 4 + END ASC, i.created_at ASC`; + + const skippedCandidateIds: string[] = []; + let fresh: typeof issues.$inferSelect | undefined; + while (true) { + const loopConditions = + skippedCandidateIds.length > 0 + ? [ + ...conditions, + sql`i.id NOT IN (${sql.join( + skippedCandidateIds.map((id) => sql`${id}`), + sql`, `, + )})`, + ] + : conditions; + + const candidateRows = await tx.execute<{ id: string }>(sql` + SELECT i.id + FROM issues i + WHERE ${sql.join(loopConditions, sql` AND `)} + ORDER BY ${orderClause} + LIMIT 1 + FOR UPDATE OF i SKIP LOCKED + `); + + const candidateId = candidateRows[0]?.id; + if (!candidateId) { + return null; + } + + const readiness = ( + await listIssueDependencyReadinessMap( + tx as unknown as Db, + companyId, + [candidateId], + false, + ) + ).get(candidateId); + if (readiness && !readiness.isDependencyReady) { + skippedCandidateIds.push(candidateId); + continue; + } + + const [candidate] = await tx + .select() + .from(issues) + .where(eq(issues.id, candidateId)); + if (!candidate) return null; + fresh = candidate; + break; + } + + lockedIssue = fresh; + targetChannel = fresh.channelId + ? channelById.get(fresh.channelId) ?? null + : null; + } + + const effectiveLeaseSec = computeEffectiveLeaseSec( + requestedLeaseSec, + targetChannel?.queueConfig, + ); + const claimToken = generateClaimToken(); + const claimTokenHash = hashClaimToken(claimToken); + const now = new Date(); + const leaseExpiresAt = new Date(now.getTime() + effectiveLeaseSec * 1000); + const nextEpoch = Number(lockedIssue.claimEpoch ?? 0) + 1; + const nextAttemptCount = (lockedIssue.claimAttemptCount ?? 0) + 1; + + await notifyDeliveryWork(tx, DELIVERY_QUEUES.claimLeaseExpiry, lockedIssue.id); + + const [updated] = await tx + .update(issues) + .set({ + status: "in_progress", + startedAt: lockedIssue.startedAt ?? now, + claimEpoch: nextEpoch, + claimAttemptCount: nextAttemptCount, + claimTokenHash, + claimHolderAgentId: actor.agentId ?? null, + claimHolderUserId: actor.agentId ? null : (actor.userId ?? null), + claimHolderProfile: actor.actorProfile ?? null, + claimLeasedAt: now, + claimLeaseExpiresAt: leaseExpiresAt, + updatedAt: now, + }) + .where(eq(issues.id, lockedIssue.id)) + .returning(); + + const actorInfo = activityActorFields(actor); + await tx.insert(activityLog).values({ + companyId, + ...actorInfo, + action: "issue.claimed", + entityType: "issue", + entityId: updated!.id, + details: { + claimEpoch: nextEpoch, + claimAttemptCount: nextAttemptCount, + leaseExpiresAt: leaseExpiresAt.toISOString(), + holderProfile: updated!.claimHolderProfile, + }, + }); + + const event = await appendBoardEvent(tx, { + companyId, + type: "task.claimed", + channelId: updated!.channelId, + channelPath: targetChannel?.path ?? null, + issueId: updated!.id, + identifier: updated!.identifier ?? updated!.id, + actor, + payload: { + claimEpoch: nextEpoch, + claimAttemptCount: nextAttemptCount, + leaseExpiresAt: leaseExpiresAt.toISOString(), + holderProfile: updated!.claimHolderProfile, + kvLabels: updated!.kvLabels ?? {}, + }, + }); + + const issueView = await loadHeadlessIssueView(tx, updated!.id, event.cursor); + + return { + event, + claimView: { + issue: issueView, + claimToken, + claimEpoch: nextEpoch, + leaseExpiresAt: leaseExpiresAt.toISOString(), + cursor: event.cursor, + } satisfies TaskClaimView, + }; + }); + + if (!committed) return null; + publishCommittedBoardEvent(committed.event); + return committed.claimView; + }; + + const immediate = await tryClaimOnce(); + if (immediate || waitMs <= 0 || parsed.issueId) { + return immediate; + } + + const deadline = Date.now() + waitMs; + while (!signal?.aborted) { + const remaining = deadline - Date.now(); + if (remaining <= 0) return null; + + let woke = false; + let wakeResolve: (() => void) | null = null; + const unsubscribe = subscribeCompanyBoardEvents(companyId, (ev) => { + if (!CLAIM_WAKE_EVENTS.has(ev.type)) return; + woke = true; + wakeResolve?.(); + }); + + try { + // Re-check after subscribing so events committed right before subscribe are never missed. + const claimed = await tryClaimOnce(); + if (claimed) return claimed; + + if (signal?.aborted) return null; + const left = deadline - Date.now(); + if (left <= 0) return null; + + if (!woke) { + await new Promise((resolve) => { + let settled = false; + const finish = () => { + if (settled) return; + settled = true; + clearTimeout(timer); + signal?.removeEventListener("abort", finish); + wakeResolve = null; + resolve(); + }; + wakeResolve = finish; + const timer = setTimeout(finish, left); + signal?.addEventListener("abort", finish, { once: true }); + }); + } + } finally { + unsubscribe(); + } + } + + return null; +} + +export async function renewTaskClaim( + db: Db, + issueId: string, + actor: HeadlessActorContext, + rawInput: unknown, + headerToken?: string, +): Promise { + enforceHeadlessScopes(actor, { action: "tasks.claim_renew" }); + const input = TaskRenewSchema.parse(rawInput ?? {}); + const token = extractClaimToken(input.claimToken, headerToken); + + let requestedLeaseSec: number | undefined; + if (input.leaseSec !== undefined) { + requestedLeaseSec = input.leaseSec; + } else if (input.lease !== undefined) { + try { + requestedLeaseSec = Math.max(1, Math.round(parseDurationMs(input.lease) / 1000)); + } catch (err) { + throw badRequest(err instanceof Error ? err.message : "Invalid lease duration"); + } + } + + const committed = await db.transaction(async (tx) => { + await tx.execute( + sql`SELECT id FROM issues WHERE id = ${issueId} AND company_id = ${actor.companyId} FOR UPDATE`, + ); + const [issue] = await tx + .select() + .from(issues) + .where(and(eq(issues.id, issueId), eq(issues.companyId, actor.companyId))); + if (!issue) { + throw conflict("claim_lost", { code: "claim_lost", currentEpoch: 0 }); + } + + const { channel: targetChannel } = await assertIssueChannelScopeAccess( + tx, + issue, + actor, + ); + + const epochMatches = + input.claimEpoch === undefined || Number(issue.claimEpoch ?? 0) === input.claimEpoch; + if ( + issue.status !== "in_progress" || + !verifyClaimToken(issue.claimTokenHash, token) || + !epochMatches + ) { + throw conflict("claim_lost", { + code: "claim_lost", + currentEpoch: Number(issue.claimEpoch ?? 0), + status: issue.status, + }); + } + + // Laptop-sleep-safe: even if claimLeaseExpiresAt is in the past, token + epoch still match + // because the lease reconciler has not reassigned or expired this epoch yet. + const effectiveLeaseSec = computeEffectiveLeaseSec( + requestedLeaseSec, + targetChannel?.queueConfig, + ); + const now = new Date(); + const leaseExpiresAt = new Date(now.getTime() + effectiveLeaseSec * 1000); + + await notifyDeliveryWork(tx, DELIVERY_QUEUES.claimLeaseExpiry, issue.id); + + const [updated] = await tx + .update(issues) + .set({ + claimLeaseExpiresAt: leaseExpiresAt, + updatedAt: now, + }) + .where(eq(issues.id, issue.id)) + .returning(); + + const event = await appendBoardEvent(tx, { + companyId: issue.companyId, + type: "task.lease_renewed", + channelId: updated!.channelId, + channelPath: targetChannel?.path ?? null, + issueId: updated!.id, + identifier: updated!.identifier ?? updated!.id, + actor, + payload: { + claimEpoch: Number(updated!.claimEpoch ?? 0), + leaseExpiresAt: leaseExpiresAt.toISOString(), + }, + }); + + const issueView = await loadHeadlessIssueView(tx, updated!.id, event.cursor); + + return { + event, + claimView: { + issue: issueView, + claimToken: token!, + claimEpoch: Number(updated!.claimEpoch ?? 0), + leaseExpiresAt: leaseExpiresAt.toISOString(), + cursor: event.cursor, + } satisfies TaskClaimView, + }; + }); + + publishCommittedBoardEvent(committed.event); + return committed.claimView; +} + +export async function releaseTaskClaim( + db: Db, + issueId: string, + actor: HeadlessActorContext, + rawInput: unknown, + headerToken?: string, +): Promise<{ released: boolean; cursor: string }> { + enforceHeadlessScopes(actor, { action: "tasks.claim_release" }); + const input = TaskReleaseSchema.parse(rawInput ?? {}); + const token = extractClaimToken(input.claimToken, headerToken); + + const committed = await db.transaction(async (tx) => { + await tx.execute( + sql`SELECT id FROM issues WHERE id = ${issueId} AND company_id = ${actor.companyId} FOR UPDATE`, + ); + const [issue] = await tx + .select() + .from(issues) + .where(and(eq(issues.id, issueId), eq(issues.companyId, actor.companyId))); + if (!issue) { + throw conflict("claim_lost", { code: "claim_lost", currentEpoch: 0 }); + } + + const { channel: targetChannel } = await assertIssueChannelScopeAccess( + tx, + issue, + actor, + ); + + const epochMatches = + input.claimEpoch === undefined || Number(issue.claimEpoch ?? 0) === input.claimEpoch; + if ( + issue.status !== "in_progress" || + !verifyClaimToken(issue.claimTokenHash, token) || + !epochMatches + ) { + throw conflict("claim_lost", { + code: "claim_lost", + currentEpoch: Number(issue.claimEpoch ?? 0), + status: issue.status, + }); + } + + const now = new Date(); + await notifyDeliveryWork(tx, DELIVERY_QUEUES.claimLeaseExpiry, issue.id); + + const nextEpoch = Number(issue.claimEpoch ?? 0) + 1; + const [updated] = await tx + .update(issues) + .set({ + status: "todo", + claimEpoch: nextEpoch, + claimTokenHash: null, + claimLeasedAt: null, + claimLeaseExpiresAt: null, + claimHolderAgentId: null, + claimHolderUserId: null, + claimHolderProfile: null, + claimAttemptCount: Math.max(0, (issue.claimAttemptCount ?? 0) - 1), + updatedAt: now, + }) + .where(eq(issues.id, issue.id)) + .returning(); + + if (input.comment?.trim()) { + await tx.insert(issueComments).values({ + companyId: issue.companyId, + issueId: issue.id, + body: input.comment.trim(), + ...commentAuthorFields(actor), + }); + } + + const actorInfo = activityActorFields(actor); + await tx.insert(activityLog).values({ + companyId: issue.companyId, + ...actorInfo, + action: "issue.claim_released", + entityType: "issue", + entityId: updated!.id, + details: { + claimEpoch: Number(updated!.claimEpoch ?? 0), + }, + }); + + const releasedEvent = await appendBoardEvent(tx, { + companyId: issue.companyId, + type: "task.lease_released", + channelId: updated!.channelId, + channelPath: targetChannel?.path ?? null, + issueId: updated!.id, + identifier: updated!.identifier ?? updated!.id, + actor, + payload: { + claimEpoch: Number(updated!.claimEpoch ?? 0), + }, + }); + + const readyEvent = await appendBoardEvent(tx, { + companyId: issue.companyId, + type: "task.ready", + channelId: updated!.channelId, + channelPath: targetChannel?.path ?? null, + issueId: updated!.id, + identifier: updated!.identifier ?? updated!.id, + actor, + payload: { + kvLabels: updated!.kvLabels ?? {}, + }, + }); + + return { + events: [releasedEvent, readyEvent], + cursor: readyEvent.cursor, + }; + }); + + for (const ev of committed.events) { + publishCommittedBoardEvent(ev); + } + return { released: true, cursor: committed.cursor }; +} + +export async function completeTaskClaim( + db: Db, + issueId: string, + actor: HeadlessActorContext, + rawInput: unknown, + headerToken?: string, +): Promise { + enforceHeadlessScopes(actor, { action: "tasks.complete" }); + const input = TaskCompleteSchema.parse(rawInput ?? {}); + const token = extractClaimToken(input.claimToken, headerToken); + + const committed = await db.transaction(async (tx) => { + await tx.execute( + sql`SELECT id FROM issues WHERE id = ${issueId} AND company_id = ${actor.companyId} FOR UPDATE`, + ); + const [issue] = await tx + .select() + .from(issues) + .where(and(eq(issues.id, issueId), eq(issues.companyId, actor.companyId))); + if (!issue) { + throw conflict("claim_lost", { code: "claim_lost", currentEpoch: 0 }); + } + + const { channel: targetChannel } = await assertIssueChannelScopeAccess( + tx, + issue, + actor, + ); + + const epochMatches = + input.claimEpoch === undefined || Number(issue.claimEpoch ?? 0) === input.claimEpoch; + + if (issue.claimTokenHash !== null) { + if ( + issue.status !== "in_progress" || + !verifyClaimToken(issue.claimTokenHash, token) || + !epochMatches + ) { + throw conflict("claim_lost", { + code: "claim_lost", + currentEpoch: Number(issue.claimEpoch ?? 0), + status: issue.status, + }); + } + } else if ( + token !== undefined || + !epochMatches || + issue.status === "done" || + issue.status === "cancelled" + ) { + throw conflict("claim_lost", { + code: "claim_lost", + currentEpoch: Number(issue.claimEpoch ?? 0), + status: issue.status, + }); + } + + await assertRequiredQualityReviewComplete(tx as unknown as Db, issue, true); + if (actor.agentId) { + const [pendingToolReview] = await tx + .select({ id: toolActionRequests.id }) + .from(toolActionRequests) + .where( + and( + eq(toolActionRequests.companyId, issue.companyId), + eq(toolActionRequests.issueId, issue.id), + inArray(toolActionRequests.status, ["pending", "approved", "executing"]), + ), + ) + .limit(1); + if (pendingToolReview) { + throw conflict( + "This task is waiting for a connection review. Finish unrelated work, then yield in_review without retrying the governed call.", + { + code: "tool_review_pending", + actionRequestId: pendingToolReview.id, + }, + ); + } + } + + if ( + issue.resultSchemaRef && + input.resultSchema && + input.resultSchema.trim().toLowerCase() !== issue.resultSchemaRef.trim().toLowerCase() + ) { + throw conflict( + `Task requires result schema '${issue.resultSchemaRef}' and cannot be overridden with '${input.resultSchema}'`, + { + code: "result_schema_mismatch", + requiredResultSchema: issue.resultSchemaRef, + }, + ); + } + + const schemaRef = issue.resultSchemaRef ?? input.resultSchema ?? null; + const rawSchemaBlocks: SchemaBlock[] = [...(input.blocks ?? [])]; + if (input.data && schemaRef) { + const parsedRef = parseSchemaRef(schemaRef); + const alreadyHasBlock = rawSchemaBlocks.some( + (b) => b.schema === parsedRef.name && b.version === parsedRef.version, + ); + if (!alreadyHasBlock) { + rawSchemaBlocks.push({ + schema: parsedRef.name, + version: parsedRef.version, + data: input.data, + }); + } + } + + if (schemaRef) { + const parsedRef = parseSchemaRef(schemaRef); + const jsonSchema = await resolveJsonSchemaForRef( + tx, + issue.companyId, + parsedRef.ref, + ); + if (!jsonSchema) { + throw unprocessable( + `Result schema '${parsedRef.ref}' is not registered`, + { + code: "result_schema_validation_failed", + errors: [`Schema '${parsedRef.ref}' is not registered`], + next: [`pc schemas list`], + }, + ); + } + + const payloadToValidate = + input.data ?? + rawSchemaBlocks.find( + (b) => b.schema === parsedRef.name && b.version === parsedRef.version, + )?.data; + + if (payloadToValidate === undefined) { + throw unprocessable( + `Task requires structured '--data' matching resultSchema '${parsedRef.ref}'`, + { + code: "result_schema_validation_failed", + errors: [ + `Completion requires structured result data matching '${parsedRef.ref}'`, + ], + next: [`pc schemas get ${parsedRef.ref}`], + }, + ); + } + + const validation = validateAgainstJsonSchema(jsonSchema, payloadToValidate); + if (!validation.valid) { + throw unprocessable( + `Result data failed '${parsedRef.ref}' validation: ${validation.errors.join("; ")}`, + { + code: "result_schema_validation_failed", + errors: validation.errors, + next: [`pc schemas get ${parsedRef.ref}`], + }, + ); + } + } + + const schemaBlocks = + rawSchemaBlocks.length > 0 + ? await validateSchemaBlocks(tx as unknown as Db, issue.companyId, rawSchemaBlocks) + : []; + + const commentText = (input.message ?? input.comment)?.trim() || ""; + if (commentText || schemaBlocks.length > 0 || input.prUrl) { + const body = + commentText || + (schemaBlocks.length > 0 + ? formatBlocksAsFencedJson(schemaBlocks) + : `Completed (${input.prUrl})`); + await tx.insert(issueComments).values({ + companyId: issue.companyId, + issueId: issue.id, + body, + schemaBlocks, + ...commentAuthorFields(actor), + }); + } + + if (input.prUrl) { + await tx.insert(issueWorkProducts).values({ + companyId: issue.companyId, + projectId: issue.projectId ?? null, + issueId: issue.id, + type: "pull_request", + provider: "github", + url: input.prUrl, + title: "Pull Request", + status: "ready_for_review", + }); + } + + const now = new Date(); + if (issue.claimTokenHash !== null) { + await notifyDeliveryWork(tx, DELIVERY_QUEUES.claimLeaseExpiry, issue.id); + } + + const [updated] = await tx + .update(issues) + .set({ + status: "done", + completedAt: now, + claimTokenHash: null, + claimLeasedAt: null, + claimLeaseExpiresAt: null, + claimHolderAgentId: null, + claimHolderUserId: null, + claimHolderProfile: null, + updatedAt: now, + }) + .where(eq(issues.id, issue.id)) + .returning(); + + const actorInfo = activityActorFields(actor); + await tx.insert(activityLog).values({ + companyId: issue.companyId, + ...actorInfo, + action: "issue.completed", + entityType: "issue", + entityId: updated!.id, + details: { + claimEpoch: Number(updated!.claimEpoch ?? 0), + ...(input.prUrl ? { prUrl: input.prUrl } : {}), + }, + }); + + // Check and lock dependent issues BEFORE acquiring the company board_events advisory lock + // so all issue row locks precede the board_events lock consistently across transactions. + const dependentLinks = await tx + .select({ relatedIssueId: issueRelations.relatedIssueId }) + .from(issueRelations) + .where( + and( + eq(issueRelations.companyId, issue.companyId), + eq(issueRelations.issueId, issue.id), + eq(issueRelations.type, "blocks"), + ), + ); + + const pendingUnblockEvents: Array<{ + dep: typeof issues.$inferSelect; + depChannelPath: string | null; + unblockPayload: Record; + }> = []; + + if (dependentLinks.length > 0) { + const dependentIds = Array.from( + new Set(dependentLinks.map((d) => d.relatedIssueId)), + ).sort(); + await tx.execute( + sql`SELECT id FROM issues WHERE company_id = ${issue.companyId} AND id IN (${sql.join( + dependentIds.map((id) => sql`${id}`), + sql`, `, + )}) ORDER BY id FOR UPDATE`, + ); + const dependentRows = await tx + .select() + .from(issues) + .where( + and( + eq(issues.companyId, issue.companyId), + inArray(issues.id, dependentIds), + eq(issues.status, "todo"), + isNull(issues.hiddenAt), + ), + ); + + const depChannelIds = Array.from( + new Set( + dependentRows + .map((d) => d.channelId) + .filter((id): id is string => Boolean(id)), + ), + ); + const depChannelRows = + depChannelIds.length > 0 + ? await tx + .select({ id: channels.id, path: channels.path }) + .from(channels) + .where(inArray(channels.id, depChannelIds)) + : []; + const depChannelMap = new Map(depChannelRows.map((c) => [c.id, c.path])); + + const dependentReadinessMap = await listIssueDependencyReadinessMap( + tx as unknown as Db, + issue.companyId, + dependentRows.map((d) => d.id), + false, + ); + + for (const dep of dependentRows) { + const depReadiness = dependentReadinessMap.get(dep.id); + if (!depReadiness || depReadiness.isDependencyReady) { + const depChannelPath = dep.channelId + ? depChannelMap.get(dep.channelId) ?? null + : null; + pendingUnblockEvents.push({ + dep, + depChannelPath, + unblockPayload: { + unblockedByIssueId: updated!.id, + unblockedByIdentifier: updated!.identifier ?? updated!.id, + kvLabels: dep.kvLabels ?? {}, + }, + }); + } + } + } + + const eventsToPublish: BoardEventView[] = []; + const completedEvent = await appendBoardEvent(tx, { + companyId: issue.companyId, + type: "task.completed", + channelId: updated!.channelId, + channelPath: targetChannel?.path ?? null, + issueId: updated!.id, + identifier: updated!.identifier ?? updated!.id, + actor, + payload: { + claimEpoch: Number(updated!.claimEpoch ?? 0), + blocks: schemaBlocks, + ...(input.prUrl ? { prUrl: input.prUrl } : {}), + kvLabels: updated!.kvLabels ?? {}, + }, + }); + eventsToPublish.push(completedEvent); + + for (const item of pendingUnblockEvents) { + eventsToPublish.push( + ...(await appendPoolDependentUnblockBoardEvents(tx, { + companyId: issue.companyId, + dep: item.dep, + channelPath: item.depChannelPath, + actor, + payload: item.unblockPayload, + })), + ); + } + + const issueView = await loadHeadlessIssueView( + tx, + updated!.id, + completedEvent.cursor, + ); + return { events: eventsToPublish, issueView }; + }); + + for (const ev of committed.events) { + publishCommittedBoardEvent(ev); + } + return committed.issueView; +} + +async function appendPoolDependentUnblockBoardEvents( + tx: DbOrTx, + args: { + companyId: string; + dep: typeof issues.$inferSelect; + channelPath: string | null; + actor: HeadlessActorContext | { principalType: "system"; actorProfile?: string | null }; + payload: Record; + }, +): Promise { + const unblockedEvent = await appendBoardEvent(tx, { + companyId: args.companyId, + type: "task.unblocked", + channelId: args.dep.channelId, + channelPath: args.channelPath, + issueId: args.dep.id, + identifier: args.dep.identifier ?? args.dep.id, + actor: args.actor, + payload: args.payload, + }); + const readyEvent = await appendBoardEvent(tx, { + companyId: args.companyId, + type: "task.ready", + channelId: args.dep.channelId, + channelPath: args.channelPath, + issueId: args.dep.id, + identifier: args.dep.identifier ?? args.dep.id, + actor: args.actor, + payload: args.payload, + }); + return [unblockedEvent, readyEvent]; +} + +export async function wakeReadyPoolDependentsForBlocker( + db: Db, + blockerIssueId: string, +): Promise { + const events = await db.transaction(async (tx) => { + const [blocker] = await tx + .select({ + id: issues.id, + companyId: issues.companyId, + identifier: issues.identifier, + status: issues.status, + completedAt: issues.completedAt, + updatedAt: issues.updatedAt, + }) + .from(issues) + .where(eq(issues.id, blockerIssueId)) + .limit(1); + if (!blocker || blocker.status !== "done") { + return [] as BoardEventView[]; + } + + const dependentLinks = await tx + .select({ relatedIssueId: issueRelations.relatedIssueId }) + .from(issueRelations) + .where( + and( + eq(issueRelations.companyId, blocker.companyId), + eq(issueRelations.issueId, blocker.id), + eq(issueRelations.type, "blocks"), + ), + ); + if (dependentLinks.length === 0) { + return [] as BoardEventView[]; + } + + const dependentIds = Array.from( + new Set(dependentLinks.map((d) => d.relatedIssueId)), + ).sort(); + await tx.execute( + sql`SELECT id FROM issues WHERE company_id = ${blocker.companyId} AND id IN (${sql.join( + dependentIds.map((id) => sql`${id}`), + sql`, `, + )}) ORDER BY id FOR UPDATE`, + ); + + const dependentRows = await tx + .select() + .from(issues) + .where( + and( + eq(issues.companyId, blocker.companyId), + inArray(issues.id, dependentIds), + eq(issues.status, "todo"), + isNull(issues.assigneeAgentId), + isNull(issues.assigneeUserId), + isNull(issues.conversationAgentId), + isNull(issues.hiddenAt), + ), + ); + if (dependentRows.length === 0) { + return [] as BoardEventView[]; + } + + const readinessMap = await listIssueDependencyReadinessMap( + tx as unknown as Db, + blocker.companyId, + dependentRows.map((d) => d.id), + false, + ); + const readyDeps = dependentRows.filter((dep) => { + const readiness = readinessMap.get(dep.id); + return !readiness || readiness.isDependencyReady; + }); + if (readyDeps.length === 0) { + return [] as BoardEventView[]; + } + + const cycleStart = blocker.completedAt ?? blocker.updatedAt; + const alreadyNotifiedRows = await tx + .select({ issueId: boardEvents.issueId }) + .from(boardEvents) + .where( + and( + eq(boardEvents.companyId, blocker.companyId), + inArray( + boardEvents.issueId, + readyDeps.map((d) => d.id), + ), + eq(boardEvents.eventType, "task.ready"), + sql`${boardEvents.payload}->>'unblockedByIssueId' = ${blocker.id}`, + gte(boardEvents.createdAt, cycleStart), + ), + ); + const notifiedIds = new Set( + alreadyNotifiedRows + .map((r) => r.issueId) + .filter((id): id is string => Boolean(id)), + ); + + const pendingDeps = readyDeps.filter((dep) => !notifiedIds.has(dep.id)); + if (pendingDeps.length === 0) { + return [] as BoardEventView[]; + } + + const depChannelIds = Array.from( + new Set( + pendingDeps + .map((d) => d.channelId) + .filter((id): id is string => Boolean(id)), + ), + ); + const depChannelRows = + depChannelIds.length > 0 + ? await tx + .select({ id: channels.id, path: channels.path }) + .from(channels) + .where(inArray(channels.id, depChannelIds)) + : []; + const depChannelMap = new Map(depChannelRows.map((c) => [c.id, c.path])); + const systemActor = { + principalType: "system" as const, + actorProfile: "workspace-finalize", + }; + + const emitted: BoardEventView[] = []; + for (const dep of pendingDeps) { + emitted.push( + ...(await appendPoolDependentUnblockBoardEvents(tx, { + companyId: blocker.companyId, + dep, + channelPath: dep.channelId + ? depChannelMap.get(dep.channelId) ?? null + : null, + actor: systemActor, + payload: { + unblockedByIssueId: blocker.id, + unblockedByIdentifier: blocker.identifier ?? blocker.id, + kvLabels: dep.kvLabels ?? {}, + source: "workspace.finalize", + }, + })), + ); + } + return emitted; + }); + + for (const ev of events) { + publishCommittedBoardEvent(ev); + } + return events.length / 2; +} + +export async function failTaskClaim( + db: Db, + issueId: string, + actor: HeadlessActorContext, + rawInput: unknown, + headerToken?: string, +): Promise { + enforceHeadlessScopes(actor, { action: "tasks.fail" }); + const input = TaskFailSchema.parse(rawInput ?? {}); + const token = extractClaimToken(input.claimToken, headerToken); + + const committed = await db.transaction(async (tx) => { + await tx.execute( + sql`SELECT id FROM issues WHERE id = ${issueId} AND company_id = ${actor.companyId} FOR UPDATE`, + ); + const [issue] = await tx + .select() + .from(issues) + .where(and(eq(issues.id, issueId), eq(issues.companyId, actor.companyId))); + if (!issue) { + throw conflict("claim_lost", { code: "claim_lost", currentEpoch: 0 }); + } + + const { channel: targetChannel } = await assertIssueChannelScopeAccess( + tx, + issue, + actor, + ); + + const epochMatches = + input.claimEpoch === undefined || Number(issue.claimEpoch ?? 0) === input.claimEpoch; + if ( + issue.status !== "in_progress" || + !verifyClaimToken(issue.claimTokenHash, token) || + !epochMatches + ) { + throw conflict("claim_lost", { + code: "claim_lost", + currentEpoch: Number(issue.claimEpoch ?? 0), + status: issue.status, + }); + } + + await tx.insert(issueComments).values({ + companyId: issue.companyId, + issueId: issue.id, + body: input.reason, + ...commentAuthorFields(actor), + }); + + const maxAttempts = + targetChannel?.queueConfig?.maxClaimAttempts ?? DEFAULT_MAX_CLAIM_ATTEMPTS; + const attemptCount = issue.claimAttemptCount ?? 0; + const shouldRequeue = input.requeue !== false && attemptCount < maxAttempts; + const now = new Date(); + + await notifyDeliveryWork(tx, DELIVERY_QUEUES.claimLeaseExpiry, issue.id); + + const [updated] = await tx + .update(issues) + .set({ + status: shouldRequeue ? "todo" : "blocked", + blockedTransitionAt: shouldRequeue ? issue.blockedTransitionAt : now, + claimTokenHash: null, + claimLeasedAt: null, + claimLeaseExpiresAt: null, + claimHolderAgentId: null, + claimHolderUserId: null, + claimHolderProfile: null, + updatedAt: now, + }) + .where(eq(issues.id, issue.id)) + .returning(); + + const actorInfo = activityActorFields(actor); + await tx.insert(activityLog).values({ + companyId: issue.companyId, + ...actorInfo, + action: shouldRequeue ? "issue.claim_failed_requeued" : "issue.claim_poison_blocked", + entityType: "issue", + entityId: updated!.id, + details: { + reason: input.reason, + claimEpoch: Number(updated!.claimEpoch ?? 0), + claimAttemptCount: attemptCount, + maxAttempts, + }, + }); + + const eventsToPublish: BoardEventView[] = []; + const failedEvent = await appendBoardEvent(tx, { + companyId: issue.companyId, + type: "task.failed", + channelId: updated!.channelId, + channelPath: targetChannel?.path ?? null, + issueId: updated!.id, + identifier: updated!.identifier ?? updated!.id, + actor, + payload: { + reason: input.reason, + claimAttemptCount: attemptCount, + requeued: shouldRequeue, + }, + }); + eventsToPublish.push(failedEvent); + + if (shouldRequeue) { + eventsToPublish.push( + await appendBoardEvent(tx, { + companyId: issue.companyId, + type: "task.ready", + channelId: updated!.channelId, + channelPath: targetChannel?.path ?? null, + issueId: updated!.id, + identifier: updated!.identifier ?? updated!.id, + actor, + payload: { + kvLabels: updated!.kvLabels ?? {}, + }, + }), + ); + } else { + eventsToPublish.push( + await appendBoardEvent(tx, { + companyId: issue.companyId, + type: "task.lease_poison_blocked", + channelId: updated!.channelId, + channelPath: targetChannel?.path ?? null, + issueId: updated!.id, + identifier: updated!.identifier ?? updated!.id, + actor, + payload: { + reason: input.reason, + claimAttemptCount: attemptCount, + maxAttempts, + }, + }), + ); + } + + const lastCursor = eventsToPublish[eventsToPublish.length - 1]!.cursor; + const issueView = await loadHeadlessIssueView(tx, updated!.id, lastCursor); + return { events: eventsToPublish, issueView }; + }); + + for (const ev of committed.events) { + publishCommittedBoardEvent(ev); + } + return committed.issueView; +} + +export function createClaimLeaseExpiryWorker(db: Db) { + let cachedNextDueMs: number | null = null; + + async function refreshNextDueAt(): Promise { + const result = await db.execute<{ min_due: Date | string | null }>(sql` + SELECT MIN(claim_lease_expires_at) AS min_due + FROM issues + WHERE status = 'in_progress' + AND claim_lease_expires_at IS NOT NULL + AND claim_token_hash IS NOT NULL + `); + const raw = result[0]?.min_due ?? null; + if (!raw) { + cachedNextDueMs = null; + return null; + } + const ms = raw instanceof Date ? raw.getTime() : Date.parse(String(raw)); + cachedNextDueMs = Number.isFinite(ms) ? ms : null; + return cachedNextDueMs; + } + + async function expireDueClaimLeases(signal?: AbortSignal): Promise { + let totalExpired = 0; + const batchLimit = 50; + + while (!signal?.aborted) { + const committed = await db.transaction(async (tx) => { + const dueResult = await tx.execute<{ id: string }>(sql` + SELECT id + FROM issues + WHERE status = 'in_progress' + AND claim_lease_expires_at IS NOT NULL + AND claim_token_hash IS NOT NULL + AND claim_lease_expires_at <= now() + ORDER BY claim_lease_expires_at ASC + LIMIT ${batchLimit} + FOR UPDATE OF issues SKIP LOCKED + `); + + const dueIds = Array.from(dueResult).map((r) => r.id); + if (dueIds.length === 0) { + return { expiredCount: 0, events: [] as BoardEventView[] }; + } + + const dueRows = await tx + .select() + .from(issues) + .where(inArray(issues.id, dueIds)); + + const channelIds = Array.from( + new Set( + dueRows + .map((r) => r.channelId) + .filter((id): id is string => Boolean(id)), + ), + ); + const channelRows = + channelIds.length > 0 + ? await tx + .select() + .from(channels) + .where(inArray(channels.id, channelIds)) + : []; + const channelMap = new Map(channelRows.map((c) => [c.id, c])); + + const now = new Date(); + const events: BoardEventView[] = []; + const systemActor = { + principalType: "system" as const, + actorProfile: "lease-reconciler", + }; + + for (const row of dueRows) { + const ch = row.channelId ? channelMap.get(row.channelId) ?? null : null; + const maxAttempts = + ch?.queueConfig?.maxClaimAttempts ?? DEFAULT_MAX_CLAIM_ATTEMPTS; + const attemptCount = row.claimAttemptCount ?? 0; + const shouldRequeue = attemptCount < maxAttempts; + const nextEpoch = Number(row.claimEpoch ?? 0) + 1; + + await tx + .update(issues) + .set({ + status: shouldRequeue ? "todo" : "blocked", + blockedTransitionAt: shouldRequeue ? row.blockedTransitionAt : now, + claimEpoch: nextEpoch, + claimTokenHash: null, + claimLeasedAt: null, + claimLeaseExpiresAt: null, + claimHolderAgentId: null, + claimHolderUserId: null, + claimHolderProfile: null, + updatedAt: now, + }) + .where(eq(issues.id, row.id)); + + if (shouldRequeue) { + events.push( + await appendBoardEvent(tx, { + companyId: row.companyId, + type: "task.lease_expired_requeued", + channelId: row.channelId, + channelPath: ch?.path ?? null, + issueId: row.id, + identifier: row.identifier ?? row.id, + actor: systemActor, + payload: { + claimEpoch: nextEpoch, + claimAttemptCount: attemptCount, + maxAttempts, + }, + }), + ); + events.push( + await appendBoardEvent(tx, { + companyId: row.companyId, + type: "task.ready", + channelId: row.channelId, + channelPath: ch?.path ?? null, + issueId: row.id, + identifier: row.identifier ?? row.id, + actor: systemActor, + payload: { + kvLabels: row.kvLabels ?? {}, + }, + }), + ); + } else { + events.push( + await appendBoardEvent(tx, { + companyId: row.companyId, + type: "task.lease_poison_blocked", + channelId: row.channelId, + channelPath: ch?.path ?? null, + issueId: row.id, + identifier: row.identifier ?? row.id, + actor: systemActor, + payload: { + claimEpoch: nextEpoch, + claimAttemptCount: attemptCount, + maxAttempts, + reason: "lease_expired_max_attempts", + }, + }), + ); + } + } + + return { expiredCount: dueRows.length, events }; + }); + + for (const ev of committed.events) { + publishCommittedBoardEvent(ev); + } + + totalExpired += committed.expiredCount; + if (committed.expiredCount < batchLimit) break; + } + + await refreshNextDueAt(); + return totalExpired; + } + + return { + expireDueClaimLeases, + refreshNextDueAt, + nextRunAt: () => cachedNextDueMs, + deliveryTask: { + retryMs: 5_000, + coalesceMs: 50, + pausePassiveMaintenance: true, + run: async (signal: AbortSignal) => { + await expireDueClaimLeases(signal); + }, + hasPending: async (runAllowed = true) => { + if (!runAllowed) return false; + return cachedNextDueMs !== null && cachedNextDueMs <= Date.now(); + }, + nextRunAt: () => cachedNextDueMs, + nextRunAtOnError: () => cachedNextDueMs, + }, + }; +} diff --git a/server/src/services/issue-comment-writes.ts b/server/src/services/issue-comment-writes.ts index 32cd4407dd6..59de1b1cb96 100644 --- a/server/src/services/issue-comment-writes.ts +++ b/server/src/services/issue-comment-writes.ts @@ -6,7 +6,10 @@ import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notificatio type WriteDb = Db | Parameters[0]>[0]; -export function insertIssueComment(db: WriteDb, input: PgInsertValue & { companyId: string }) { +export function insertIssueComment( + db: WriteDb, + input: PgInsertValue & { companyId: string }, +): Promise> { return db.transaction(async tx => { await notifyStatusCardIssueChange(tx, input.companyId); await notifyIssueRecovery(tx, { companyId: input.companyId, diff --git a/server/src/services/issue-thread-interactions.ts b/server/src/services/issue-thread-interactions.ts index 218ebe544b5..c5c5b85092b 100644 --- a/server/src/services/issue-thread-interactions.ts +++ b/server/src/services/issue-thread-interactions.ts @@ -43,6 +43,7 @@ import type { Db } from "@paperclipai/db"; import { agents, assets, + channels, chatVoiceSessions, authUsers, companySecretProposals, @@ -150,6 +151,11 @@ import { logger } from "../middleware/logger.js"; import { conflict, forbidden, notFound, unprocessable } from "../errors.js"; import { getTelemetryClient } from "../telemetry.js"; import { withTelemetryCompany } from "../telemetry-company-scope.js"; +import { + appendBoardEvent, + publishCommittedBoardEvent, +} from "./headless-common.js"; +import type { BoardEventView } from "@paperclipai/shared"; import { emitPlanApprovedAfterCommit } from "./product-telemetry.js"; import { authorizationService } from "./authorization.js"; import { isCloudManagedInstance } from "./cloud-instance.js"; @@ -167,6 +173,7 @@ import { } from "./issue-review-policy.js"; import { issueService, + listIssueDependencyReadinessMap, executeIssuePostCommitActions, type IssuePostCommitAction, ensureAssignmentIssueAccessGrant, @@ -555,6 +562,8 @@ function assertInteractionResolutionAllowed( type IssueResolutionContext = { id: string; companyId: string; + identifier?: string | null; + channelId?: string | null; status: string; executionRunId: string | null; hiddenAt?: Date | null; @@ -2688,6 +2697,171 @@ export function issueThreadInteractionService( } } + function toInteractionBoardEventActor(actor: InteractionActor) { + return actor.agentId + ? { + principalType: "agent" as const, + userId: null, + agentId: actor.agentId, + agentName: null, + actorProfile: null, + } + : { + principalType: "user" as const, + userId: actor.userId ?? null, + agentId: null, + agentName: null, + actorProfile: null, + }; + } + + async function resolveChannelPathForIssue( + tx: Db, + channelId: string | null | undefined, + ): Promise { + if (!channelId) return null; + const [ch] = await tx + .select({ path: channels.path }) + .from(channels) + .where(eq(channels.id, channelId)) + .limit(1); + return ch?.path ?? null; + } + + const hasRelationalBoardEventStore = Boolean( + (db as unknown as { $client?: unknown; _?: unknown })?.$client || + (db as unknown as { _?: unknown })?._, + ); + + async function appendInteractionResolvedBoardEvent( + tx: Db, + args: { + issue: { + id: string; + companyId: string; + channelId?: string | null; + identifier?: string | null; + }; + interaction: Pick; + decision: "approve" | "reject"; + actor: InteractionActor; + note?: string | null; + }, + ): Promise { + if (!hasRelationalBoardEventStore) return null; + const channelPath = await resolveChannelPathForIssue(tx, args.issue.channelId); + const trimmedNote = args.note?.trim(); + return appendBoardEvent(tx, { + companyId: args.issue.companyId, + type: "interaction.resolved", + channelId: args.issue.channelId ?? null, + channelPath, + issueId: args.issue.id, + identifier: args.issue.identifier ?? args.issue.id, + actor: toInteractionBoardEventActor(args.actor), + payload: { + interactionId: args.interaction.id, + kind: args.interaction.kind, + status: args.interaction.status, + decision: args.decision, + ...(trimmedNote ? { note: trimmedNote } : {}), + }, + }); + } + + async function requeuePoolTaskOnResolve( + tx: Db, + args: { + issueId: string; + companyId: string; + interaction: Pick; + actor: InteractionActor; + publications: ActivityPublication[]; + boardEventsOut: BoardEventView[]; + }, + ): Promise { + if (args.interaction.continuationPolicy !== "requeue_on_resolve") return; + const [freshIssue] = await tx + .select({ + id: issues.id, + companyId: issues.companyId, + status: issues.status, + channelId: issues.channelId, + identifier: issues.identifier, + kvLabels: issues.kvLabels, + }) + .from(issues) + .where(and(eq(issues.id, args.issueId), eq(issues.companyId, args.companyId))) + .limit(1); + if (!freshIssue || freshIssue.status !== "blocked") return; + + const [otherPending] = await tx + .select({ id: issueThreadInteractions.id }) + .from(issueThreadInteractions) + .where( + and( + eq(issueThreadInteractions.companyId, args.companyId), + eq(issueThreadInteractions.issueId, args.issueId), + eq(issueThreadInteractions.status, "pending"), + ), + ) + .limit(1); + if (otherPending) return; + + const readiness = ( + await listIssueDependencyReadinessMap( + tx as unknown as Db, + args.companyId, + [args.issueId], + false, + ) + ).get(args.issueId); + if (readiness && !readiness.isDependencyReady) return; + + await issueService(db).update( + args.issueId, + { + status: "todo", + actorAgentId: args.actor.agentId ?? null, + actorUserId: args.actor.userId ?? null, + }, + tx, + args.publications, + ); + + const channelPath = await resolveChannelPathForIssue(tx, freshIssue.channelId); + const eventActor = toInteractionBoardEventActor(args.actor); + const identifier = freshIssue.identifier ?? freshIssue.id; + const payload = { + interactionId: args.interaction.id, + kvLabels: freshIssue.kvLabels ?? {}, + }; + args.boardEventsOut.push( + await appendBoardEvent(tx, { + companyId: args.companyId, + type: "task.unblocked", + channelId: freshIssue.channelId, + channelPath, + issueId: freshIssue.id, + identifier, + actor: eventActor, + payload, + }), + ); + args.boardEventsOut.push( + await appendBoardEvent(tx, { + companyId: args.companyId, + type: "task.ready", + channelId: freshIssue.channelId, + channelPath, + issueId: freshIssue.id, + identifier, + actor: eventActor, + payload, + }), + ); + } + async function acceptRequestConfirmation(args: { issue: { id: string; companyId: string }; current: IssueThreadInteractionRow; @@ -2712,6 +2886,7 @@ export function issueThreadInteractionService( const now = new Date(); const postCommitActivityPublications: ActivityPublication[] = []; + const postCommitBoardEvents: BoardEventView[] = []; const result = await db.transaction(async (tx) => { await assertInteractionRunWriteAllowed(tx as unknown as Db, args.issue, args.actor, [JSON.stringify(args.input)]); await notifyChatConfirmationResolution(tx, args.current); @@ -2727,6 +2902,8 @@ export function issueThreadInteractionService( .select({ id: issues.id, companyId: issues.companyId, + identifier: issues.identifier, + channelId: issues.channelId, status: issues.status, executionRunId: issues.executionRunId, hiddenAt: issues.hiddenAt, @@ -2835,6 +3012,18 @@ export function issueThreadInteractionService( tx, acceptedInteraction, ); + const acceptedBoardEvent = await appendInteractionResolvedBoardEvent( + tx as unknown as Db, + { + issue: issueContext, + interaction: updated, + decision: "approve", + actor: args.actor, + }, + ); + if (acceptedBoardEvent) { + postCommitBoardEvents.push(acceptedBoardEvent); + } let continuationIssue: IssueWakeTarget | null = null; const acceptedPlanTarget = readAcceptedPlanConfirmationTarget( @@ -2952,6 +3141,22 @@ export function issueThreadInteractionService( workMode: executionIssue.workMode, }; } + } else if ( + lockedCurrent.continuationPolicy === "requeue_on_resolve" && + issueContext.status === "blocked" + ) { + const eventsBeforeRequeue = postCommitBoardEvents.length; + await requeuePoolTaskOnResolve(tx as unknown as Db, { + issueId: args.issue.id, + companyId: args.issue.companyId, + interaction: lockedCurrent, + actor: args.actor, + publications: postCommitActivityPublications, + boardEventsOut: postCommitBoardEvents, + }); + if (postCommitBoardEvents.length === eventsBeforeRequeue) { + await touchIssue(tx, args.issue.id, args.issue.companyId); + } } else { await touchIssue(tx, args.issue.id, args.issue.companyId); } @@ -2995,6 +3200,7 @@ export function issueThreadInteractionService( }); const publish = async (committedDb: Db) => { for (const publication of postCommitActivityPublications) publishActivity(publication); + for (const event of postCommitBoardEvents) publishCommittedBoardEvent(event); await emitInteractionResolvedTelemetry(committedDb, result.interaction); }; if (args.mutationOptions?.deferConfirmationCommitEffects) args.mutationOptions.deferConfirmationCommitEffects(publish); @@ -3031,6 +3237,8 @@ export function issueThreadInteractionService( } const now = new Date(); + const rejectPostCommitActivityPublications: ActivityPublication[] = []; + const rejectPostCommitBoardEvents: BoardEventView[] = []; const updated = await db.transaction(async (tx) => { await assertInteractionRunWriteAllowed(tx as unknown as Db, args.issue, args.actor, [JSON.stringify(args.input)]); await notifyChatConfirmationResolution(tx, args.current); @@ -3041,6 +3249,8 @@ export function issueThreadInteractionService( .select({ id: issues.id, companyId: issues.companyId, + identifier: issues.identifier, + channelId: issues.channelId, status: issues.status, executionRunId: issues.executionRunId, workMode: issues.workMode, @@ -3144,6 +3354,19 @@ export function issueThreadInteractionService( tx, rejectedInteraction, ); + const rejectedBoardEvent = await appendInteractionResolvedBoardEvent( + tx as unknown as Db, + { + issue: issueContext, + interaction: resolved, + decision: "reject", + actor: args.actor, + note: reason || null, + }, + ); + if (rejectedBoardEvent) { + rejectPostCommitBoardEvents.push(rejectedBoardEvent); + } const rejectedPlanNeedsRevision = lockedCurrent.kind === "request_confirmation" && readAcceptedPlanConfirmationTarget( @@ -3178,7 +3401,24 @@ export function issueThreadInteractionService( actorUserId: args.actor.userId ?? null, }, tx, + rejectPostCommitActivityPublications, ); + } else if ( + lockedCurrent.continuationPolicy === "requeue_on_resolve" && + issueContext.status === "blocked" + ) { + const eventsBeforeRequeue = rejectPostCommitBoardEvents.length; + await requeuePoolTaskOnResolve(tx as unknown as Db, { + issueId: args.issue.id, + companyId: args.issue.companyId, + interaction: lockedCurrent, + actor: args.actor, + publications: rejectPostCommitActivityPublications, + boardEventsOut: rejectPostCommitBoardEvents, + }); + if (rejectPostCommitBoardEvents.length === eventsBeforeRequeue) { + await touchIssue(tx, args.issue.id, args.issue.companyId); + } } else { await touchIssue(tx, args.issue.id, args.issue.companyId); } @@ -3190,7 +3430,11 @@ export function issueThreadInteractionService( }); const rejected = hydrateInteraction(updated); - const publish = (committedDb: Db) => emitInteractionResolvedTelemetry(committedDb, rejected); + const publish = async (committedDb: Db) => { + for (const publication of rejectPostCommitActivityPublications) publishActivity(publication); + for (const event of rejectPostCommitBoardEvents) publishCommittedBoardEvent(event); + await emitInteractionResolvedTelemetry(committedDb, rejected); + }; if (args.mutationOptions?.deferConfirmationCommitEffects) args.mutationOptions.deferConfirmationCommitEffects(publish); else await publish(db); return rejected; @@ -6821,10 +7065,17 @@ export function issueThreadInteractionService( } } + const postCommitActivityPublications: ActivityPublication[] = []; + const postCommitBoardEvents: BoardEventView[] = []; + let shouldTouchIssueAfterCommit = false; const updated = await db.transaction(async (tx) => { // Serialize against task completion/cancellation and use the persisted // status, including when the caller read the task before it closed. - const [issueRow] = await tx.select({ status: issues.status }).from(issues) + const [issueRow] = await tx.select({ + status: issues.status, + identifier: issues.identifier, + channelId: issues.channelId, + }).from(issues) .where(and(eq(issues.id, issue.id), eq(issues.companyId, issue.companyId))).for("update"); if (!issueRow) throw interactionNotFoundError(); let historicalAnswer = false; @@ -6875,6 +7126,37 @@ export function issueThreadInteractionService( await tx .insert(issueQuestionResponseDeliveries) .values(questionResponseDeliveryValues(answered)); + const answeredBoardEvent = await appendInteractionResolvedBoardEvent( + tx as unknown as Db, + { + issue: { + id: issue.id, + companyId: issue.companyId, + channelId: issueRow.channelId, + identifier: issueRow.identifier, + }, + interaction: row, + decision: "approve", + actor, + note: input.summaryMarkdown ?? null, + }, + ); + if (answeredBoardEvent) { + postCommitBoardEvents.push(answeredBoardEvent); + } + const eventsBeforeRequeue = postCommitBoardEvents.length; + await requeuePoolTaskOnResolve(tx as unknown as Db, { + issueId: issue.id, + companyId: issue.companyId, + interaction: current, + actor, + publications: postCommitActivityPublications, + boardEventsOut: postCommitBoardEvents, + }); + shouldTouchIssueAfterCommit = + postCommitBoardEvents.length === eventsBeforeRequeue; + } else { + shouldTouchIssueAfterCommit = true; } // Provider callbacks use this hook to atomically claim and complete // the action that resolved the interaction. Settle all remaining @@ -6889,7 +7171,15 @@ export function issueThreadInteractionService( return row; }); - await touchIssue(db, issue.id, issue.companyId); + for (const publication of postCommitActivityPublications) { + publishActivity(publication); + } + for (const event of postCommitBoardEvents) { + publishCommittedBoardEvent(event); + } + if (shouldTouchIssueAfterCommit) { + await touchIssue(db, issue.id, issue.companyId); + } const answered = hydrateInteraction(updated); await emitInteractionResolvedTelemetry(db, answered); return answered; diff --git a/server/src/services/issue-visibility.ts b/server/src/services/issue-visibility.ts index d9461db4fcd..1e34e4fe4e6 100644 --- a/server/src/services/issue-visibility.ts +++ b/server/src/services/issue-visibility.ts @@ -3,6 +3,7 @@ import { and, eq, inArray, isNull, isNotNull, ne, or, type SQL } from "drizzle-o import { issues } from "@paperclipai/db"; import { ISSUE_SCOPES, type IssueScope } from "@paperclipai/shared"; import { unprocessable } from "../errors.js"; +import { pendingUserRequestCondition } from "./issue-participation.js"; export function visibleIssueCondition(): SQL { return and(isNull(issues.hiddenAt), isNull(issues.harnessKind))!; @@ -17,6 +18,29 @@ export function nonChatAndChannelIssueCondition(): SQL { return and(ne(issues.scope, "chat"), ne(issues.scope, "channel"), isNull(issues.conversationAgentId))!; } +/** + * Exclude standing 1:1 chats and passive channel streams while keeping + * channel issues that are explicitly assigned to `mineUserId` or have a + * pending interaction addressed to `mineUserId`. + */ +export function nonChatAndPassiveChannelCondition( + companyId?: string, + mineUserId?: string, +): SQL { + if (companyId && mineUserId) { + return and( + ne(issues.scope, "chat"), + isNull(issues.conversationAgentId), + or( + ne(issues.scope, "channel"), + eq(issues.assigneeUserId, mineUserId), + pendingUserRequestCondition(companyId, mineUserId), + )!, + )!; + } + return nonChatAndChannelIssueCondition(); +} + /** Parse and validate comma-separated or repeated issue scope filters. */ export function parseScopeFilter( input: IssueScope | string | readonly string[] | undefined, @@ -45,9 +69,13 @@ export function parseScopeFilter( /** Resolve the surface scope SQL condition for issue list, count, and inbox queries. */ export function surfaceScopeCondition(filters?: { + companyId?: string; scope?: IssueScope | string | readonly IssueScope[]; q?: string; issueIds?: string[]; + assigneeUserId?: string; + touchedByUserId?: string; + unreadForUserId?: string; }): { scopes: IssueScope[]; condition: SQL | undefined } { const scopes = parseScopeFilter(filters?.scope); if (scopes.length > 0) { @@ -57,7 +85,15 @@ export function surfaceScopeCondition(filters?: { }; } if (!filters?.q?.trim() && !filters?.issueIds) { - return { scopes, condition: nonChatAndChannelIssueCondition() }; + const mineUserId = + filters?.assigneeUserId?.trim() || + filters?.touchedByUserId?.trim() || + filters?.unreadForUserId?.trim() || + undefined; + return { + scopes, + condition: nonChatAndPassiveChannelCondition(filters?.companyId, mineUserId), + }; } return { scopes, condition: undefined }; } diff --git a/server/src/services/issues.ts b/server/src/services/issues.ts index 8b9aad4f84d..92a6912ea27 100644 --- a/server/src/services/issues.ts +++ b/server/src/services/issues.ts @@ -270,6 +270,7 @@ import { } from "./recovery/issue-graph-liveness.js"; import { nonChatAndChannelIssueCondition, + nonChatAndPassiveChannelCondition, parseScopeFilter, surfaceScopeCondition, visibleIssueCondition, @@ -2781,7 +2782,7 @@ export async function runWorkspaceIsFinalized( return heartbeatRunIsTerminalOrMissing(dbOrTx, runId); } -async function listIssueDependencyReadinessMap( +export async function listIssueDependencyReadinessMap( dbOrTx: Pick, companyId: string, issueIds: string[], @@ -3435,6 +3436,7 @@ async function withIssueLabels( const issueLabels = labelsByIssueId.get(row.id) ?? []; return { ...row, + ...("claimTokenHash" in row ? { claimTokenHash: null } : {}), labels: issueLabels, labelIds: issueLabels.map((label) => label.id), watchdog: watchdogByIssueId.get(row.id) ?? null, @@ -5319,6 +5321,7 @@ const issueListSelect = { id: issues.id, companyId: issues.companyId, projectId: issues.projectId, + channelId: issues.channelId, projectWorkspaceId: issues.projectWorkspaceId, goalId: issues.goalId, parentId: issues.parentId, @@ -5362,7 +5365,19 @@ const issueListSelect = { executionLockedAt: issues.executionLockedAt, createdByAgentId: issues.createdByAgentId, createdByUserId: issues.createdByUserId, + createdByProfile: issues.createdByProfile, responsibleUserId: issues.responsibleUserId, + kvLabels: issues.kvLabels, + schemaBlocks: issues.schemaBlocks, + resultSchemaRef: issues.resultSchemaRef, + claimEpoch: issues.claimEpoch, + claimTokenHash: sql`null`, + claimHolderAgentId: issues.claimHolderAgentId, + claimHolderUserId: issues.claimHolderUserId, + claimHolderProfile: issues.claimHolderProfile, + claimLeasedAt: issues.claimLeasedAt, + claimLeaseExpiresAt: issues.claimLeaseExpiresAt, + claimAttemptCount: issues.claimAttemptCount, issueNumber: issues.issueNumber, identifier: issues.identifier, originKind: issues.originKind, @@ -7242,7 +7257,7 @@ export function issueService(db: Db) { async function getIssueByUuid(id: string) { const row = await retryIdempotentDatabaseOperation(() => db - .select({ ...getTableColumns(issues), displayStatus: issueDisplayStatusSql(), externalConversationState: externalConversationStateSql() }) + .select({ ...getTableColumns(issues), claimTokenHash: sql`null`, displayStatus: issueDisplayStatusSql(), externalConversationState: externalConversationStateSql() }) .from(issues) .where(eq(issues.id, id)) .then((rows) => rows[0] ?? null)); @@ -7253,7 +7268,7 @@ export function issueService(db: Db) { async function getIssueByIdentifier(identifier: string) { const row = await retryIdempotentDatabaseOperation(() => db - .select({ ...getTableColumns(issues), displayStatus: issueDisplayStatusSql(), externalConversationState: externalConversationStateSql() }) + .select({ ...getTableColumns(issues), claimTokenHash: sql`null`, displayStatus: issueDisplayStatusSql(), externalConversationState: externalConversationStateSql() }) .from(issues) .where(eq(issues.identifier, identifier.toUpperCase())) .then((rows) => rows[0] ?? null)); @@ -8581,7 +8596,7 @@ export function issueService(db: Db) { .from(participated).innerJoin(issues, eq(issues.id, sql`"mine_participants"."id"`)).where(and( eq(issues.companyId, companyId), visibleIssueCondition(), - nonChatAndChannelIssueCondition(), + nonChatAndPassiveChannelCondition(companyId, userId), nonPluginOperationIssueCondition(), ne(issues.status, "cancelled"), inboxVisibleForUserCondition(companyId, userId), @@ -8639,7 +8654,7 @@ export function issueService(db: Db) { ? sql`NOT (${inboxVisibleForUserCondition(companyId, inboxArchive.userId)})` : undefined; if (inboxArchive?.mode === "archived" && archivedCondition) conditions.push(archivedCondition); - const { scopes, condition: scopeCondition } = surfaceScopeCondition(filters); + const { scopes, condition: scopeCondition } = surfaceScopeCondition({ ...filters, companyId }); if (scopeCondition) conditions.push(scopeCondition); // Explicit child navigation includes waiting chat tasks, just like // readable-child counts. Ambient lists still omit idle conversations. @@ -9047,7 +9062,7 @@ export function issueService(db: Db) { if (filters?.readCondition) conditions.push(filters.readCondition); const creationCondition = creationVisibilityCondition(companyId, filters); if (creationCondition) conditions.push(creationCondition); - const { scopes, condition: scopeCondition } = surfaceScopeCondition(filters); + 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) { conditions.push(nonIdleSlackIssueCondition()); diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts index 15931ae819e..886bd22baf5 100644 --- a/server/src/services/recovery/service.ts +++ b/server/src/services/recovery/service.ts @@ -1,4 +1,5 @@ import { wakeWaitersOfStalledIssues, type BlockerStallWakeup } from "./blocker-stall-wakeups.js"; +import { wakeReadyPoolDependentsForBlocker } from "../headless-task-queue.js"; import { ANTIGRAVITY_SWARM_UNAVAILABLE } from "../antigravity-swarm-refusal.js"; import { DEPENDENCY_WAKE_REPEATED_FAILURE_STREAK, readDependencyWakeCircuit } from "./dependency-wake-circuit-breaker.js"; import { INTERACTION_DELIVERY_DENIED, isInteractionDeliveryDeniedRun } from "../agent-interaction-delivery.js"; @@ -6573,6 +6574,16 @@ export function recoveryService( result.enqueueFailed += stalls.failed; if (stalls.retryAt !== null) opts?.onDeferredDeadline?.(stalls.retryAt); } + if (opts?.blockerIssueId) { + try { + await wakeReadyPoolDependentsForBlocker(db, opts.blockerIssueId); + } catch (err) { + logger.warn( + { err, blockerIssueId: opts.blockerIssueId, source }, + "failed to wake unassigned pool dependents after blocker finality", + ); + } + } return result; } diff --git a/server/src/types/express.d.ts b/server/src/types/express.d.ts index d3ae48c4c6f..65aae43306c 100644 --- a/server/src/types/express.d.ts +++ b/server/src/types/express.d.ts @@ -1,6 +1,6 @@ export {}; -import type { AgentApiKeyScope } from "@paperclipai/shared"; +import type { AgentApiKeyScope, ClientScopes } from "@paperclipai/shared"; declare global { namespace Express { @@ -25,9 +25,13 @@ declare global { status?: string; }>; isInstanceAdmin?: boolean; + ignoreInstanceAdmin?: boolean; canManageExperimentalSettings?: boolean; keyId?: string; keyScope?: AgentApiKeyScope; + keyCompanyId?: string | null; + keyLockedProfile?: string | null; + keyScopes?: ClientScopes | null; runId?: string; onBehalfOfUserId?: string | null; authorizingUserId?: string; diff --git a/skills/paperclip-lite/SKILL.md b/skills/paperclip-lite/SKILL.md new file mode 100644 index 00000000000..da8a89fa351 --- /dev/null +++ b/skills/paperclip-lite/SKILL.md @@ -0,0 +1,94 @@ +--- +name: paperclip-lite +description: > + Coordinate on Paperclip channels, queues, and tasks using the `pc` CLI without + raw curl boilerplate. Use for external coding agents (Claude Code, Codex, + OpenCode, Gemini) reading threads, posting updates, claiming pooled tasks, + renewing/completing fenced leases, and waiting on events. +--- + +# Paperclip Lite (`pc`) + +Use the `pc` CLI (alias for `npx paperclipai`) for all Paperclip coordination — never hand-roll `curl` requests, and never run `pnpm paperclipai` (use `pc` or `npx paperclipai` with static args or `--file -` stdin piping for untrusted Markdown/JSON). + +## 1. Check Context & Discover Channels + +```sh +pc whoami --json +pc channels --json +pc read --json +``` + +- Pass `--as ` (or rely on `PAPERCLIP_PROFILE`) if acting under a dedicated profile/agent key. +- Trailing `/` in a channel path (e.g. `build/`) reads the channel and all nested subchannels. +- Inside `pc tasks run`, `PAPERCLIP_TASK_ID`, `PAPERCLIP_CLAIM_TOKEN`, `PAPERCLIP_CLAIM_EPOCH`, `PAPERCLIP_API_URL`, `PAPERCLIP_COMPANY_ID`, and `PAPERCLIP_PROFILE` are pre-injected. + +## 2. Post Updates & Reply Safely + +```sh +# Passive channel note (status=backlog, unassigned) +pc post "Summary of update" --label + +# Reply to an existing thread or task +pc reply "Progress or findings" +pc reply --after --file - +``` + +- Use `--after ` when replying to a contested thread so a `409 stale_reply_cursor` stops you from answering over newer instructions. +- Use `--schema ''` when posting structured findings; read structured blocks from `blocks` in `pc read --json`. + +## 3. Lock-Free State Transitions (`label --if`) + +Use Compare-And-Swap (`CAS`) labels instead of read-then-write races: + +```sh +pc label triage_state=investigating owner=worker-1 --if triage_state=new --if-unset owner +``` + +On `409 label_conflict`, skip the item and move on. Never write keys prefixed with `paperclip.` (reserved for server metadata). + +## 4. Claim & Settle Pooled Tasks + +```sh +# Pop oldest unblocked todo task (5m fenced lease) +pc tasks claim --ready --label role=worker --lease 5m --wait 5m + +# Extend lease while working (required if not wrapped by `pc tasks run`) +pc tasks renew --lease 5m + +# Release back to todo if you must stop early +pc tasks release --comment "Handing back to pool" + +# Complete (add --data '' if task has a resultSchema) +pc tasks complete "Implemented and verified" --pr + +# Fail permanently (blocked) or retryable (--requeue) +pc tasks fail "Missing required fixture" +pc tasks fail "Transient network failure" --requeue +``` + +- Never ignore `409 claim_lost` — stop work on `` immediately if another worker or admin took over. +- Use `pc tasks run --ready -- ` when wrapping a subprocess so lease renewal, `SIGINT` release, and exit settlement happen automatically. + +## 5. Human Decisions & Event Waiting + +```sh +# Ask a question or confirmation (transitions to blocked and releases pool lease) +pc ask "Which option should we ship?" --choices "a,b,c" --human-only +pc confirm "Drop legacy table?" --human-only + +# Block cleanly for a reply, interaction resolution, or downstream task completion (no sleep loops!) +pc wait --event comment.posted,interaction.resolved,task.completed --after --timeout 15m --json +``` + +## 6. Error Recovery & Rules of Thumb + +- **`403 agent_key_required` (strict Cloud mode):** Ask the operator to run `pc agent connect --role ` or run `pc agent login --name --api-base `. +- **`409 profile_matches_registered_agent`:** Never impersonate a registered `@agent`; authenticate with its key or use a distinct `--as ` name. +- **`409 claim_lost` / `409 label_conflict` / `409 stale_reply_cursor`:** Do not retry blindly — stop work on a lost claim, skip a conflicted CAS item, or re-read before replying. +- **`422 missing_or_invalid_result_schema`:** Inspect the schema with `pc schemas inspect --json` and pass valid JSON to `pc tasks complete --data ''`. + +1. Read `` (`pc read --json`) before acting so you see prior comments, `resultSchema`, and `cursor`. +2. Prefer `--file -` over inline quotes for large or untrusted payloads. +3. Never poll in a `sleep` loop — use `pc wait`, `pc tail`, or `pc tasks claim --ready --wait`. +4. Always pass `--after ` to `pc wait` so updates that landed right after your read return immediately without race windows. diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index fd734d05485..e0e3d9d5de1 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -33,7 +33,7 @@ "packages/plugins/sdk/src/workspace-operation-error.ts": "2cd247d002d83b163239229e631bca4e519e5075", "packages/plugins/sdk/src/workspace-provider.ts": "38e945b807f22150710c11b136af0a28aab2cb7c", "packages/plugins/sdk/tsconfig.json": "d62ebdff94bc4b75dabf1fcad187e1e7a90fc794", - "packages/shared/package.json": "6417ef8baef0cb9b836b14f453dc8bc5025709e0", + "packages/shared/package.json": "0d417d9a3db4fd099b1fe2e0c0a3fa52eee243cf", "packages/shared/src/__snapshots__/slack-app-manifest.test.ts.snap": "79020ba3aa6662923f70aa44e2c483844e9901d9", "packages/shared/src/account-handle.test.ts": "fb77e08a68b8deb3ab5ebf271724a268ac6bae56", "packages/shared/src/account-handle.ts": "4bc5d6ec16b854497e83ce781bd900dfec599cbd", @@ -274,12 +274,22 @@ "packages/shared/src/google-workspace-connectors.ts": "3338962075622b929f0fae18d8ca0333f88cf23a", "packages/shared/src/google-workspace-setup-links.test.ts": "d86428b26e74e54ab2902d1a14c0f06f562de775", "packages/shared/src/grok-bot.ts": "9de68f00e7926c397729ff62bf8e277f5a41c525", + "packages/shared/src/headless/channels.ts": "9db0d9cd0fe8b43478ab4585c5df47b310c5caa7", + "packages/shared/src/headless/events.ts": "71ece3f5df8fc14ad685fdf86f7ed7db748586c2", + "packages/shared/src/headless/headless.test.ts": "616c41aff5d45b5cff8b216441c630adfc6fe740", + "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/plans.ts": "9755160a884569aff9cfaaac8330486e392951ee", + "packages/shared/src/headless/pure.ts": "962757460d6e60494bbb75d2f476fb2be1e530dc", + "packages/shared/src/headless/schemas.ts": "eb0716395a15111699d18ec209a2fda4990b9e4d", "packages/shared/src/heartbeat-inbox.ts": "227dc89705c20460ca02194091cb162e11503186", "packages/shared/src/home-paths.test.ts": "81235c17c376224e1be3abd3f034a8400f079c66", "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": "159182d500385c0d13c20ff71627e20ba5c0d47f", + "packages/shared/src/index.ts": "dbdd64c5df8ba7011e2a14fa17a77f8c330ecd43", "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", @@ -368,6 +378,14 @@ "packages/shared/src/runtime-exposure/loopback-bind.ts": "696dcbc1fc8f7e64f37314bc574360cf06bbae95", "packages/shared/src/runtime-exposure/ports.test.ts": "de27b2c17db88c65f9f4e7240d9fae969dd1551e", "packages/shared/src/runtime-exposure/ports.ts": "6566d780a36c4eb37fab5584db19714f596654b7", + "packages/shared/src/sdk/client.ts": "497691448c2548afb87e4fe52767d1a970369a07", + "packages/shared/src/sdk/env.ts": "f651aca6f5fcca466deba63cc00257e534ad4d18", + "packages/shared/src/sdk/index.ts": "dedd01673f6a34d0291db0e5352c6b57b41a3222", + "packages/shared/src/sdk/lite.ts": "d4bbb9c4a953ab7239388e1e7f3120e110bb9778", + "packages/shared/src/sdk/memory-backend.ts": "35d8403191d3b7d534368dffb3e4159b32499df2", + "packages/shared/src/sdk/sdk.test.ts": "4421224d6125b6cad0e47e912de7a8bfa1af78aa", + "packages/shared/src/sdk/sse.ts": "cb1284b6acd556f0b8ffb4ce5c6f3b4456415e08", + "packages/shared/src/sdk/types.ts": "d7212ea5913b447e1c2a789c075edf86c062a20b", "packages/shared/src/self-serve-mcp-research.json": "98a90544e8e00b31350b5c07e39940429bc026b9", "packages/shared/src/self-serve-mcp-research.ts": "312abfecb0dbac8a0e5bf80fb8e3467ca94f500f", "packages/shared/src/setting-defaults.test.ts": "f5554686f7bf9cc34f14cdd4505257dcc562d410",