mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 09:39:53 +01:00
## Thinking Path > - Paperclip manages work for AI agents. > - SSH environments run tasks on computers that users own. > - A Paperclip server needs network access before it can reach a private computer. > - A reusable Tailscale connection belongs in Connectors. > - Connected machines should become choices in the existing SSH environment form. > - This change connects a tailnet and resolves selected machines through a private network client. > - Agents retain their choice of harness and AI account. ## Linked Issues or Issue Description **Subsystem affected** Connectors, environment settings, SSH execution, company secret storage, and runtime packaging. **Problem or motivation** Entering a Tailscale address in the SSH form does not connect the Paperclip server to that tailnet. Requiring a separate device key for every environment also duplicates network setup. **Proposed solution** Add a Tailscale Connector with **Connect Tailscale Network**. Use brokered OAuth consent to enroll one private network client per connection. Let SSH environments select a connected network and stable machine identity. Preserve the enrolled node state through the company vault so a restart does not reuse the one-time token. **Alternatives considered** A separate Tailscale environment type would duplicate SSH behavior and mix network access with harness selection. This change uses the existing `ssh` driver. Related #15648 adds OAuth client credentials and a health check; this change uses user consent and supplies outbound task execution. Related #11743 concerns HTTPS brokering. **Roadmap alignment** This extends the existing Connected Apps, environment, and Personal & Shared AI Accounts capabilities. This PR is stacked on #21248, which provides SSH account selection independently of Tailscale. The hosted OAuth broker is a companion control-plane change. ## What Changed - Preserve Cloud reauthentication in the current browser tab. Explain canceled or failed consent in the connector and offer a retry of the same authorized saved connection. - Record Cloud enrollment starts initiated through the Tailscale connector in the company activity log. - Check install-preparation descendant liveness through the kernel process table in the Runner support test. Keep the direct child’s strict reaping assertion and reject any non-zombie descendant. - Align the application image stage contract with the Tailscale client stage after the upstream Runner-image refactor. Keep the exact stage list and check every application stage, including `tailscale-client`, for prohibited Runner compiler commands. - Group Tailscale consent, discovery, daemon lifecycle, pairing, and deletion under `server/src/services/connectors/tailscale/`, with their service tests. Update existing route, runtime, environment, vault, and company-deletion imports. Keep the existing contracts, authorization, audit, and transaction owners. - Handle early stdin closure in the Kubernetes real-shell test helper. Stop the input stream on `EPIPE`, preserve nonzero child exits, and reject a zero exit when input was lost. Add two real-process regression cases. Production transfer code and confinement checks are unchanged. - Read configured Tailscale executable paths when a client starts, after supported `.env` loading. Keep explicit command overrides available. - Discard pending pairing results after switching to Direct SSH or closing the form. Retain the existing company, connection, machine, and port checks. - Store network credentials with an immutable server-owned purpose from their first vault row. Exclude them from generic catalogs, bindings, environment projection, and value reads. Use a dedicated audited server consumer for pinned connector reads. Block unclassified legacy serialized node state at the same value boundary. Keep SSH private-key binding separate from connector credentials. - Gate network queries and setup on verified local-implicit or instance-admin access. Hide Tailscale catalog rows for other members, show an admin requirement on direct setup navigation, and avoid device discovery before management access is known. - Keep failed-client cleanup in the network manager. A failed request cannot disconnect a newer retry for the same identity; explicit connector disconnect and enrollment retirement still stop their networks. - Check for readable Ed25519, ECDSA, or RSA host public keys before pairing edits `authorized_keys`. Print a known-hosts entry for every available key, or fail before changing authorized keys if none are available. - Return self-hosted Cloud enrollment to the Tailscale connector. Save the unprefixed setup path and let the shared callback add the verified company prefix. Keep external and unrelated destinations rejected. - Hide pairing instructions after an SSH port change. Ignore late key-selection results for the old port. Operators prepare again for matching known-hosts output. - Retire connector references before deleting a company or its vault credential. Stop company daemons after the database commit. Keep failed secret retirement retryable and prevent late node-state writes from restoring deleted connections. Discard retired state without blocking behind the vault deletion lock. - Reload a mismatched credential before replacing a ready daemon. Recheck the active entry and manager generation after the read. An older request cannot stop a newer healthy socket or cross shutdown. - Pin connector credentials to the exact vault version and SHA-256 digest recorded by trusted enrollment and node-state writes. Ignore generic secret rotations. Advance both fields with a compare-and-set guard. Reject unpinned or tampered credentials before network startup. - Save an explicit Direct SSH selection and clear old Tailscale fields after config merging. Preserve the operator's entered direct host. - Route all Tailscale SSH runtime access through the connection service after SSH-key loading. Pin access to the environment's saved connector identity and recheck after device discovery. Remove standalone key-based daemon startup and reject raw enrollment keys or credential-only network configurations. Align the shared config type and SDK pins. - Correct two E2E assumptions exposed during connector qualification. Keep the two-window chat fixture stale until its own mutation. Validate the original failed run and its permitted write-revocation timestamp in the legacy recovery browser test. - Add the Tailscale Connector page, catalog entry, OAuth return flow, connected-network management, device discovery, and disconnect. Document all six routes in OpenAPI and the API reference, including their instance-admin requirement. - Add company-scoped connection storage in `0480_lazy_lethal_legion`, trusted credential version/digest fields in `0481_round_pet_avengers`, and server-owned secret purpose/backfill in `0482_aberrant_rumiko_fujikawa`. Generate all three migrations through the maintained command and retain the five newest snapshots. - Add machine pairing that generates a fresh SSH key per request, stores its private half in the company vault, and uses the generated public half in the install command. Do not trust editable saved metadata. Preserve existing authorized keys, including a file without a final newline. Keep SSH username, workspace, and trusted host keys explicit. - Use the existing SSH driver. Resolve the machine's current address from its stable device ID. Reject disconnected, removed, offline, and wrong-company selections. - Hide Network when Direct is the only option. Select a sole connected tailnet automatically and hide its selector. Remove the requested setup helper copy. Do not restrict the harness to Claude. - Run a private userspace Tailscale daemon with a separate socket. Persist its node state before execution. Restore it after restart, bound startup, serialize reconnect cleanup, and close it during server shutdown. - Guard OAuth completion with a durable attempt marker. Disconnect and newer authorization invalidate older callbacks. Close replaced daemons and remove cancelled enrollment secrets without changing newer connection state. - Preserve SSH host verification and tailnet-specific session identity. Honor the configured Tailscale executable path, including spaces and OpenSSH percent escaping. - Package checksum-pinned Tailscale clients and their license in the standard runtime image. Exercise the client build stage in PR CI and include it in image smoke checks. ## Verification - Merge status: all CI and image checks pass, and current-head Apex is 5/5 with no unresolved comments. GitHub rejected a direct merge because the active master ruleset requires code-owner approval for `.github/workflows/pr-trusted.yml`. The [CODEOWNERS workflow pattern](https://github.com/paperclipai/paperclip/blob/master/.github/CODEOWNERS#L3) applies; eligible maintainers already have review requests. Auto-merge is enabled with the squash method for the verified head. The PR remains open pending that required approval; no branch policy was bypassed. - Final revision: `fdb29b2cc366f4945b7f4c3e2b2d25070329a21b`, including master `999709b0a6dd416af335b5debded13e1de7fcb7a`. [Final CI verification passed](https://github.com/paperclipai/paperclip/actions/runs/43518584814/job/132213508320). All required checks pass, all applicable test/build gates are green, and the branch is mergeable against master. SSH prerequisite #21248 and Cloud broker paperclipai/paperclip-cloud#1314 are already merged. - [Apex reviewed this exact revision at 5/5](https://github.com/paperclipai/paperclip/pull/20617#issuecomment-6776629437). There are no unresolved review threads. The PR is classified as Critical impact. - Final image qualification passes for the [application Runner path](https://github.com/paperclipai/paperclip/actions/runs/43518584522/job/132206784267), [amd64 Runner image](https://github.com/paperclipai/paperclip/actions/runs/43518584544/job/132207296198), and [arm64 Runner image](https://github.com/paperclipai/paperclip/actions/runs/43518584544/job/132207296156). Typechecks, Runner support, native/Rust tests, provider tests, serialized-server suites, browser shards, and the remaining applicable CI checks pass. This is source/image CI qualification, not a production rollout. - The last master conflict affected only Docker stage declarations and their boundary test. Both the checksum-pinned Tailscale stage and upstream `runner-lockfile` guard are retained, including the upstream `deps` inheritance. The Tailscale client stage is byte-identical. All 180 cases across five Docker/image contract suites pass locally, along with server and UI typechecks. The maintained 543-input SDK check has no drift. Runtime and lock pins are unchanged. Secret/PII and whitespace scans pass. - Seven OAuth regression cases failed before the fixes. The current-tab test uses the real handoff helper, checks that the session is stored before reauthentication navigation, mounts the shared return page, resumes consent, and verifies handoff cleanup. Callback tests check trusted saved-connection context, fixed safe outcomes, failure audit metadata, denied membership and expired-state rejection, JSON API errors, and no provider text in browser returns. UI retries require a connection in the current company's catalog. All 80 OAuth route/service/UI/shared-handoff cases pass; server and UI source/test typechecks pass. - [Server shard 4/12 on the prior refresh](https://github.com/paperclipai/paperclip/actions/runs/43510727031/job/132180301436) passed 2,784 cases and skipped 21, then failed a reassignment fixture's `TRUNCATE companies CASCADE` cleanup with PostgreSQL `40P01`. Its automatic retry found the surviving `REA` prefix. The unchanged test passes all three cases locally. A controlled reader/cleanup overlap reproduces the same deadlock, but the exact competing CI query was not logged. Each case now has a distinct company prefix and identifier; the owned database is removed at suite end. The three test bodies and assertions are byte-identical. Eight local reassignment/lock-release cases pass, and the [final server shard 4/12 passes](https://github.com/paperclipai/paperclip/actions/runs/43518584814/job/132207159392). Production reassignment logic, deadlines, and retries are unchanged. - The initial master integration passed 330 cases across 17 suites. Coverage includes connector state, device discovery, network lifecycle, pairing, routes, SSH binding and exports, environment persistence, and connector UI. All three unpublished migrations were regenerated after master's `0479_short_darkstar`: `0480_lazy_lethal_legion`, `0481_round_pet_avengers`, and `0482_aberrant_rumiko_fujikawa`. Each SQL body is byte-identical to its earlier unpublished migration. Generated snapshots preserve existing master tables and add only the intended Tailscale table and secret-purpose column. Exactly five snapshots remain, 0478–0482. Numbering, safety, compatibility, and snapshot-drift checks pass. The later Docker refresh did not alter this migration sequence. - Earlier attempts remain part of the verification record. On `1c020a0`, Rust cache restoration and server shard 5/12 were interrupted by shutdown signals, Runner shard 2/3 lost communication with no retrievable log, and an amd64 provider download failed with npm `ECONNRESET`. Same-head retries recovered, without establishing the cause of the communication loss. Later superseded runs also had cancellations with incomplete logs. These interrupted attempts are not counted as passes. The final revision has fresh successful CI. - Local platform limits remain recorded. The Kubernetes suite on macOS passed 191 cases, failed 12 Linux `/proc/self/fd` transfer cases, and skipped four Linux-only cases. Unchanged source reproduced the same 12 failures. An initial run also lacked provider dependencies until the maintained preparation command installed them. Those local attempts are not green qualification. Final Linux provider CI passes. Local Docker qualification was unavailable; final image checks passed in CI. - Before PR separation, a live tailnet/SSH Claude Code task completed on Ubuntu ARM64 without provider login for the remote user. The selected Paperclip subscription ran it, wrote the expected file, posted completion, and marked the task done. File contents and private runtime cleanup were checked. This is prior live evidence; the final revision was not live-retested. Other providers have automated coverage only. Hosted registration for unrelated tailnets and production concurrency remain qualification limits below. - The Superagent security and supply-chain reports remain neutral and inconclusive. Earlier attempts to restart the failed security scan returned HTTP 404. Supply-chain intelligence lacked coverage for extracted pinned dependencies and the shared workflow reference. These reports do not establish successful security qualification. The required CI and review gates pass; this external coverage gap remains disclosed. ## Risks - The Superagent security and supply-chain reports are inconclusive. The security scan re-run request returned HTTP 404, and the supply-chain scanner lacks coverage for the extracted dependencies and shared workflow reference. These neutral results are not successful security qualification. - The server-owned secret purpose is internal database metadata, not an HTTP-writable field. The generic secret service owns enforcement so direct API reads and runtime projection share the same restriction. Previously copied node state remains valid outside Paperclip until the enrolled device is revoked in Tailscale; a local disconnect cannot stop an external copy. - Tailscale network configurations now require a connected Connector and selected machine. The unreleased key-only path is removed; any saved configuration from that path needs Connector setup. - The connector remains a pilot. The local test used an OAuth app registered in the consenting user's tailnet. Qualify hosted app registration for unrelated customer tailnets before general availability. - This implementation supports one serving process per instance. Concurrent replicas need exclusive ownership of the persisted network identity before production rollout. Preserve the database and company vault master key across restarts. - Each machine-pairing preparation creates a new vault secret. Unused generated keys follow the existing secret deletion lifecycle. A saved SSH key remains available as an explicit choice. - Apply additive migrations `0480_lazy_lethal_legion`, `0481_round_pet_avengers`, and `0482_aberrant_rumiko_fujikawa` before application rollout. The new credential version and digest columns are nullable. Existing unpinned connections require fresh OAuth consent; the migration deliberately does not trust or backfill a generic secret value. Regenerate or renumber migrations if master advances the sequence before merge. - The target needs an SSH server, its chosen harness, and allowed tailnet access. A reachable network does not grant SSH or provider authorization. Pairing reads standard `/etc/ssh` host-public-key files; custom host-key locations require manual known-hosts configuration. - Roll back the application revision to remove new entry points. Existing connection secrets and registered Tailscale nodes retain their separate lifecycle. Do not drop the table or delete node state as part of an application rollback. - Production qualification still needs denied-policy, revocation, cancellation, and deployment-overlap checks. Local Docker and a production deployment were not performed. ## Model Used OpenAI Codex, gpt-6.1-sol, xhigh reasoning, with local code execution and tool use. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used - [x] I have checked ROADMAP.md and this extends existing connector and environment features - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have described the issue in-PR using the feature request fields - [x] I have not referenced internal issues, local URLs, or private machine identifiers - [x] My branch name describes the change - [x] I have run focused tests locally and they pass - [x] I have added tests for new behavior and failure paths - [x] I have updated documentation - [x] I have documented migration and runtime risks - [x] All Paperclip CI gates are green - [ ] Required code-owner approval received for the workflow change - [x] Greptile Apex is 5/5 on the final head with no unresolved comments - [x] I will address CI and review findings before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
1693 lines
80 KiB
TypeScript
1693 lines
80 KiB
TypeScript
import express from "express";
|
|
import fs from "node:fs";
|
|
import path from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import request from "supertest";
|
|
import { describe, expect, it } from "vitest";
|
|
import { MUSE_ASSET_VERSION, MUSE_PUBLIC_ROUTES } from "@paperclipai/shared";
|
|
import { COMPANY_IMPORT_TRANSFERS_ROUTE_PATH } from "@paperclipai/shared/company-import-transfer";
|
|
import { errorHandler } from "../middleware/index.js";
|
|
import { buildOpenApiSpec, openApiRoutes, applyPluginSettingsVisibility, buildOpenApiDocument } from "../routes/openapi.js";
|
|
import { mcpDiscoveryDocuments } from "../services/public-mcp/discovery.js";
|
|
|
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
const ROUTES_DIR = path.resolve(__dirname, "../routes");
|
|
|
|
const apiPrefixes: Record<string, string> = {
|
|
"cases.ts": "/api",
|
|
"case-handoffs.ts": "/api",
|
|
"workflows.ts": "/api",
|
|
"smoke-lab.ts": "/api",
|
|
"access.ts": "/api",
|
|
"activity.ts": "/api",
|
|
"adapters.ts": "/api",
|
|
"agents.ts": "/api",
|
|
"agent-project-access.ts": "/api",
|
|
"agent-permission-grants.ts": "/api",
|
|
"agent-interaction-permissions.ts": "/api",
|
|
"agent-commentary.ts": "/api",
|
|
"agent-chat-messages.ts": "/api",
|
|
"agent-avatars.ts": "/api",
|
|
"agent-profile-avatar.ts": "/api",
|
|
"announcements.ts": "/api",
|
|
"ai-connections.ts": "/api",
|
|
"decision-models.ts": "/api",
|
|
"agent-observability.ts": "/api",
|
|
"fast-responses.ts": "/api",
|
|
"prompt-injection-prevention.ts": "/api",
|
|
"attention.ts": "/api",
|
|
"approvals.ts": "/api",
|
|
"assets.ts": "/api",
|
|
"auth.ts": "/api/auth",
|
|
"board-chat.ts": "/api",
|
|
"browser-use.ts": "/api",
|
|
"mcp-apps.ts": "/api",
|
|
"mcp-skills.ts": "/api",
|
|
"built-in-agents.ts": "/api",
|
|
"chat-channels.ts": "/api",
|
|
"slack-tools.ts": "/api",
|
|
"email.ts": "/api",
|
|
"cloud.ts": "/api/cloud",
|
|
"customer-success.ts": "/api/customer-success/v1",
|
|
"companies.ts": "/api/companies",
|
|
"company-skills.ts": "/api",
|
|
"company-skill-policy.ts": "/api",
|
|
"connection-intents.ts": "/api",
|
|
"connection-event-wake.ts": "/",
|
|
"ephemeral-enrollment.ts": "/api",
|
|
"costs.ts": "/api",
|
|
"dashboard.ts": "/api",
|
|
"dot-runner.ts": "/api",
|
|
"muse.ts": "/api",
|
|
"muse-qualification.ts": "/api",
|
|
"grok-bot.ts": "/api",
|
|
"decision-queues.ts": "/api",
|
|
"decisions.ts": "/api",
|
|
"decision-training.ts": "/api",
|
|
"environments.ts": "/api",
|
|
"execution-workspaces.ts": "/api",
|
|
"task-workspaces.ts": "/api",
|
|
"file-resources.ts": "/api",
|
|
"folders.ts": "/api",
|
|
"goals.ts": "/api",
|
|
"health.ts": "/api/health",
|
|
"ready.ts": "/api/ready",
|
|
"liveness.ts": "/api/liveness",
|
|
"inbox-agent-policy.ts": "/api",
|
|
"inbox-dismissals.ts": "/api",
|
|
"instance-database-backups.ts": "/api",
|
|
"instance-settings.ts": "/api",
|
|
"issues.ts": "/api",
|
|
"issue-tree-control.ts": "/api",
|
|
"llms.ts": "/api",
|
|
"link-previews.ts": "/api",
|
|
"managed-agent-profiles.ts": "/api",
|
|
"onboarding-seed.ts": "/api",
|
|
"openapi.ts": "/api",
|
|
"plugin-ui-static.ts": "/api",
|
|
"plugins.ts": "/api",
|
|
"projects.ts": "/api",
|
|
"primary-agent.ts": "/api",
|
|
"public-mcp.ts": "/api",
|
|
"project-tools.ts": "/api",
|
|
"resource-memberships.ts": "/api",
|
|
"remote-agent-profiles.ts": "/api",
|
|
"routines.ts": "/api",
|
|
"secrets.ts": "/api",
|
|
"sidebar-badges.ts": "/api",
|
|
"sidebar-preferences.ts": "/api",
|
|
"summary-slots.ts": "/api",
|
|
"status-cards.ts": "/api",
|
|
"tailscale-connections.ts": "/api",
|
|
"teams-catalog.ts": "/api",
|
|
"tool-access.ts": "/api",
|
|
"voice-sessions.ts": "/api",
|
|
"tool-gateway.ts": "/api",
|
|
"user-profiles.ts": "/api",
|
|
"workspace-preferences.ts": "/api",
|
|
};
|
|
|
|
const ROUTE_LITERAL_PATTERN =
|
|
/router\.(get|head|post|put|patch|delete)\(\s*["'`]([^"'`]+)["'`]/g;
|
|
const ROUTE_ARRAY_PATTERN = /router\.(get|head|post|put|patch|delete)\(\s*\[([^\]]+)\]/g;
|
|
const ROUTER_METHOD_PATTERN = /router\.(get|head|post|put|patch|delete)\(/;
|
|
const HTTP_METHODS = new Set([
|
|
"get",
|
|
"put",
|
|
"post",
|
|
"delete",
|
|
"options",
|
|
"head",
|
|
"patch",
|
|
"trace",
|
|
]);
|
|
const explicitOpenApiCoverageExclusions = new Set<string>();
|
|
|
|
const explicitOpenApiOperationCoverageExclusions = new Set([
|
|
// Exact Cloud-control signed action; ordinary board/agent credentials cannot invoke it.
|
|
"POST /api/instance/connector-events/wake",
|
|
"POST /api/instance/ephemeral-enrollment/prepare",
|
|
// Muse uses its closed, versioned receiver protocol and dedicated credentials,
|
|
// documented in doc/muse-personal-agent.md and the shared protocol contract.
|
|
// Board connection/qualification management remains in this OpenAPI document.
|
|
...MUSE_PUBLIC_ROUTES.map(route => `${route.method} ${route.path}`),
|
|
// Inspection uses its own versioned Cloud-permit/managed-run protocol,
|
|
// documented in CUSTOMER-SUCCESS-INSPECTION.md and the shared contract.
|
|
// Ordinary board sessions and agent API keys cannot invoke these endpoints.
|
|
"GET /api/customer-success/v1/run-authority",
|
|
"POST /api/customer-success/v1/read",
|
|
// OAuth discovery and protocol endpoints have their own metadata contract;
|
|
// browser connection-management operations remain documented in the board API.
|
|
// Markdown rendering of the separately documented assistant setup page.
|
|
"GET /api/mcp/setup.md",
|
|
"GET /.well-known/oauth-protected-resource",
|
|
"GET /.well-known/oauth-protected-resource/mcp/paperclip",
|
|
"GET /.well-known/oauth-protected-resource/mcp/runner",
|
|
"GET /.well-known/oauth-authorization-server",
|
|
"POST /mcp/oauth/register",
|
|
"POST /mcp/oauth/device_authorization",
|
|
"GET /mcp/oauth/authorize",
|
|
"POST /mcp/oauth/token",
|
|
"POST /mcp/oauth/revoke",
|
|
"GET /.well-known/oauth-authorization-server/mcp/runner/oauth",
|
|
"POST /mcp/runner/oauth/register",
|
|
"POST /mcp/runner/oauth/device_authorization",
|
|
"GET /mcp/runner/oauth/authorize",
|
|
"POST /mcp/runner/oauth/token",
|
|
"POST /mcp/runner/oauth/revoke",
|
|
// This endpoint is authenticated by the provider signature rather than by a
|
|
// Paperclip board/agent credential. It intentionally stays out of the public
|
|
// board API document, while this exact exclusion keeps route coverage honest.
|
|
"POST /api/chat-webhooks/agentmail/{publicId}",
|
|
"POST /api/chat-webhooks/{publicId}/{provider}",
|
|
"POST /api/voice-webhooks/{publicId}/events",
|
|
"POST /api/voice-webhooks/{publicId}/tools",
|
|
]);
|
|
|
|
// The set of contract-first routes whose OpenAPI document leads the mounted
|
|
// request handler. The company-and-environment Claude setup-token login routes
|
|
// now have request handlers, so the set is empty. A new contract-first route
|
|
// belongs here only until its handler lands.
|
|
const specOnlyContractFirstRoutes = new Set<string>([]);
|
|
|
|
function createApp() {
|
|
const app = express();
|
|
app.use("/api", openApiRoutes());
|
|
app.use(errorHandler);
|
|
return app;
|
|
}
|
|
|
|
// Route files may compose paths from shared path constants inside template
|
|
// literals; substitute the constants' values before normalizing.
|
|
const routePathConstantSubstitutions: Record<string, string> = {
|
|
"${COMPANY_IMPORT_TRANSFERS_ROUTE_PATH}": COMPANY_IMPORT_TRANSFERS_ROUTE_PATH,
|
|
};
|
|
|
|
function normalizeExpressPath(routePath: string) {
|
|
let substituted = routePath;
|
|
for (const [placeholder, value] of Object.entries(
|
|
routePathConstantSubstitutions,
|
|
)) {
|
|
substituted = substituted.split(placeholder).join(value);
|
|
}
|
|
return substituted
|
|
.replace(/\*([A-Za-z0-9_]+)/g, "{$1}")
|
|
.replace(/:([A-Za-z0-9_]+)/g, "{$1}")
|
|
.replace(/\/+/g, "/");
|
|
}
|
|
|
|
function resolveMountedPath(file: string, prefix: string, routePath: string) {
|
|
if (file === "connection-event-wake.ts") return routePath;
|
|
if (file === "public-mcp.ts" && (routePath.startsWith("/mcp/oauth/") || routePath.startsWith("/.well-known/"))) return routePath;
|
|
if (
|
|
(file === "chat-channels.ts" || file === "email.ts") &&
|
|
routePath.startsWith("/api/chat-webhooks/")
|
|
) {
|
|
return routePath;
|
|
}
|
|
if (file === "voice-sessions.ts" && routePath.startsWith("/api/voice-webhooks/")) return routePath;
|
|
if (file === "tool-gateway.ts" && routePath.startsWith("/mcp/gateways/")) {
|
|
return routePath;
|
|
}
|
|
if (
|
|
file === "connection-intents.ts" &&
|
|
(routePath.startsWith("/mcp/") || routePath.startsWith("/runtime-tools/"))
|
|
) {
|
|
return routePath;
|
|
}
|
|
if ((file === "companies.ts" || file === "health.ts" || file === "liveness.ts" || file === "ready.ts") && routePath === "/") {
|
|
return prefix;
|
|
}
|
|
if (file === "companies.ts" || file === "health.ts") {
|
|
return `${prefix}${routePath}`;
|
|
}
|
|
if (file === "auth.ts") {
|
|
return `${prefix}${routePath === "/" ? "" : routePath}`;
|
|
}
|
|
return `${prefix}${routePath}`;
|
|
}
|
|
|
|
function loadActualRoutes() {
|
|
const routes = new Set<string>();
|
|
const excludedRoutes = new Set<string>();
|
|
const unknownRouteFiles: string[] = [];
|
|
|
|
for (const file of fs
|
|
.readdirSync(ROUTES_DIR)
|
|
.filter((entry) => entry.endsWith(".ts"))) {
|
|
if (explicitOpenApiCoverageExclusions.has(file)) continue;
|
|
const prefix = apiPrefixes[file];
|
|
const source = fs.readFileSync(path.join(ROUTES_DIR, file), "utf8");
|
|
if (!prefix) {
|
|
if (ROUTER_METHOD_PATTERN.test(source)) {
|
|
unknownRouteFiles.push(file);
|
|
}
|
|
continue;
|
|
}
|
|
|
|
for (const match of source.matchAll(ROUTE_LITERAL_PATTERN)) {
|
|
const method = match[1].toUpperCase();
|
|
const routePath = match[2];
|
|
const operation = `${method} ${normalizeExpressPath(resolveMountedPath(file, prefix, routePath))}`;
|
|
if (explicitOpenApiOperationCoverageExclusions.has(operation)) {
|
|
excludedRoutes.add(operation);
|
|
} else {
|
|
routes.add(operation);
|
|
}
|
|
}
|
|
|
|
for (const match of source.matchAll(ROUTE_ARRAY_PATTERN)) {
|
|
for (const literal of match[2].matchAll(/["'`]([^"'`]+)["'`]/g)) {
|
|
const operation = `${match[1].toUpperCase()} ${normalizeExpressPath(resolveMountedPath(file, prefix, literal[1]))}`;
|
|
if (explicitOpenApiOperationCoverageExclusions.has(operation)) excludedRoutes.add(operation);
|
|
else routes.add(operation);
|
|
}
|
|
}
|
|
|
|
if (file === "public-mcp.ts") {
|
|
// The shared gateway mounts these protocol paths for each OAuth resource.
|
|
if (source.includes("mcpDiscoveryDocuments({") && source.includes("router.get(entry.path,")) {
|
|
for (const entry of mcpDiscoveryDocuments({ origin: "https://example.test",
|
|
authorizationOrigin: "https://example.test", profiles: ["personal-mcp", "dot-mcp"] })) {
|
|
const operation = `GET ${entry.path}`;
|
|
if (explicitOpenApiOperationCoverageExclusions.has(operation)) excludedRoutes.add(operation);
|
|
else routes.add(operation);
|
|
}
|
|
}
|
|
for (const match of source.matchAll(/router\.(get|post)\(oauthPath \+ "([^"]+)"/g)) {
|
|
for (const oauthPath of ["/mcp/oauth", "/mcp/runner/oauth"]) {
|
|
const operation = `${match[1].toUpperCase()} ${oauthPath}${match[2]}`;
|
|
if (explicitOpenApiOperationCoverageExclusions.has(operation)) excludedRoutes.add(operation);
|
|
else routes.add(operation);
|
|
}
|
|
}
|
|
}
|
|
const variablePaths = file === "dot-runner.ts" ? ["path", "invitePath"]
|
|
: file === "grok-bot.ts" ? ["path"]
|
|
: file === "muse.ts" ? ["path", "invite"]
|
|
: file === "muse-qualification.ts" ? ["path"] : [];
|
|
for (const name of variablePaths) {
|
|
const basePath = new RegExp(`\\b${name}\\s*=\\s*"([^"]+)"`).exec(source)?.[1];
|
|
if (!basePath) throw new Error(`${file} ${name} route prefix is missing`);
|
|
const methods = new RegExp(`router\\.(get|post|put|delete)\\(\\s*${name}(?:\\s*\\+\\s*"([^"]+)")?\\s*,`, "g");
|
|
for (const match of source.matchAll(methods)) {
|
|
routes.add(`${match[1].toUpperCase()} ${normalizeExpressPath(prefix + basePath + (match[2] ?? ""))}`);
|
|
}
|
|
}
|
|
if (file === "muse.ts" && /for\s*\(const route of MUSE_PUBLIC_ROUTES\)/.test(source)) {
|
|
for (const route of MUSE_PUBLIC_ROUTES) excludedRoutes.add(`${route.method} ${route.path}`);
|
|
}
|
|
|
|
if (
|
|
file === "companies.ts" &&
|
|
source.includes("router.post(COMPANY_IMPORT_ROUTE_PATH")
|
|
) {
|
|
routes.add("POST /api/companies/import");
|
|
}
|
|
if (
|
|
file === "companies.ts" &&
|
|
source.includes("router.post(COMPANY_IMPORT_TRANSFERS_ROUTE_PATH")
|
|
) {
|
|
routes.add(`POST /api/companies${COMPANY_IMPORT_TRANSFERS_ROUTE_PATH}`);
|
|
}
|
|
}
|
|
|
|
return {
|
|
routes,
|
|
excludedRoutes,
|
|
unknownRouteFiles: unknownRouteFiles.sort(),
|
|
};
|
|
}
|
|
|
|
function loadSpecRoutes() {
|
|
const spec = buildOpenApiSpec();
|
|
const routes = new Set<string>();
|
|
|
|
for (const [routePath, pathItem] of Object.entries<
|
|
Record<string, Record<string, unknown>>
|
|
>(spec.paths ?? {})) {
|
|
for (const method of Object.keys(pathItem)) {
|
|
if (HTTP_METHODS.has(method)) {
|
|
routes.add(`${method.toUpperCase()} ${routePath}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
return { spec, routes };
|
|
}
|
|
|
|
describe("openapi routes", () => {
|
|
it("tells agents that unpriced usage in cost reports is unknown cost, not zero", () => {
|
|
const paths = buildOpenApiSpec().paths;
|
|
for (const segment of ["summary", "by-agent", "by-agent-model", "by-project"]) {
|
|
const description = paths[`/api/companies/{companyId}/costs/${segment}`].get.description as string;
|
|
expect(description).toContain("unpricedEventCount is above 0");
|
|
expect(description).toContain("never as $0.00");
|
|
expect(description).toContain("GET /api/companies/{companyId}/heartbeat-runs?agentId=<agentId>");
|
|
expect(description).not.toContain("costs/data-quality");
|
|
}
|
|
expect(paths["/api/companies/{companyId}/costs/window-spend"].get.description).toBeUndefined();
|
|
});
|
|
|
|
it("tells agents managed-agent profiles are created with the CLI, not a web page", () => {
|
|
const route = buildOpenApiSpec().paths["/api/companies/{companyId}/managed-agent-profiles"];
|
|
for (const operation of [route.get, route.post]) {
|
|
expect(operation.description).toContain("Board only");
|
|
expect(operation.description).toContain("There is no web page");
|
|
}
|
|
expect(route.post.description).toContain("paperclipai managed-agent setup --company-id <companyId>");
|
|
expect(route.post.description).toContain("--acknowledge-retention");
|
|
});
|
|
|
|
it("documents the agent Mine inbox read as a person's inbox that requires their user id", () => {
|
|
const operation = buildOpenApiSpec().paths["/api/agents/me/inbox/mine"].get;
|
|
expect(operation.summary).not.toMatch(/current agent/i);
|
|
expect(operation.description).toContain("/<prefix>/inbox/mine");
|
|
expect(operation.description).toContain("not your own work queue");
|
|
const userId = operation.parameters.find((parameter: { name: string; in: string }) => parameter.name === "userId" && parameter.in === "query");
|
|
expect(userId).toMatchObject({ required: true });
|
|
});
|
|
|
|
it("documents the export include body so agents can request projects and skills", () => {
|
|
const spec = buildOpenApiSpec();
|
|
for (const path of ["/api/companies/{companyId}/exports", "/api/companies/{companyId}/exports/preview"]) {
|
|
const operation = spec.paths[path].post;
|
|
const body = operation.requestBody.content["application/json"].schema;
|
|
expect(body.properties.include.properties).toMatchObject({ projects: expect.anything(), skills: expect.anything() });
|
|
expect(operation.description).toMatch(/include\.projects/);
|
|
}
|
|
});
|
|
it("documents the safe company import body so agents can preview and resolve agent name conflicts", () => {
|
|
const spec = buildOpenApiSpec();
|
|
for (const path of ["/api/companies/{companyId}/imports/preview", "/api/companies/{companyId}/imports/apply"]) {
|
|
const operation = spec.paths[path].post;
|
|
const body = operation.requestBody.content["application/json"].schema;
|
|
expect(body.required).toEqual(expect.arrayContaining(["source", "target"]));
|
|
expect(body.properties).toMatchObject({ collisionStrategy: expect.anything(), nameOverrides: expect.anything(), include: expect.anything() });
|
|
expect(operation.description).toMatch(/replace/);
|
|
}
|
|
});
|
|
it("documents generic webhook provenance headers and accepted responses without a provider-specific endpoint", () => {
|
|
const spec = buildOpenApiSpec();
|
|
const operation = spec.paths["/api/routine-triggers/public/{publicId}/fire"].post;
|
|
expect(operation.parameters).toEqual(expect.arrayContaining([
|
|
expect.objectContaining({ in: "header", name: "X-Paperclip-Source-Run-Token", required: false }),
|
|
expect.objectContaining({ in: "header", name: "X-Paperclip-Idempotency-Scope", required: false }),
|
|
]));
|
|
for (const status of ["202", "400", "401", "404", "409", "415", "422"]) expect(operation.responses).toHaveProperty(status);
|
|
expect(operation.requestBody.content).toHaveProperty("application/json");
|
|
expect(spec.paths).not.toHaveProperty("/api/routine-triggers/public/{publicId}/sentry-run-failures");
|
|
});
|
|
it("documents connected-app skill review as board only and file reads as agent-run only", () => {
|
|
const spec = buildOpenApiSpec() as any;
|
|
const files = spec.paths["/api/agents/me/mcp-skills/{skillId}/files"].get;
|
|
expect(files["x-paperclip-authorization"]).toEqual({ actor: "agent", heartbeatBound: true });
|
|
expect(files.security).not.toContainEqual({ BoardSessionAuth: [] });
|
|
expect(spec.paths["/api/companies/{companyId}/mcp-skills/{skillId}/approve"].post["x-paperclip-authorization"]).toEqual({ actor: "board" });
|
|
});
|
|
|
|
it.each(["summary", "tasks"])("documents the board-only compact attention %s contract", projection => {
|
|
const spec = buildOpenApiSpec() as any;
|
|
const operation = spec.paths[`/api/companies/{companyId}/attention/${projection}`].get;
|
|
expect(operation.security).toEqual([{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }]);
|
|
expect(operation["x-paperclip-authorization"]).toEqual({ actor: "board" });
|
|
expect(operation.parameters.filter((parameter: { in: string }) => parameter.in === "query")).toEqual([]);
|
|
const response = operation.responses["200"].content["application/json"].schema;
|
|
expect(response.properties.totalCount).toMatchObject({ type: "integer", minimum: 0 });
|
|
expect(response.properties.generatedAt).toMatchObject({ format: "date-time" });
|
|
expect(response.properties.items).toBeUndefined();
|
|
expect(response.properties.nextCursor).toBeUndefined();
|
|
if (projection === "tasks") expect(response.properties.taskIds).toMatchObject({ type: "array", items: { type: "string", format: "uuid" } });
|
|
for (const code of ["200", "401", "403"]) expect(operation.responses[code]).toBeDefined();
|
|
});
|
|
|
|
// Full chat cohort 4: search_api listed the cancel route as open to agents, so an agent tried it and got 403.
|
|
it("documents question cancellation as board-only and points agents to withdraw", () => {
|
|
const spec = buildOpenApiSpec() as any;
|
|
const cancel = spec.paths["/api/issues/{id}/interactions/{interactionId}/cancel"].post;
|
|
expect(cancel["x-paperclip-authorization"]).toEqual({ actor: "board" });
|
|
expect(cancel.security).toEqual([{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }]);
|
|
expect(cancel.summary).toContain("POST /api/issues/{id}/interactions/{interactionId}/withdraw");
|
|
expect(spec.paths["/api/issues/{id}/interactions/{interactionId}/withdraw"].post["x-paperclip-authorization"]).toEqual({ actor: "board_or_agent" });
|
|
});
|
|
|
|
it("points agents to resolve-from-comment to record a person's decline and keeps withdraw for their own obsolete card", () => {
|
|
const spec = buildOpenApiSpec() as any;
|
|
const interaction = "/api/issues/{id}/interactions/{interactionId}";
|
|
for (const summary of [spec.paths[`${interaction}/cancel`].post.summary, spec.paths[`${interaction}/withdraw`].post.summary]) {
|
|
expect(summary).toContain("only for the agent's own obsolete card");
|
|
expect(summary).toContain(`POST ${interaction}/resolve-from-comment`);
|
|
expect(summary).toContain("when the card's resolver policy allows");
|
|
expect(summary).toContain("to accept or decline a confirmation card on the person's explicit instruction");
|
|
expect(summary).toContain("not for question forms or governed approvals");
|
|
}
|
|
expect(spec.paths[`${interaction}/resolve-from-comment`].post.summary).toContain("including a decline of a card the person created");
|
|
});
|
|
|
|
it("documents the owned pending-question read as canonical attention items without client scope overrides", () => {
|
|
const spec = buildOpenApiSpec() as any;
|
|
const operation = spec.paths["/api/issues/{id}/pending-questions"].get;
|
|
expect(operation.security).toEqual([{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }]);
|
|
expect(operation["x-paperclip-authorization"]).toEqual({ actor: "board" });
|
|
expect(operation.parameters.filter((parameter: { in: string }) => parameter.in === "query")).toEqual([]);
|
|
const response = operation.responses["200"].content["application/json"].schema;
|
|
expect(response).toMatchObject({ type: "array", items: { type: "object", properties: {
|
|
sourceKind: { enum: ["issue_thread_interaction"] },
|
|
detail: { properties: { kind: { enum: ["questions"] } } },
|
|
} } });
|
|
for (const code of ["200", "400", "401", "403", "404"]) expect(operation.responses[code]).toBeDefined();
|
|
});
|
|
|
|
it("documents task-tree controls as board-only and names the human page", () => {
|
|
const spec = buildOpenApiSpec() as any;
|
|
const boardSecurity = [{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }];
|
|
for (const [path, method] of [
|
|
["/api/issues/{id}/tree-control/state", "get"],
|
|
["/api/issues/{id}/tree-control/preview", "post"],
|
|
["/api/issues/{id}/tree-holds", "get"],
|
|
["/api/issues/{id}/tree-holds", "post"],
|
|
["/api/issues/{id}/tree-holds/{holdId}", "get"],
|
|
["/api/issues/{id}/tree-holds/{holdId}/release", "post"],
|
|
] as const) {
|
|
const operation = spec.paths[path][method];
|
|
expect(operation.security).toEqual(boardSecurity);
|
|
expect(operation["x-paperclip-authorization"]).toEqual({ actor: "board" });
|
|
}
|
|
const create = spec.paths["/api/issues/{id}/tree-holds"].post.description as string;
|
|
expect(create).toContain("Pause subtree");
|
|
expect(create).toContain("/{prefix}/issues/{identifier}");
|
|
});
|
|
|
|
it("publishes grant-gated access operations as board_or_agent and keeps member edits board-only", () => {
|
|
const spec = buildOpenApiSpec() as any;
|
|
for (const [path, method, grant] of [
|
|
["/api/companies/{companyId}/invites", "post", "users:invite"],
|
|
["/api/companies/{companyId}/invites", "get", "users:invite"],
|
|
["/api/companies/{companyId}/join-requests", "get", "joins:approve"],
|
|
["/api/companies/{companyId}/join-requests/{requestId}/approve", "post", "joins:approve"],
|
|
["/api/companies/{companyId}/join-requests/{requestId}/reject", "post", "joins:approve"],
|
|
["/api/companies/{companyId}/members", "get", "users:manage_permissions"],
|
|
] as const) {
|
|
const operation = spec.paths[path][method];
|
|
expect(operation["x-paperclip-authorization"], `${method} ${path}`).toEqual({ actor: "board_or_agent" });
|
|
expect(operation.description).toContain(grant);
|
|
}
|
|
expect(spec.paths["/api/companies/{companyId}/invites"].post.description).toContain("inviteUrl");
|
|
for (const path of [
|
|
"/api/companies/{companyId}/members/{memberId}/permissions",
|
|
"/api/companies/{companyId}/members/{memberId}/role-and-grants",
|
|
]) {
|
|
expect(spec.paths[path].patch["x-paperclip-authorization"]).toEqual({ actor: "board" });
|
|
expect(spec.paths[path].patch.description).toContain("/<prefix>/company/settings/members");
|
|
}
|
|
expect(spec.paths["/api/companies/{companyId}/members"].get.description).toContain("/<prefix>/company/settings/members");
|
|
});
|
|
|
|
it("documents owned conversation reads and exact revision access separately", () => {
|
|
const spec = buildOpenApiSpec() as any;
|
|
const boardSecurity = [{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }];
|
|
for (const path of [
|
|
"/api/issues/{id}/decision-receipts",
|
|
"/api/issues/{id}/chat-handoffs",
|
|
"/api/companies/{companyId}/attention/history",
|
|
]) {
|
|
const operation = spec.paths[path].get;
|
|
expect(operation.security).toEqual(boardSecurity);
|
|
expect(operation["x-paperclip-authorization"]).toEqual({ actor: "board" });
|
|
const query = Object.fromEntries(operation.parameters
|
|
.filter((parameter: { in: string }) => parameter.in === "query")
|
|
.map((parameter: { name: string; schema: unknown }) => [parameter.name, parameter.schema]));
|
|
expect(query.cursor).toMatchObject({ type: "string", maxLength: 1000 });
|
|
expect(query.limit).toMatchObject({ type: "integer", minimum: 1, maximum: 100 });
|
|
if (path.endsWith("/history")) {
|
|
expect(query.search).toMatchObject({ maxLength: 200 });
|
|
expect(query.outcome).toMatchObject({ maxLength: 40 });
|
|
expect(query.agentId).toMatchObject({ format: "uuid" });
|
|
expect(query.projectId).toMatchObject({ format: "uuid" });
|
|
expect(query.sort).toMatchObject({ enum: ["newest", "oldest"] });
|
|
expect(query.since).toMatchObject({ format: "date-time" });
|
|
} else {
|
|
expect(Object.keys(query).sort()).toEqual(["cursor", "limit"]);
|
|
expect(operation.responses["404"]).toBeDefined();
|
|
}
|
|
for (const code of ["200", "400", "401", "403"]) {
|
|
expect(operation.responses[code]).toBeDefined();
|
|
}
|
|
}
|
|
|
|
const revision = spec.paths["/api/issues/{id}/documents/{key}/revisions/{revisionId}"].get;
|
|
expect(revision.security).toEqual([...boardSecurity, { AgentBearerAuth: [] }]);
|
|
const params = Object.fromEntries(revision.parameters.map(
|
|
(parameter: { name: string; schema: unknown }) => [parameter.name, parameter.schema],
|
|
));
|
|
expect(params.key).toMatchObject({ minLength: 1, maxLength: 64, pattern: "^[a-z0-9][a-z0-9_-]*$" });
|
|
expect(params.revisionId).toMatchObject({ type: "string", format: "uuid" });
|
|
for (const code of ["200", "400", "401", "403", "404"]) {
|
|
expect(revision.responses[code]).toBeDefined();
|
|
}
|
|
});
|
|
|
|
it("removes Pipelines discovery while retaining Cases and Routines", () => {
|
|
const spec = buildOpenApiSpec() as any;
|
|
const paths = Object.keys(spec.paths);
|
|
expect(paths.filter((path) => /pipelines|review-cases|case-events/.test(path))).toEqual([]);
|
|
// Standalone handoffs also use caseId; that parameter name no longer
|
|
// identifies a removed Pipeline operation. Retain only their live paths.
|
|
expect(paths.filter((path) => path.startsWith("/api/cases/{caseId}")).sort()).toEqual([
|
|
"/api/cases/{caseId}/handoffs",
|
|
"/api/cases/{caseId}/handoffs/{handoffId}/cancel",
|
|
"/api/cases/{caseId}/handoffs/{handoffId}/retry",
|
|
]);
|
|
expect(spec.paths["/api/companies/{companyId}/cases"].post).toBeDefined();
|
|
expect(spec.paths["/api/companies/{companyId}/case-handoffs"].post).toBeDefined();
|
|
expect(spec.paths["/api/cases/{id}"].get).toBeDefined();
|
|
expect(spec.paths["/api/routines/{id}/run"].post).toBeDefined();
|
|
});
|
|
|
|
it("documents anonymous liveness separately from database readiness", () => {
|
|
const spec = buildOpenApiSpec() as any;
|
|
for (const method of ["get", "head"]) {
|
|
const operation = spec.paths["/api/liveness"][method];
|
|
expect(operation.security).toEqual([]);
|
|
expect(operation.responses[503]).toBeDefined();
|
|
}
|
|
expect(Object.keys(spec.paths["/api/liveness"].get.responses[200].content["application/json"].schema.properties))
|
|
.toEqual(["status", "commit"]);
|
|
expect(spec.paths["/api/health"].get.responses[503]).toBeDefined();
|
|
});
|
|
it("documents only writable agent update fields and lifecycle status requests", () => {
|
|
const document = buildOpenApiSpec() as any;
|
|
const properties = document.paths["/api/agents/{id}"].patch.requestBody.content["application/json"].schema.properties;
|
|
expect(properties).not.toHaveProperty("spentMonthlyCents");
|
|
expect(properties.status.enum).toEqual(["paused", "idle", "terminated"]);
|
|
expect(properties).toHaveProperty("name");
|
|
expect(properties).toHaveProperty("budgetMonthlyCents");
|
|
});
|
|
|
|
it("documents public Dot pairing capabilities while ordinary consent keeps board authentication", () => {
|
|
const spec = buildOpenApiSpec() as any;
|
|
for (const [method, path] of [
|
|
["get", "/api/dot-mcp/requests/{id}"],
|
|
["post", "/api/dot-mcp/requests/{id}/dot-pairing"],
|
|
["post", "/api/dot-mcp/requests/{id}/dot-pairing/preview"],
|
|
]) {
|
|
expect(spec.paths[path][method].security).toEqual([]);
|
|
expect(spec.paths[path][method].responses["404"]).toBeDefined();
|
|
}
|
|
expect(spec.paths["/api/mcp/requests/{id}/consent"].post.security).not.toEqual([]);
|
|
});
|
|
|
|
it("documents manager-only task privacy hints without protected scope identity", () => {
|
|
const spec = buildOpenApiSpec() as any;
|
|
const operation = spec.paths["/api/issues/{id}/privacy-constraints"].get;
|
|
const schema = operation.responses["200"].content["application/json"].schema;
|
|
expect(schema.properties).toEqual({
|
|
publicBlockedBy: { type: "string", enum: ["parent", "project"], nullable: true },
|
|
leavesPersonalProject: { type: "boolean" },
|
|
});
|
|
expect(schema.required).toEqual(["publicBlockedBy", "leavesPersonalProject"]);
|
|
expect(operation.responses["403"]).toBeDefined();
|
|
expect(operation.responses["404"]).toBeDefined();
|
|
});
|
|
|
|
it("documents strict run-attributed feedback and board-or-agent commentary reads", () => {
|
|
const { spec } = loadSpecRoutes();
|
|
const path = spec.paths["/api/companies/{companyId}/agent-commentary"];
|
|
expect(Object.keys(path)).toEqual(["get", "post"]);
|
|
const detail = spec.paths["/api/companies/{companyId}/agent-commentary/{id}"].get;
|
|
for (const read of [path.get, detail]) {
|
|
expect(read.security).toEqual([{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }, { AgentBearerAuth: [] }]);
|
|
expect(read.responses["403"]).toBeDefined();
|
|
expect(read.responses["404"]).toBeDefined();
|
|
}
|
|
expect(path.get.parameters.map((parameter: { name: string }) => parameter.name)).toEqual(
|
|
expect.arrayContaining(["agentId", "kind", "q", "limit", "offset"]),
|
|
);
|
|
const operation = path.post;
|
|
expect(operation.security).toEqual([{ AgentBearerAuth: [] }]);
|
|
expect(operation["x-paperclip-authorization"]).toEqual({ actor: "agent", heartbeatBound: true });
|
|
expect(operation.description).toContain("X-Paperclip-Run-Id");
|
|
const body = operation.requestBody.content["application/json"].schema;
|
|
expect(body.additionalProperties).toBe(false);
|
|
expect(Object.keys(body.properties).sort()).toEqual(["body", "idempotencyKey", "kind"]);
|
|
expect(body.properties.body.maxLength).toBe(524288);
|
|
for (const code of ["200", "201"]) {
|
|
const result = operation.responses[code].content["application/json"].schema;
|
|
expect(result.additionalProperties).toBe(false);
|
|
expect(Object.keys(result.properties).sort()).toEqual(["createdAt", "id", "kind", "replayed"]);
|
|
}
|
|
expect(operation.responses["409"]).toBeDefined();
|
|
expect(operation.responses["503"]).toBeDefined();
|
|
});
|
|
|
|
it("documents delegated pool management with revision-checked deletion", () => {
|
|
const { spec } = loadSpecRoutes();
|
|
const pools = spec.paths["/api/companies/{companyId}/ai-connection-pools"];
|
|
const remove = spec.paths["/api/companies/{companyId}/ai-connection-pools/{poolId}"].delete;
|
|
const inspection = spec.paths["/api/companies/{companyId}/ai-connection-pools/{poolId}/inspection"].get;
|
|
for (const operation of [pools.get, pools.post, remove, inspection]) {
|
|
expect(operation.security).toEqual([{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }, { AgentBearerAuth: [] }]);
|
|
}
|
|
expect(remove.requestBody.required).toBe(true);
|
|
expect(remove.requestBody.content["application/json"].schema).toMatchObject({
|
|
required: ["expectedRevision"], additionalProperties: false,
|
|
properties: { expectedRevision: { type: "integer", minimum: 0, exclusiveMinimum: true } },
|
|
});
|
|
expect(Object.keys(remove.responses)).toEqual(expect.arrayContaining(["200", "400", "401", "403", "404", "409"]));
|
|
});
|
|
|
|
it("documents masked board-only agent export settings and revision-checked writes", () => {
|
|
const { spec } = loadSpecRoutes();
|
|
const settings = spec.paths["/api/companies/{companyId}/observability"];
|
|
const test = spec.paths["/api/companies/{companyId}/observability/test"].post;
|
|
for (const operation of [settings.get, settings.put, settings.delete, test]) {
|
|
expect(operation.security).toEqual([{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }]);
|
|
}
|
|
expect(settings.delete.requestBody.content["application/json"].schema).toMatchObject({ required: ["expectedRevision"], additionalProperties: false });
|
|
expect(test.responses["409"]).toBeDefined();
|
|
expect(JSON.stringify(settings.get.responses)).not.toMatch(/credentialsSecretId|ciphertext|apiKey/);
|
|
expect(test.responses["200"].content["application/json"].schema.properties.source).toMatchObject({ enum: ["control_plane"] });
|
|
});
|
|
|
|
it("documents personal board-only announcements and private responses", () => {
|
|
const { spec } = loadSpecRoutes();
|
|
const current = spec.paths["/api/announcements/current"].get;
|
|
const image = spec.paths["/api/announcements/{id}/image"].get;
|
|
const animation = spec.paths["/api/announcements/{id}/animation"].get;
|
|
const dismiss = spec.paths["/api/announcements/{id}/dismiss"].post;
|
|
for (const operation of [current, image, animation, dismiss]) {
|
|
expect(operation.security).toEqual([{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }]);
|
|
expect(operation["x-paperclip-authorization"]).toEqual({ actor: "board" });
|
|
const success = operation.responses["200"] ?? operation.responses["204"];
|
|
expect(success.headers["Cache-Control"].schema.enum).toEqual(["private, no-store"]);
|
|
}
|
|
expect(current.responses["200"].content["application/json"].schema.nullable).toBe(true);
|
|
expect(Object.keys(image.responses["200"].content)).toEqual(["image/png", "image/jpeg", "image/webp"]);
|
|
expect(dismiss.requestBody.content["application/json"].schema).toMatchObject({
|
|
required: ["companyId"], additionalProperties: false,
|
|
});
|
|
expect(dismiss.description).toContain("viewers may dismiss their own");
|
|
});
|
|
|
|
it("tells agents that Agent Chat is always on instead of advertising a retired toggle", async () => {
|
|
const res = await request(createApp()).get("/api/openapi.json");
|
|
const experimental = res.body.paths["/api/instance/settings/experimental"];
|
|
for (const operation of [experimental.get, experimental.patch]) {
|
|
expect(operation.description).toContain("Agent Chat is always on");
|
|
expect(operation.description).toContain("enableAgentChat is a retired compatibility key");
|
|
expect(operation.description).toContain("tell them it is already on");
|
|
}
|
|
});
|
|
|
|
it("names the Experimental settings page where an instance admin turns a feature on", async () => {
|
|
const res = await request(createApp()).get("/api/openapi.json");
|
|
const experimental = res.body.paths["/api/instance/settings/experimental"];
|
|
for (const operation of [experimental.get, experimental.patch]) {
|
|
expect(operation.description).toContain("[Experimental settings](/<prefix>/company/settings/instance/experimental)");
|
|
expect(operation.description).toContain("Agent credentials cannot read or change these settings");
|
|
expect(operation.description).toContain("Cases via enableCases");
|
|
}
|
|
});
|
|
|
|
it("names the hosting operator instead of a hidden Experimental settings page", () => {
|
|
const hidden = applyPluginSettingsVisibility(buildOpenApiDocument(), new Set(["instance.experimental"]));
|
|
const experimental = hidden.paths["/api/instance/settings/experimental"];
|
|
for (const operation of [experimental.get, experimental.patch]) {
|
|
expect(operation.description).toContain("controlled by the hosting operator");
|
|
expect(operation.description).not.toContain("/instance/experimental");
|
|
}
|
|
});
|
|
|
|
it("tells agents that archiving keeps a status card and where a person restores it", async () => {
|
|
const res = await request(createApp()).get("/api/openapi.json");
|
|
const patch = res.body.paths["/api/status-cards/{id}"].patch;
|
|
expect(patch.description).toContain("it is not deleted");
|
|
expect(patch.description).toContain("give them the returned href as a Markdown link");
|
|
expect(patch.description).toContain("Restoring (archived: false) starts a fresh full summary");
|
|
});
|
|
|
|
it("tells agents that creating or refreshing a status card only queues the summarizer, so they reply now with its link", async () => {
|
|
const res = await request(createApp()).get("/api/openapi.json");
|
|
const create = res.body.paths["/api/companies/{companyId}/status-cards"].post;
|
|
expect(create.description).toContain("The response is returned before any summary exists");
|
|
expect(create.description).toContain("reply now with the returned href as a Markdown link");
|
|
const refresh = res.body.paths["/api/status-cards/{id}/refresh"].post;
|
|
expect(refresh.description).toContain("Queues a refresh; it does not return a new summary");
|
|
expect(refresh.description).toContain("Do not sleep or poll for it: reply now that the refresh is queued, with the returned card.href");
|
|
});
|
|
|
|
it("documents exact failed-run selection and durable accepted retry responses", async () => {
|
|
const res = await request(createApp()).get("/api/openapi.json");
|
|
const wake = res.body.paths["/api/agents/{id}/wakeup"].post;
|
|
expect(
|
|
wake.requestBody.content["application/json"].schema.properties
|
|
.failedRunId,
|
|
).toMatchObject({ type: "string", format: "uuid" });
|
|
expect(wake.responses["202"]).toBeDefined();
|
|
expect(wake.responses["409"]).toBeDefined();
|
|
expect(wake.description).toContain("durable queued/deferred receipt");
|
|
});
|
|
it("advertises the guarded prepared-task promotion contract to API clients", async () => {
|
|
const res = await request(createApp()).get("/api/openapi.json");
|
|
const patch = res.body.paths["/api/issues/{id}"].patch;
|
|
expect(patch.requestBody.content["application/json"].schema.properties.expectedStatusVersion)
|
|
.toMatchObject({ type: "integer", minimum: 0 });
|
|
expect(patch.responses["409"]).toBeDefined();
|
|
expect(patch.description).toContain("send exactly status=todo and expectedStatusVersion");
|
|
});
|
|
it("serves the generated OpenAPI document", async () => {
|
|
const res = await request(createApp()).get("/api/openapi.json");
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.openapi).toBe("3.0.0");
|
|
expect(res.body.info.title).toBe("Paperclip API");
|
|
expect(res.body.paths["/api/openapi.json"].get.summary).toBe(
|
|
"Get the generated OpenAPI document",
|
|
);
|
|
expect(
|
|
res.body.paths["/api/companies/{companyId}/agents"].get.summary,
|
|
).toBe("List agents in a company");
|
|
expect(res.body.paths["/api/agents/{id}/keys"].post.summary).toBe(
|
|
"Create an agent API key",
|
|
);
|
|
expect(res.body.components.securitySchemes).toMatchObject({
|
|
BoardSessionAuth: { type: "apiKey", in: "cookie" },
|
|
BoardApiKeyAuth: { type: "http", scheme: "bearer" },
|
|
AgentBearerAuth: { type: "http", scheme: "bearer" },
|
|
});
|
|
expect(res.body.paths["/api/health"].get.security).toEqual([]);
|
|
expect(res.body.paths["/api/mcp/project-tools"].post.security).toEqual([{ AgentRunAuth: [] }]);
|
|
expect(res.body.paths["/api/mcp/project-tools"].post["x-paperclip-authorization"]).toEqual({ actor: "agent", heartbeatBound: true, taskBound: true });
|
|
expect(res.body.paths["/mcp/gateways/{gatewayPublicId}"].post.security).toEqual([]);
|
|
expect(res.body.paths["/api/mcp/gateways/{gatewayPublicId}"]).toBeUndefined();
|
|
expect(res.body.paths["/api/companies"].get.parameters).toContainEqual({
|
|
name: "scope",
|
|
in: "query",
|
|
required: false,
|
|
schema: { type: "string", enum: ["accessible"] },
|
|
});
|
|
expect(res.body.paths["/api/companies"].get.responses["403"]).toBeDefined();
|
|
expect(res.body.paths["/api/companies"].get.responses["400"]).toBeDefined();
|
|
expect(
|
|
res.body.paths["/api/companies"].post.responses["201"],
|
|
).toBeDefined();
|
|
expect(
|
|
res.body.paths["/api/companies"].post.requestBody.content[
|
|
"application/json"
|
|
].schema,
|
|
).toMatchObject({
|
|
type: "object",
|
|
properties: {
|
|
name: { type: "string", minLength: 1 },
|
|
},
|
|
required: ["name"],
|
|
});
|
|
expect(
|
|
JSON.stringify(res.body.paths["/api/companies"].post.responses),
|
|
).not.toContain("candidates");
|
|
expect(
|
|
res.body.paths["/api/companies/{companyId}/skills/scan-projects"].post
|
|
.responses["200"].content["application/json"].schema,
|
|
).toMatchObject({
|
|
type: "object",
|
|
properties: {
|
|
candidates: { type: "array" },
|
|
},
|
|
required: expect.arrayContaining(["candidates"]),
|
|
});
|
|
expect(
|
|
res.body.paths["/api/agents/{id}/keys"].post.requestBody.content[
|
|
"application/json"
|
|
].schema,
|
|
).toMatchObject({
|
|
type: "object",
|
|
properties: {
|
|
name: { type: "string" },
|
|
},
|
|
});
|
|
expect(
|
|
res.body.paths["/api/companies/{companyId}/folders"].post.responses[
|
|
"201"
|
|
],
|
|
).toBeDefined();
|
|
expect(
|
|
Object.keys(
|
|
res.body.paths[
|
|
"/api/issues/{id}/work-products/{workProductId}/review-document"
|
|
].post.responses,
|
|
).sort(),
|
|
).toEqual(["200", "201", "401", "403", "404", "409", "413", "415", "422"]);
|
|
expect(
|
|
res.body.paths["/api/issues/{id}/interactions/{interactionId}/withdraw"]
|
|
.post.summary,
|
|
).toMatch(/^Withdraw a pending issue thread interaction\. /);
|
|
const createInteraction =
|
|
res.body.paths["/api/issues/{id}/interactions"].post;
|
|
expect(createInteraction.description).toContain(
|
|
"defaults to canonical `anyone`",
|
|
);
|
|
const createInteractionSchema = JSON.stringify(
|
|
createInteraction.requestBody.content["application/json"].schema,
|
|
);
|
|
for (const resolverPolicy of [
|
|
"anyone",
|
|
"not_creator",
|
|
"human_only",
|
|
"board_or_agents",
|
|
"board_only",
|
|
]) {
|
|
expect(createInteractionSchema).toContain(`\"${resolverPolicy}\"`);
|
|
}
|
|
expect(
|
|
res.body.paths["/api/companies/{companyId}/folders/items/move"].post
|
|
.summary,
|
|
).toBe("Move an item into or out of a folder");
|
|
const createQueue =
|
|
res.body.paths["/api/companies/{companyId}/decision-queues"].post;
|
|
expect(createQueue.security).toContainEqual({ AgentBearerAuth: [] });
|
|
expect(createQueue.responses["200"]).toBeDefined();
|
|
expect(createQueue.responses["201"]).toBeDefined();
|
|
expect(
|
|
createQueue.requestBody.content["application/json"].schema,
|
|
).toMatchObject({
|
|
type: "object",
|
|
properties: {
|
|
key: { type: "string", minLength: 1, maxLength: 80 },
|
|
title: { type: "string", minLength: 1, maxLength: 120 },
|
|
},
|
|
required: ["key", "title"],
|
|
});
|
|
const updateTriage =
|
|
res.body.paths[
|
|
"/api/companies/{companyId}/decision-triage/{sourceKind}/{sourceId}"
|
|
].put;
|
|
expect(updateTriage.responses["422"]).toBeDefined();
|
|
expect(
|
|
updateTriage.requestBody.content["application/json"].schema.properties,
|
|
).toMatchObject({
|
|
decideBy: { nullable: true },
|
|
snoozedUntil: { type: "string", format: "date-time", nullable: true },
|
|
});
|
|
expect(
|
|
JSON.stringify(res.body.paths["/api/tool-gateway/tools"].get),
|
|
).not.toContain("sessionToken");
|
|
expect(
|
|
JSON.stringify(res.body.paths["/api/tool-gateway/tools/call"].post),
|
|
).not.toContain("sessionToken");
|
|
});
|
|
|
|
it("publishes delegated chat configuration and human-only confirmation boundaries", () => {
|
|
const { spec } = loadSpecRoutes();
|
|
const boardSecurity = [{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }];
|
|
const operations = [
|
|
["get", "/api/companies/{companyId}/chat-endpoints"],
|
|
["post", "/api/companies/{companyId}/chat-endpoints"],
|
|
["get", "/api/chat-endpoints/{endpointId}"],
|
|
["get", "/api/chat-endpoints/{endpointId}/github/configuration"],
|
|
["put", "/api/chat-endpoints/{endpointId}/github/configuration"],
|
|
["post", "/api/chat-endpoints/{endpointId}/github/verify"],
|
|
["put", "/api/chat-endpoints/{endpointId}/github/progress"],
|
|
["get", "/api/chat-endpoints/{endpointId}/github/reviews"],
|
|
["get", "/api/chat-endpoints/{endpointId}/github/personal-connections"],
|
|
["post", "/api/chat-endpoints/{endpointId}/github/identity"],
|
|
["post", "/api/chat-endpoints/{endpointId}/github/people/lookup"],
|
|
["post", "/api/chat-endpoints/{endpointId}/github/registration"],
|
|
["post", "/api/chat-endpoints/{endpointId}/github/app"],
|
|
["post", "/api/chat-endpoints/{endpointId}/github/repositories/refresh"],
|
|
["patch", "/api/chat-endpoints/{endpointId}"],
|
|
["post", "/api/chat-endpoints/{endpointId}/setup"],
|
|
["post", "/api/chat-endpoints/{endpointId}/setup-secret"],
|
|
["post", "/api/chat-endpoints/{endpointId}/test"],
|
|
["post", "/api/chat-endpoints/{endpointId}/photon/inspect"],
|
|
["get", "/api/chat-endpoints/{endpointId}/resources"],
|
|
["put", "/api/chat-endpoints/{endpointId}/resources"],
|
|
["get", "/api/chat-endpoints/{endpointId}/principals"],
|
|
[
|
|
"post",
|
|
"/api/chat-endpoints/{endpointId}/principals/{principalId}/link-intent",
|
|
],
|
|
[
|
|
"delete",
|
|
"/api/chat-endpoints/{endpointId}/principals/{principalId}/link",
|
|
],
|
|
["get", "/api/chat-identity-links/preview"],
|
|
["post", "/api/chat-identity-links/confirm"],
|
|
["get", "/api/chat-endpoints/{endpointId}/conversations"],
|
|
["get", "/api/chat-endpoints/{endpointId}/activity"],
|
|
[
|
|
"post",
|
|
"/api/chat-endpoints/{endpointId}/deliveries/{deliveryId}/replay",
|
|
],
|
|
[
|
|
"post",
|
|
"/api/chat-endpoints/{endpointId}/publications/{publicationId}/replay",
|
|
],
|
|
[
|
|
"post",
|
|
"/api/chat-endpoints/{endpointId}/publications/{publicationId}/resolve",
|
|
],
|
|
["post", "/api/chat-endpoints/{endpointId}/actions/{actionId}/resolve"],
|
|
[
|
|
"post",
|
|
"/api/chat-endpoints/{endpointId}/conversations/{conversationId}/publications",
|
|
],
|
|
["get", "/api/issues/{issueId}/chat-binding"],
|
|
[
|
|
"get",
|
|
"/api/chat-endpoints/{endpointId}/conversations/{conversationId}/publications/{publicationId}/status",
|
|
],
|
|
] as const;
|
|
|
|
const humanOnly = new Set([
|
|
"/api/chat-endpoints/{endpointId}/deliveries/{deliveryId}/replay",
|
|
"/api/chat-endpoints/{endpointId}/publications/{publicationId}/replay",
|
|
"/api/chat-endpoints/{endpointId}/conversations/{conversationId}/publications",
|
|
"/api/chat-endpoints/{endpointId}/github/identity", "/api/chat-identity-links/preview", "/api/chat-identity-links/confirm",
|
|
"/api/chat-endpoints/{endpointId}/publications/{publicationId}/resolve", "/api/chat-endpoints/{endpointId}/actions/{actionId}/resolve",
|
|
]);
|
|
for (const [method, routePath] of operations) {
|
|
const operation = spec.paths[routePath]?.[method];
|
|
expect(
|
|
operation,
|
|
`${method.toUpperCase()} ${routePath} is documented`,
|
|
).toBeDefined();
|
|
expect(
|
|
operation.security,
|
|
`${method.toUpperCase()} ${routePath} retains its actor boundary`,
|
|
).toEqual(humanOnly.has(routePath) ? boardSecurity : [...boardSecurity, { AgentBearerAuth: [] }]);
|
|
expect(operation["x-paperclip-authorization"]).toEqual({
|
|
actor: humanOnly.has(routePath) ? "board" : "board_or_agent",
|
|
});
|
|
expect(operation.tags).toContain("chat-channels");
|
|
}
|
|
|
|
const create = spec.paths["/api/companies/{companyId}/chat-endpoints"].post;
|
|
expect(create.responses["201"]).toBeDefined();
|
|
expect(create.requestBody.content["application/json"].schema).toMatchObject(
|
|
{
|
|
type: "object",
|
|
additionalProperties: false,
|
|
properties: {
|
|
provider: {
|
|
type: "string",
|
|
enum: ["slack", "github", "discord", "microsoft-teams", "telegram", "speko", "imessage-photon"],
|
|
},
|
|
assignedAgentId: { type: "string", format: "uuid" },
|
|
},
|
|
required: ["provider", "assignedAgentId"],
|
|
},
|
|
);
|
|
|
|
const endpointResponse =
|
|
spec.paths["/api/chat-endpoints/{endpointId}"].get.responses["200"]
|
|
.content["application/json"].schema;
|
|
expect(endpointResponse).toMatchObject({
|
|
type: "object",
|
|
additionalProperties: false,
|
|
properties: {
|
|
assignedAgentId: { type: "string", format: "uuid" },
|
|
status: {
|
|
type: "string",
|
|
enum: [
|
|
"draft",
|
|
"verifying",
|
|
"active",
|
|
"paused",
|
|
"attention",
|
|
"revoked",
|
|
"archived",
|
|
],
|
|
},
|
|
capabilities: { type: "object", additionalProperties: false },
|
|
setup: { type: "object", additionalProperties: false },
|
|
},
|
|
});
|
|
expect(JSON.stringify(endpointResponse)).not.toContain('"credentials":');
|
|
expect(JSON.stringify(endpointResponse)).not.toContain("privateKey");
|
|
expect(JSON.stringify(endpointResponse)).not.toContain("signingSecret");
|
|
expect(
|
|
endpointResponse.properties.setup.properties.callbacksNeedUpdate,
|
|
).toEqual({ type: "boolean" });
|
|
expect(
|
|
endpointResponse.properties.setup.properties.callbackSurfaces.properties
|
|
.events.properties.status.enum,
|
|
).toEqual(["current", "stale", "unverified"]);
|
|
|
|
const setup = spec.paths["/api/chat-endpoints/{endpointId}/setup"].post;
|
|
const setupResponse = setup.responses["200"].content["application/json"].schema;
|
|
expect((setupResponse.oneOf ?? setupResponse.anyOf)[1].properties.requiredUserAction.properties.kind.enum).toEqual(["enter_credentials"]);
|
|
expect(setup.description).toContain("without changing credentials");
|
|
expect(
|
|
setup.requestBody.content["application/json"].schema.properties.action
|
|
.enum,
|
|
).toEqual([
|
|
"configure",
|
|
"verify",
|
|
"pause",
|
|
"resume",
|
|
"reconnect",
|
|
"remove",
|
|
]);
|
|
expect(setup.description).toContain(
|
|
"Discord: `applicationId`, `guildId`, `botToken`",
|
|
);
|
|
expect(setup.responses["409"]).toBeDefined();
|
|
expect(setup.responses["422"]).toBeDefined();
|
|
expect(setup.responses["502"]).toBeDefined();
|
|
expect(setup.responses["503"]).toBeDefined();
|
|
|
|
const photon = spec.paths["/api/chat-endpoints/{endpointId}/photon/inspect"].post;
|
|
expect(photon.requestBody.content["application/json"].schema.required).toEqual([
|
|
"projectId", "projectSecret",
|
|
]);
|
|
const photonResponse = photon.responses["200"].content["application/json"].schema;
|
|
expect(photonResponse.properties.allocation.enum).toEqual(["dedicated", "shared"]);
|
|
expect(photonResponse.properties.lines.items.additionalProperties).toBe(false);
|
|
expect(JSON.stringify(photonResponse)).not.toMatch(/projectSecret|token/);
|
|
expect(photon.responses["422"]).toBeDefined();
|
|
expect(photon.responses["429"]).toBeDefined();
|
|
expect(photon.responses["502"]).toBeDefined();
|
|
expect(photon.responses["503"]).toBeDefined();
|
|
|
|
const setupSecret =
|
|
spec.paths["/api/chat-endpoints/{endpointId}/setup-secret"].post;
|
|
const secretHandoff = setupSecret.responses["200"].content["application/json"].schema;
|
|
expect(secretHandoff.properties.requiredUserAction.properties.kind.enum).toEqual(["enter_credentials"]);
|
|
expect(secretHandoff.properties).not.toHaveProperty("webhookSecret");
|
|
expect(setupSecret.description).toContain("without rotating or reading");
|
|
expect(
|
|
setupSecret.responses["201"].content["application/json"].schema,
|
|
).toMatchObject({
|
|
type: "object",
|
|
additionalProperties: false,
|
|
required: ["webhookSecret", "credentialRotationId"],
|
|
});
|
|
expect(setupSecret.responses["409"]).toBeDefined();
|
|
expect(setupSecret.responses["422"]).toBeDefined();
|
|
|
|
const resolveAction =
|
|
spec.paths["/api/chat-endpoints/{endpointId}/actions/{actionId}/resolve"]
|
|
.post;
|
|
expect(
|
|
resolveAction.requestBody.content["application/json"].schema.properties
|
|
.action.enum,
|
|
).toEqual(["mark_delivered", "retry_anyway", "cancel"]);
|
|
expect(resolveAction.responses["409"]).toBeDefined();
|
|
expect(resolveAction.responses["422"]).toBeDefined();
|
|
|
|
const activity =
|
|
spec.paths["/api/chat-endpoints/{endpointId}/activity"].get.responses[
|
|
"200"
|
|
].content["application/json"].schema.oneOf[0].items;
|
|
expect(activity.properties.actionType.enum).toEqual([
|
|
"slash_task_start",
|
|
"provider_effect",
|
|
"github_webhook_ingress",
|
|
"slack_session_sync",
|
|
"slack_session_stop",
|
|
]);
|
|
const fileTransfer = activity.properties.fileTransfer;
|
|
expect(fileTransfer).toMatchObject({
|
|
type: "object",
|
|
additionalProperties: false,
|
|
required: ["provider", "phase", "filename", "version"],
|
|
properties: {
|
|
provider: { type: "string", enum: ["microsoft-teams"] },
|
|
version: { type: "integer", minimum: 0, exclusiveMinimum: true },
|
|
},
|
|
});
|
|
expect(Object.keys(fileTransfer.properties).sort()).toEqual([
|
|
"expiresAt",
|
|
"filename",
|
|
"phase",
|
|
"provider",
|
|
"version",
|
|
]);
|
|
expect(fileTransfer.properties.phase.enum).toHaveLength(15);
|
|
const boardSend =
|
|
spec.paths[
|
|
"/api/chat-endpoints/{endpointId}/conversations/{conversationId}/publications"
|
|
].post;
|
|
expect(boardSend.responses["409"]).toBeDefined();
|
|
expect(boardSend.responses["422"]).toBeDefined();
|
|
expect(boardSend.description).toContain(
|
|
"chat_board_send_attachments_already_bound",
|
|
);
|
|
expect(boardSend.description).toContain(
|
|
"Other errors do not establish non-delivery",
|
|
);
|
|
const batchStatus =
|
|
spec.paths[
|
|
"/api/chat-endpoints/{endpointId}/conversations/{conversationId}/publications/{publicationId}/status"
|
|
].get.responses["200"].content["application/json"].schema;
|
|
expect(batchStatus.required).toEqual(
|
|
expect.arrayContaining([
|
|
"publication",
|
|
"parts",
|
|
"total",
|
|
"published",
|
|
"awaitingConsent",
|
|
"declined",
|
|
"expired",
|
|
"cancelled",
|
|
"settled",
|
|
"canDismiss",
|
|
]),
|
|
);
|
|
expect(batchStatus.properties.parts.items.properties.fileTransfer).toEqual(
|
|
fileTransfer,
|
|
);
|
|
expect(batchStatus.properties.publication.properties.state.enum).toContain(
|
|
"awaiting_consent",
|
|
);
|
|
const resolvePublication =
|
|
spec.paths[
|
|
"/api/chat-endpoints/{endpointId}/publications/{publicationId}/resolve"
|
|
].post.requestBody.content["application/json"].schema;
|
|
expect(resolvePublication.properties.fileTransfer).toMatchObject({
|
|
type: "object",
|
|
additionalProperties: false,
|
|
required: ["phase", "version"],
|
|
properties: {
|
|
phase: { enum: fileTransfer.properties.phase.enum },
|
|
version: { type: "integer", minimum: 0, exclusiveMinimum: true },
|
|
},
|
|
});
|
|
expect(JSON.stringify(batchStatus)).not.toMatch(
|
|
/uploadUrl|privateState|tokenSha256|credentialFingerprint/,
|
|
);
|
|
|
|
const replaceResources =
|
|
spec.paths["/api/chat-endpoints/{endpointId}/resources"].put;
|
|
expect(
|
|
replaceResources.requestBody.content["application/json"].schema,
|
|
).toMatchObject({
|
|
type: "object",
|
|
additionalProperties: false,
|
|
required: ["resources"],
|
|
});
|
|
expect(replaceResources.responses["409"]).toBeDefined();
|
|
expect(replaceResources.responses["422"]).toBeDefined();
|
|
|
|
expect(
|
|
spec.paths[
|
|
"/api/chat-endpoints/{endpointId}/principals/{principalId}/link"
|
|
].delete.responses["204"],
|
|
).toBeDefined();
|
|
expect(
|
|
spec.paths[
|
|
"/api/chat-endpoints/{endpointId}/deliveries/{deliveryId}/replay"
|
|
].post.responses["204"],
|
|
).toBeDefined();
|
|
expect(
|
|
spec.paths[
|
|
"/api/chat-endpoints/{endpointId}/publications/{publicationId}/replay"
|
|
].post.responses["204"],
|
|
).toBeDefined();
|
|
|
|
const endpointScopedOperations = operations.filter(
|
|
([, routePath]) =>
|
|
routePath.includes("{endpointId}") ||
|
|
routePath === "/api/issues/{issueId}/chat-binding",
|
|
);
|
|
for (const [method, routePath] of endpointScopedOperations) {
|
|
expect(
|
|
spec.paths[routePath][method].responses["404"],
|
|
`${method.toUpperCase()} ${routePath} preserves the non-member 404 boundary`,
|
|
).toBeDefined();
|
|
}
|
|
|
|
expect(
|
|
spec.paths["/api/chat-webhooks/{publicId}/{provider}"],
|
|
).toBeUndefined();
|
|
});
|
|
|
|
it("documents session-bound voice authority without durable credentials", () => {
|
|
const {spec} = loadSpecRoutes();
|
|
const start = spec.paths["/api/companies/{companyId}/voice-sessions"].post;
|
|
expect(start.security).toEqual([{BoardSessionAuth: []}]);
|
|
expect(start["x-paperclip-authorization"]).toEqual({actor: "board", sessionBound: true});
|
|
expect(start.requestBody.content["application/json"].schema.required).toEqual(expect.arrayContaining(["endpointId", "idempotencyKey"]));
|
|
expect(start.responses["201"]).toBeDefined();
|
|
expect(JSON.stringify(start.responses)).not.toContain("signingSecret");
|
|
expect(spec.paths["/api/voice-webhooks/{publicId}/tools"]).toBeUndefined();
|
|
expect(spec.paths["/api/voice-webhooks/{publicId}/events"]).toBeUndefined();
|
|
const decision=spec.paths["/api/companies/{companyId}/voice-phone/{endpointId}/incoming/{callId}"].post;
|
|
expect(decision.requestBody.content["application/json"].schema.required).toEqual(expect.arrayContaining(["approve", "approvalCode"]));
|
|
});
|
|
|
|
it("documents board-only prompt injection settings and fixed-sample testing", () => {
|
|
const { spec } = loadSpecRoutes();
|
|
const base = "/api/companies/{companyId}/prompt-injection-prevention";
|
|
for (const [method, suffix] of [["get", ""], ["put", ""], ["get", "/models"], ["post", "/test"]]) {
|
|
expect(spec.paths[base + suffix][method]["x-paperclip-authorization"]).toEqual({ actor: "board" });
|
|
expect(spec.paths[base + suffix][method].security).toEqual([{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }]);
|
|
}
|
|
expect(spec.paths[base].put.requestBody.content["application/json"].schema).toMatchObject({
|
|
additionalProperties: false, required: ["enabled", "connectionId", "grantId", "model"],
|
|
});
|
|
expect(spec.paths[base + "/test"].post.requestBody.content["application/json"].schema).toMatchObject({
|
|
type: "object", additionalProperties: false, properties: {},
|
|
});
|
|
});
|
|
|
|
it("documents Tailscale management as instance-admin operations without credential responses", () => {
|
|
const { spec } = loadSpecRoutes();
|
|
const base = "/api/companies/{companyId}/tailscale-connections";
|
|
for (const [path, method] of [[base, "get"], [base, "post"], [base + "/{connectionId}", "delete"],
|
|
[base + "/{connectionId}/devices", "get"], [base + "/{connectionId}/pairing", "post"], ["/api/tools/oauth/tailscale/callback", "get"]]) {
|
|
const operation = spec.paths[path]?.[method];
|
|
expect(operation).toBeDefined();
|
|
expect(operation["x-paperclip-authorization"]).toEqual({ actor: "board", instanceAdmin: true });
|
|
expect(operation.security).toEqual([{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }]);
|
|
expect(operation.responses["403"]).toBeDefined();
|
|
}
|
|
const connection = spec.paths[base].get.responses["200"].content["application/json"].schema.items;
|
|
expect(Object.keys(connection.properties).sort()).toEqual(["companyId", "id", "name", "status"]);
|
|
expect(connection.additionalProperties).toBe(false);
|
|
const start = spec.paths[base].post;
|
|
expect(start.requestBody.content["application/json"].schema).toMatchObject({ additionalProperties: false,
|
|
properties: { name: { minLength: 1, maxLength: 100 }, connectionId: { format: "uuid" } } });
|
|
expect(start.requestBody.content["application/json"].schema.required ?? []).toEqual([]);
|
|
const session = start.responses["201"].content["application/json"].schema;
|
|
expect(session.required).toEqual(["authorizationUrl", "expiresAt"]);
|
|
expect(session.properties.handoff.properties.kind).toEqual({ type: "string", enum: ["paperclip_cloud"] });
|
|
const pairing = spec.paths[base + "/{connectionId}/pairing"].post;
|
|
expect(pairing.requestBody.content["application/json"].schema).toMatchObject({ additionalProperties: false, required: ["deviceId"],
|
|
properties: { deviceId: { minLength: 1, maxLength: 256 }, port: { minimum: 1, maximum: 65535 } } });
|
|
expect(Object.keys(pairing.responses["200"].content["application/json"].schema.properties).sort()).toEqual(["command", "privateKeySecretId", "publicKey"]);
|
|
const callback = spec.paths["/api/tools/oauth/tailscale/callback"].get;
|
|
expect(callback.responses["303"].headers).toMatchObject({ Location: { schema: { type: "string" } }, "Cache-Control": { schema: { enum: ["no-store"] } } });
|
|
expect(callback.parameters).toContainEqual(expect.objectContaining({ in: "query", name: "state", required: true, schema: expect.objectContaining({ maxLength: 128 }) }));
|
|
});
|
|
|
|
it("covers the mounted server routes exactly", () => {
|
|
const {
|
|
routes: actualRoutes,
|
|
excludedRoutes,
|
|
unknownRouteFiles,
|
|
} = loadActualRoutes();
|
|
const { routes: specRoutes } = loadSpecRoutes();
|
|
|
|
const missingInSpec = [...actualRoutes]
|
|
.filter((route) => !specRoutes.has(route))
|
|
.sort();
|
|
const extraInSpec = [...specRoutes]
|
|
.filter(
|
|
(route) =>
|
|
!actualRoutes.has(route) && !specOnlyContractFirstRoutes.has(route),
|
|
)
|
|
.sort();
|
|
|
|
expect({
|
|
unknownRouteFiles,
|
|
missingInSpec,
|
|
extraInSpec,
|
|
excludedRoutes: [...excludedRoutes].sort(),
|
|
}).toEqual({
|
|
unknownRouteFiles: [],
|
|
missingInSpec: [],
|
|
extraInSpec: [],
|
|
excludedRoutes: [...explicitOpenApiOperationCoverageExclusions].sort(),
|
|
});
|
|
});
|
|
|
|
it("documents agent permission grants as Board-only with a strict request", () => {
|
|
const operation = loadSpecRoutes().spec.paths["/api/agents/{id}/permission-grants"].patch;
|
|
expect(operation["x-paperclip-authorization"]).toEqual({ actor: "board" });
|
|
expect(operation.security).toEqual([{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }]);
|
|
expect(operation.requestBody.content["application/json"].schema).toMatchObject({
|
|
additionalProperties: false, required: ["permissionKey", "enabled"],
|
|
properties: { enabled: { type: "boolean" }, permissionKey: { enum: expect.arrayContaining(["commentary:view"]) } },
|
|
});
|
|
});
|
|
|
|
it("documents additive project access as board-only with a strict request", () => {
|
|
const { spec } = loadSpecRoutes();
|
|
const path = spec.paths["/api/agents/{id}/project-access"];
|
|
for (const operation of [path.get, path.post]) {
|
|
expect(operation["x-paperclip-authorization"]).toEqual({ actor: "board" });
|
|
expect(operation.security).toEqual([{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }]);
|
|
expect(operation.responses["200"].content["application/json"].schema.required).toEqual(["projectIds", "canManage"]);
|
|
}
|
|
expect(path.post.requestBody.content["application/json"].schema).toMatchObject({
|
|
additionalProperties: false, required: ["projectIds"],
|
|
properties: { projectIds: { type: "array", items: { type: "string", format: "uuid" } } },
|
|
});
|
|
expect(path.post.responses["409"]).toBeDefined();
|
|
});
|
|
|
|
it("documents the authenticated personal primary-agent contract", () => {
|
|
const { spec } = loadSpecRoutes();
|
|
const path = spec.paths["/api/companies/{companyId}/primary-agent/me"];
|
|
for (const operation of [path.get, path.put]) {
|
|
expect(operation["x-paperclip-authorization"]).toEqual({ actor: "board" });
|
|
expect(operation.security).toEqual([{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }]);
|
|
expect(operation.responses["200"].content["application/json"].schema.required).toEqual([
|
|
"companyId", "userId", "primaryAgentId", "initialized",
|
|
]);
|
|
}
|
|
expect(path.put.requestBody.content["application/json"].schema).toMatchObject({
|
|
additionalProperties: false,
|
|
required: ["primaryAgentId"],
|
|
properties: { primaryAgentId: { type: "string", format: "uuid" } },
|
|
});
|
|
expect(path.put.responses["422"]).toBeDefined();
|
|
});
|
|
|
|
it("documents Muse operator management separately from receiver credentials", () => {
|
|
const { spec } = loadSpecRoutes();
|
|
const base = "/api/companies/{companyId}/agents/{agentId}/muse-binding";
|
|
const operations = [
|
|
["get", "/api/companies/{companyId}/muse-invitations"],
|
|
["post", "/api/companies/{companyId}/muse-invitations"],
|
|
["get", base], ["post", base], ["post", `${base}/verify`],
|
|
["post", `${base}/revoke`], ["post", `${base}/attest-stop`],
|
|
["post", `${base}/attest-detector-cleanup`],
|
|
["get", `${base}/qualification`], ["post", `${base}/qualification`], ["delete", `${base}/qualification`],
|
|
];
|
|
for (const [method, routePath] of operations) {
|
|
const operation = spec.paths[routePath][method];
|
|
expect(operation["x-paperclip-authorization"]).toEqual({ actor: "board" });
|
|
expect(operation.security).toEqual([{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }]);
|
|
expect(operation.responses["403"]).toBeDefined();
|
|
}
|
|
expect(spec.paths[base].post.responses["201"]).toBeDefined();
|
|
expect(spec.paths[base].post.responses["201"].content["application/json"].schema.properties.assetVersion.enum).toEqual([MUSE_ASSET_VERSION]);
|
|
expect(spec.paths[`${base}/revoke`].post.responses["204"]).toBeDefined();
|
|
expect(spec.paths[`${base}/qualification`].delete.responses["204"]).toBeDefined();
|
|
expect(spec.paths[`${base}/qualification`].get.parameters).toEqual(expect.arrayContaining([
|
|
expect.objectContaining({ name: "bindingId", in: "query", required: true }),
|
|
expect.objectContaining({ name: "qualificationId", in: "query", required: true }),
|
|
]));
|
|
for (const route of MUSE_PUBLIC_ROUTES) expect(spec.paths[route.path]).toBeUndefined();
|
|
});
|
|
|
|
it("documents operator Dot invitations and current pairing and event-test fields", () => {
|
|
const { spec } = loadSpecRoutes();
|
|
const invitations = spec.paths["/api/companies/{companyId}/dot-invitations"];
|
|
for (const operation of [invitations.get, invitations.post]) {
|
|
expect(operation["x-paperclip-authorization"]).toEqual({ actor: "board" });
|
|
expect(operation.responses["200"]).toBeDefined();
|
|
}
|
|
expect(invitations.post.requestBody.content["application/json"].schema.additionalProperties).toBe(false);
|
|
const base = "/api/companies/{companyId}/agents/{agentId}/dot-binding";
|
|
expect(spec.paths[base].post.requestBody.content["application/json"].schema.properties.replaceBindingId).toMatchObject({ type: "string", format: "uuid" });
|
|
expect(spec.paths[base + "/event-test"].post.requestBody.content["application/json"].schema.properties.bindingId).toMatchObject({ type: "string", format: "uuid" });
|
|
});
|
|
|
|
it("documents project environment compatibility and creation selection", () => {
|
|
const { spec } = loadSpecRoutes();
|
|
const operation = spec.paths["/api/companies/{companyId}/project-environments"].get;
|
|
expect(operation["x-paperclip-authorization"]).toEqual({ actor: "board_or_agent" });
|
|
expect(operation.responses["403"]).toBeDefined();
|
|
expect(operation.responses["200"].content["application/json"].schema.properties).toHaveProperty("defaultEnvironmentId");
|
|
const creation = spec.paths["/api/companies/{companyId}/projects"].post;
|
|
expect(creation.requestBody.content["application/json"].schema.properties.environmentId).toMatchObject({ type: "string", format: "uuid" });
|
|
expect(creation.requestBody.content["application/json"].schema.properties.expectedStorageProviderPluginId).toMatchObject({ type: "string", nullable: true });
|
|
});
|
|
|
|
it("documents board-only repository discovery and selection", () => {
|
|
const { spec } = loadSpecRoutes();
|
|
const discovery = spec.paths["/api/companies/{companyId}/project-repositories"].get;
|
|
const replacement = spec.paths["/api/projects/{id}/repositories"].put;
|
|
for (const operation of [discovery, replacement]) {
|
|
expect(operation["x-paperclip-authorization"]).toEqual({ actor: "board" });
|
|
expect(operation.security).toEqual([{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }]);
|
|
}
|
|
expect(replacement.requestBody.content["application/json"].schema.required).toContain("repositoryIds");
|
|
expect(replacement.responses["422"]).toBeDefined();
|
|
});
|
|
|
|
it("documents delegated GitHub setup with human identity confirmation and compatible owner-aware registration", () => {
|
|
const { spec } = loadSpecRoutes();
|
|
for (const [suffix, method] of [["draft", "put"], ["setup", "post"], ["identity/start", "post"], ["identity/confirm", "post"]]) {
|
|
const operation = spec.paths[`/api/chat-endpoints/{endpointId}/github/${suffix}`][method];
|
|
expect(operation["x-paperclip-authorization"]).toEqual({ actor: suffix === "identity/confirm" ? "board" : "board_or_agent" });
|
|
expect(operation.security).toEqual([{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }, ...(suffix === "identity/confirm" ? [] : [{ AgentBearerAuth: [] }])]);
|
|
}
|
|
const registration = spec.paths["/api/chat-endpoints/{endpointId}/github/registration"].post;
|
|
const input = registration.requestBody.content["application/json"].schema;
|
|
expect(input.properties.ownerType.enum).toEqual(["personal", "organization"]);
|
|
expect(input.required).not.toContain("ownerType");
|
|
const response = registration.responses["200"].content["application/json"].schema;
|
|
expect(response.oneOf ?? response.anyOf).toHaveLength(2);
|
|
const appImport = spec.paths["/api/chat-endpoints/{endpointId}/github/app"].post;
|
|
expect(appImport.description).toContain("Only a human session");
|
|
const appImportResponse = appImport.responses["200"].content["application/json"].schema;
|
|
expect(appImportResponse.oneOf ?? appImportResponse.anyOf).toHaveLength(2);
|
|
});
|
|
|
|
it("documents GitHub recovery, draft receipts, paged repositories and old review lookups", () => {
|
|
const { spec } = loadSpecRoutes();
|
|
const root = "/api/chat-endpoints/{endpointId}/github/";
|
|
const setup = spec.paths[root + "setup"].post.responses["200"].content["application/json"].schema;
|
|
expect(setup.properties.restartableRegistrationId.format).toBe("uuid");
|
|
const restart = spec.paths[root + "registration/restart"].post;
|
|
expect(restart["x-paperclip-authorization"]).toEqual({ actor: "board_or_agent" });
|
|
const restartInput = restart.requestBody.content["application/json"].schema;
|
|
expect(restartInput.required).toEqual(expect.arrayContaining(["registrationId", "appNotCreated"]));
|
|
expect(restartInput.properties.appNotCreated.enum ?? [restartInput.properties.appNotCreated.const]).toEqual([true]);
|
|
const receipt = spec.paths[root + "draft"].put.responses["200"].content["application/json"].schema;
|
|
expect(receipt.required).toEqual(["saved"]);
|
|
expect(receipt.properties).not.toHaveProperty("state");
|
|
const appInput = spec.paths[root + "app"].post.requestBody.content["application/json"].schema;
|
|
const app = (appInput.oneOf ?? appInput.anyOf).find((variant: { properties?: { appId?: unknown } }) => variant.properties?.appId);
|
|
expect(app.properties.clientId).toBeDefined();
|
|
expect(app.properties.clientSecret).toBeDefined();
|
|
expect(app.required).not.toContain("clientId");
|
|
const page = spec.paths[root + "repositories"].get;
|
|
expect(page.parameters.map((param: { name: string }) => param.name)).toEqual(expect.arrayContaining(["endpointId", "offset", "limit", "search"]));
|
|
expect(page.responses["200"].content["application/json"].schema.properties).toHaveProperty("totalCount");
|
|
expect(spec.paths[root + "repositories/access"].put["x-paperclip-authorization"]).toEqual({ actor: "board_or_agent" });
|
|
const review = spec.paths[root + "reviews/{reviewId}"].get;
|
|
expect(review.parameters.map((param: { name: string }) => param.name)).toEqual(["endpointId", "reviewId"]);
|
|
expect(review.responses["404"]).toBeDefined();
|
|
});
|
|
|
|
it("documents auth and reviewed response-code invariants", () => {
|
|
const { spec } = loadSpecRoutes();
|
|
|
|
expect(spec.paths["/api/openapi.json"].get.security).toEqual([]);
|
|
expect(
|
|
spec.paths["/runtime-tools/github/credentials"].post.security,
|
|
).toEqual([{ RuntimeToolsBearerAuth: [] }]);
|
|
expect(spec.paths["/api/plugins/install"].post.security).toEqual([
|
|
{ BoardSessionAuth: [] },
|
|
{ BoardApiKeyAuth: [] },
|
|
]);
|
|
expect(
|
|
spec.paths["/api/plugins/install"].post["x-paperclip-authorization"],
|
|
).toEqual({
|
|
actor: "board",
|
|
instanceAdmin: true,
|
|
});
|
|
expect(
|
|
spec.paths["/api/execution-workspaces/{id}/reconcile-branch"].post
|
|
.security,
|
|
).toEqual([{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }]);
|
|
expect(
|
|
spec.paths["/api/execution-workspaces/{id}/reconcile-branch"].post[
|
|
"x-paperclip-authorization"
|
|
],
|
|
).toEqual({
|
|
actor: "board",
|
|
});
|
|
expect(
|
|
spec.paths["/api/companies/{companyId}/cost-events"].post.responses[
|
|
"201"
|
|
],
|
|
).toBeDefined();
|
|
expect(
|
|
spec.paths["/api/companies/{companyId}/cost-events"].post.responses[
|
|
"403"
|
|
],
|
|
).toBeDefined();
|
|
expect(
|
|
spec.paths["/api/companies/{companyId}/managed-agent-profiles"].post
|
|
.security,
|
|
).toEqual([{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }]);
|
|
expect(
|
|
spec.paths["/api/companies/{companyId}/remote-agent-profiles"].get
|
|
.security,
|
|
).toEqual([{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }]);
|
|
const remoteAgentProfileBody =
|
|
spec.paths["/api/companies/{companyId}/remote-agent-profiles"].post
|
|
.requestBody.content["application/json"].schema;
|
|
expect(remoteAgentProfileBody.properties.service).toMatchObject({
|
|
type: "string",
|
|
enum: ["aws_bedrock_agentcore_harness"],
|
|
});
|
|
expect(
|
|
remoteAgentProfileBody.properties.credentialSecretId,
|
|
).toBeUndefined();
|
|
expect(
|
|
spec.paths["/api/instance/database-backups"].post.responses["201"],
|
|
).toBeDefined();
|
|
expect(
|
|
spec.paths["/api/invites/{token}/accept"].post.responses["202"],
|
|
).toBeDefined();
|
|
expect(
|
|
spec.paths["/api/board-api-keys"].post.responses["201"],
|
|
).toBeDefined();
|
|
expect(
|
|
spec.paths["/api/companies/import"].post.responses["202"],
|
|
).toBeDefined();
|
|
expect(
|
|
spec.paths["/api/routines/{id}/run"].post.responses["422"],
|
|
).toBeDefined();
|
|
});
|
|
|
|
it("publishes the Claude browser-code grammar and strict setup-token response shapes", () => {
|
|
const { spec } = loadSpecRoutes();
|
|
const base = "/api/companies/{companyId}/setup-token-login-sessions";
|
|
|
|
// The submitted browser code carries the bounded printable-ASCII grammar.
|
|
const codeBody =
|
|
spec.paths[`${base}/{sessionId}/code`].post.requestBody.content[
|
|
"application/json"
|
|
].schema;
|
|
const browserCode = codeBody.properties.browserCode;
|
|
expect(browserCode.minLength).toBe(1);
|
|
expect(browserCode.maxLength).toBe(512);
|
|
expect(typeof browserCode.pattern).toBe("string");
|
|
expect(browserCode.pattern.length).toBeGreaterThan(0);
|
|
|
|
// Every Claude request object forbids an unknown property.
|
|
const startBody =
|
|
spec.paths[base].post.requestBody.content["application/json"].schema;
|
|
expect(startBody.additionalProperties).toBe(false);
|
|
expect(codeBody.additionalProperties).toBe(false);
|
|
|
|
// The four contract-first routes carry typed strict response schemas.
|
|
const responseSchemas: Record<string, Record<string, unknown>> = {
|
|
start:
|
|
spec.paths[base].post.responses["201"].content["application/json"]
|
|
.schema,
|
|
status:
|
|
spec.paths[`${base}/{sessionId}`].get.responses["200"].content[
|
|
"application/json"
|
|
].schema,
|
|
prompt:
|
|
spec.paths[`${base}/{sessionId}/prompt`].get.responses["200"].content[
|
|
"application/json"
|
|
].schema,
|
|
code: spec.paths[`${base}/{sessionId}/code`].post.responses["200"]
|
|
.content["application/json"].schema,
|
|
};
|
|
const forbiddenProperties = ["token", "accountId", "leaseId"];
|
|
for (const [name, schema] of Object.entries(responseSchemas)) {
|
|
expect(schema.type, `${name} response is a typed object`).toBe("object");
|
|
expect(schema.additionalProperties, `${name} response is strict`).toBe(
|
|
false,
|
|
);
|
|
const properties = (schema.properties ?? {}) as Record<string, unknown>;
|
|
expect(
|
|
Object.keys(properties).length,
|
|
`${name} response lists properties`,
|
|
).toBeGreaterThan(0);
|
|
for (const forbidden of forbiddenProperties) {
|
|
expect(
|
|
properties[forbidden],
|
|
`${name} response hides ${forbidden}`,
|
|
).toBeUndefined();
|
|
}
|
|
// No property name looks like a raw prompt secret or a token.
|
|
for (const property of Object.keys(properties)) {
|
|
expect(
|
|
/token|secret|accountId|leaseId/i.test(property),
|
|
`${name}.${property} is not secret-adjacent`,
|
|
).toBe(false);
|
|
}
|
|
}
|
|
|
|
// The status and code routes share the public response; it hides the prompt.
|
|
expect(responseSchemas.status.properties).toEqual(
|
|
responseSchemas.code.properties,
|
|
);
|
|
expect(
|
|
(responseSchemas.status.properties as Record<string, unknown>).prompt,
|
|
).toBeUndefined();
|
|
// The owner start response adds the panel mode and the one-time prompt.
|
|
expect(
|
|
(responseSchemas.start.properties as Record<string, unknown>).panelMode,
|
|
).toBeDefined();
|
|
expect(
|
|
(responseSchemas.start.properties as Record<string, unknown>).prompt,
|
|
).toBeDefined();
|
|
const activeSchema = spec.paths[`${base}/active`].get.responses["200"].content["application/json"].schema;
|
|
expect(activeSchema.properties.agentId).toMatchObject({ type: "string", format: "uuid" });
|
|
expect(activeSchema.required ?? []).not.toContain("agentId");
|
|
expect((responseSchemas.status.properties as Record<string, unknown>).agentId).toBeUndefined();
|
|
// The prompt route returns the authorization URL and the optional transport
|
|
// advisory. The advisory is present on a non-confidential transport, so the
|
|
// client can show a non-blocking disclaimer.
|
|
expect(
|
|
Object.keys(responseSchemas.prompt.properties as Record<string, unknown>),
|
|
).toEqual(["authorizationUrl", "transportAdvisory"]);
|
|
});
|
|
|
|
it("documents the 404 non-member gate on the Claude setup-token cancel route", () => {
|
|
const { spec } = loadSpecRoutes();
|
|
const cancel =
|
|
spec.paths[
|
|
"/api/companies/{companyId}/setup-token-login-sessions/{sessionId}/cancel"
|
|
].post;
|
|
// The 404 is reachable at run time. The company-access gate returns a fixed
|
|
// 404 for a non-member before the cancel logic runs, so the spec declares
|
|
// it. The idempotent cancel still returns 200 for an owner-scoped missing,
|
|
// terminal, or foreign session id.
|
|
const codes = Object.keys(cancel.responses).sort();
|
|
expect(codes).toEqual(["200", "401", "403", "404"]);
|
|
});
|
|
});
|
|
|
|
|
|
describe("heartbeat run ID OpenAPI contract", () => {
|
|
it("publishes the runtime UUID constraint and 400 response on all agent-router run endpoints", async () => {
|
|
const response = await request(createApp()).get("/api/openapi.json");
|
|
expect(response.status).toBe(200);
|
|
const paths = response.body.paths;
|
|
let checked = 0;
|
|
for (const [path, operations] of Object.entries(paths)) {
|
|
if (!path.startsWith("/api/heartbeat-runs/{runId}") || path.endsWith("/issues")) continue;
|
|
for (const operation of Object.values(operations as Record<string, any>)) {
|
|
const parameter = operation.parameters.find((param: { name: string }) => param.name === "runId");
|
|
expect(parameter.schema.pattern).toEqual(expect.any(String));
|
|
const pattern = new RegExp(parameter.schema.pattern);
|
|
for (const id of [
|
|
"aaaaaaaa-aaaa-1aaa-8aaa-aaaaaaaaaaaa",
|
|
"aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
|
|
"AAAAAAAA-AAAA-5AAA-BAAA-AAAAAAAAAAAA",
|
|
]) expect(pattern.test(id), id).toBe(true);
|
|
for (const id of [
|
|
"undefined", "not-a-uuid", " aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa ",
|
|
"aaaaaaaa-aaaa-7aaa-8aaa-aaaaaaaaaaaa", "aaaaaaaa-aaaa-4aaa-0aaa-aaaaaaaaaaaa",
|
|
"aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa\n",
|
|
]) expect(pattern.test(id), JSON.stringify(id)).toBe(false);
|
|
expect(operation.responses["400"]).toBeDefined();
|
|
checked++;
|
|
}
|
|
}
|
|
expect(checked).toBe(12);
|
|
});
|
|
});
|
|
|
|
|
|
it("documents explicit owner removals in the timeline response event enum", () => {
|
|
const spec = buildOpenApiSpec() as any;
|
|
const schema = spec.paths["/api/companies/{companyId}/timeline"].get.responses["200"].content["application/json"].schema;
|
|
expect(schema.properties.events.items.properties.kind.enum).toEqual([
|
|
"created", "commented", "approved", "delegated", "assigned", "unassigned",
|
|
]);
|
|
});
|
|
|
|
it("documents canonical saved-resource links in catalog team install responses", () => {
|
|
const operation = buildOpenApiSpec().paths["/api/companies/{companyId}/teams/catalog/{catalogId}/install"].post;
|
|
expect(operation.description).toContain("resourceLinks");
|
|
const schema = operation.responses[201].content["application/json"].schema;
|
|
expect(schema.required).toContain("resourceLinks");
|
|
expect(schema.properties.resourceLinks.items.properties.kind.enum).toEqual(["agent", "project", "routine"]);
|
|
expect(schema.properties.resourceLinks.items.required).toEqual(["kind", "id", "name", "href"]);
|
|
});
|