Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1030,6 +1030,30 @@ export interface paths {
patch?: never;
trace?: never;
};
"/api/v1/projects/{projectId}/graph": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* Get a project's workflow graph
* @description Returns every job in the project and configured lifecycle, idle, manual invocation permission, and external webhook source connections. Connections are derived from executable trigger configuration and current permission grants. Only safe webhook provider and resource metadata is returned.
*
* Requires the projects:read scope.
*
* Accepts a scoped bearer token or interactive owner session.
*/
get: operations["get_api_v1_projects_projectId_graph"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/skills": {
parameters: {
query?: never;
Expand Down Expand Up @@ -4553,6 +4577,57 @@ export interface operations {
503: components["responses"]["Error503"];
};
};
get_api_v1_projects_projectId_graph: {
parameters: {
query?: never;
header?: never;
path: {
projectId: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Complete project graph */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
nodes: {
id: string;
/** @enum {string} */
type: "job" | "webhook";
label: string;
/** @enum {string} */
jobKind?: "Agent" | "Code";
enabled?: boolean;
provider?: string;
resource?: string;
}[];
edges: {
id: string;
source: string;
target: string;
label: string;
/** @enum {string} */
kind: "lifecycle" | "idle" | "manual" | "webhook";
enabled: boolean;
}[];
};
};
};
400: components["responses"]["Error400"];
401: components["responses"]["Error401"];
403: components["responses"]["Error403"];
404: components["responses"]["Error404"];
409: components["responses"]["Error409"];
429: components["responses"]["Error429"];
500: components["responses"]["Error500"];
503: components["responses"]["Error503"];
};
};
get_api_v1_skills: {
parameters: {
query?: {
Expand Down
2 changes: 2 additions & 0 deletions packages/api/src/api-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { triggerAvailabilityResponse, namedOption, providerOptions, githubInstal
import { runSummaryResponse, runPageResponse, runStatusResponse, fullRunResponse, revisionTracePage, revisionTraceQuery, runtimeContextResponse } from "./run-read-contracts";
import { jobPageQuery, jobSummaryPage, jobSelectorPage, jobResponse, jobUpdateInput } from "./job-contracts";
import { projectInput, projectListQuery, projectResponse } from "./project-contracts";
import { projectGraphResponse } from "./project-graph-contracts";
import { z } from "zod";
import type { ApiService } from "./flow-service";
import {
Expand Down Expand Up @@ -660,6 +661,7 @@ export const API_ROUTES: RouteContract[] = [
),
route("POST", "/api/v1/projects", "flows:write", { summary: "Create project", responses: { "201": { description: "Created", content: { "application/json": { schema: jsonSchema(projectResponse, "output") } } } } }, (service, { body }) => service.createProject(body), { body: projectInput }),
route("GET", "/api/v1/projects/{projectId}", "flows:read", { summary: "Get project", responses: { "200": { description: "Project", content: { "application/json": { schema: jsonSchema(projectResponse, "output") } } } } }, (service, { params }) => service.getProject(params.projectId)),
route("GET", "/api/v1/projects/{projectId}/graph", "flows:read", { summary: "Get a project's workflow graph", description: "Returns every job in the project and configured lifecycle, idle, manual invocation permission, and external webhook source connections. Connections are derived from executable trigger configuration and current permission grants. Only safe webhook provider and resource metadata is returned.", responses: { "200": { description: "Complete project graph", content: { "application/json": { schema: jsonSchema(projectGraphResponse, "output") } } } } }, (service, { params }) => service.getProjectGraph(params.projectId)),
route("PUT", "/api/v1/projects/{projectId}", "flows:write", { summary: "Update project", responses: { "200": { description: "Updated", content: { "application/json": { schema: jsonSchema(projectResponse, "output") } } } } }, (service, { params, body }) => service.updateProject(params.projectId, body), { body: projectInput }),
route("DELETE", "/api/v1/projects/{projectId}", "flows:write", { summary: "Delete empty project", responses: { "200": { description: "Deleted" } } }, (service, { params }) => service.deleteProject(params.projectId)),
route("GET", "/api/v1/skills", "skills:read", { summary: "Search global skills", responses: { "200": { description: "Skills", content: { "application/json": { schema: jsonSchema(skillPage, "output") } } } } }, (service, { query }) => service.listSkills(query), { query: skillQuery }),
Expand Down
30 changes: 30 additions & 0 deletions packages/api/src/flow-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,36 @@ export class ApiService {
async getJob(jobId: string) { await this.authorize("jobs:read"); const job = await this.jobs().getJob(jobId); if (!job) throw new ServiceError(404, "not_found", "Job not found"); return this.presentJob(job); }
async listProjects(options?: { limit?: number; sort?: "name" | "updated" }) { await this.authorize("projects:read"); return this.projects().list(options); }
async getProject(projectId: string) { await this.authorize("projects:read"); const project = await this.projects().get(projectId); if (!project) throw new ServiceError(404, "not_found", "Project not found"); return project; }
async getProjectGraph(projectId: string) {
await this.authorize("projects:read");
if (!await this.projects().get(projectId)) throw new ServiceError(404, "not_found", "Project not found");
const db = databaseFor(this.env), tenantId = this.auth.tenantId;
const jobs = await db.pool.query<any>(`SELECT j.id,j.name,j.enabled,j.execution_config,
COALESCE(jsonb_agg(jsonb_build_object('id',t.id,'kind',t.kind,'enabled',t.enabled,'config',CASE
WHEN t.kind='jobLifecycle' THEN jsonb_build_object('sourceJobIds',t.config->'sourceJobIds','sourceJobId',t.config->'sourceJobId','states',t.config->'states')
WHEN t.kind='jobIdle' THEN jsonb_build_object('sourceJobIds',t.config->'sourceJobIds')
WHEN t.kind='webhook' THEN jsonb_build_object('provider',t.config->>'provider','projectId',t.config->>'projectId','listId',t.config->>'listId','repositoryId',t.config->>'repositoryId','event',t.config->>'event','integrationId',t.config->>'integrationId')
ELSE '{}'::jsonb END) ORDER BY t.position,t.id) FILTER (WHERE t.id IS NOT NULL),'[]'::jsonb) triggers
FROM app.jobs j LEFT JOIN app.triggers t ON t.tenant_id=j.tenant_id AND t.job_id=j.id AND t.removed_at IS NULL
WHERE j.tenant_id=$1 AND j.project_id=$2 GROUP BY j.tenant_id,j.id ORDER BY j.id`, [tenantId, projectId]);
const ids = new Set<string>(jobs.rows.map(row => row.id));
const nodes: any[] = jobs.rows.map(row => ({ id: row.id, type: "job", label: row.name, jobKind: row.execution_config?.executionType === "code" ? "Code" : "Agent", enabled: row.enabled }));
const edges: any[] = [];
for (const job of jobs.rows) for (const trigger of job.triggers) {
if (trigger.kind === "jobLifecycle") for (const source of trigger.config?.sourceJobIds ?? (trigger.config?.sourceJobId ? [trigger.config.sourceJobId] : [])) if (ids.has(source)) edges.push({ id: `${trigger.id}:${source}:${job.id}`, source, target: job.id, label: (trigger.config?.states ?? []).map((state: string) => state === "succeeded" ? "Succeeded" : state === "failed" ? "Failed" : state === "stopped" ? "Stopped" : "Edited").join(", "), kind: "lifecycle", enabled: Boolean(job.enabled && trigger.enabled) });
if (trigger.kind === "jobIdle") for (const source of trigger.config?.sourceJobIds ?? []) if (ids.has(source)) edges.push({ id: `${trigger.id}:${source}:${job.id}`, source, target: job.id, label: "Idle", kind: "idle", enabled: Boolean(job.enabled && trigger.enabled) });
if (trigger.kind === "webhook") {
const config = trigger.config ?? {}, provider = String(config.provider ?? "webhook").slice(0, 50);
const resource = (provider === "linear" ? String(config.projectId ?? "Project") : provider === "clickup" ? String(config.listId ?? "List") : provider === "github" ? String(config.repositoryId ? `Repository ${config.repositoryId}` : config.event ?? "Repository") : provider === "cloudflareTail" ? "Tail" : "External source").slice(0, 120);
const source = `webhook:${provider}:${resource}`;
if (!nodes.some(node => node.id === source)) nodes.push({ id: source, type: "webhook", label: `${provider} · ${resource}`, provider, resource });
edges.push({ id: `${trigger.id}:${source}:${job.id}`, source, target: job.id, label: `${provider} · ${resource}`, kind: "webhook", enabled: Boolean(job.enabled && trigger.enabled) });
}
}
const grants = await db.pool.query<any>(`SELECT p.source_job_id,p.destination_job_id FROM app.manual_invocation_permissions p JOIN app.jobs s ON s.tenant_id=p.tenant_id AND s.id=p.source_job_id JOIN app.jobs d ON d.tenant_id=p.tenant_id AND d.id=p.destination_job_id WHERE p.tenant_id=$1 AND s.project_id=$2 AND d.project_id=$2 ORDER BY p.source_job_id,p.destination_job_id`, [tenantId, projectId]);
for (const grant of grants.rows) edges.push({ id: `manual:${grant.source_job_id}:${grant.destination_job_id}`, source: grant.source_job_id, target: grant.destination_job_id, label: "Manual", kind: "manual", enabled: Boolean(jobs.rows.find(row => row.id === grant.source_job_id)?.enabled && jobs.rows.find(row => row.id === grant.destination_job_id)?.enabled) });
return { nodes, edges };
}
async createProject(input: { name: string; description?: string }) { await this.authorize("projects:write"); try { return await this.projects().create(input.name, input.description); } catch (error: any) { if (error?.code === "23505") throw new ServiceError(409, "conflict", "A project with this name already exists"); throw error; } }
async updateProject(projectId: string, input: { name: string; description?: string }) { await this.authorize("projects:write"); const result = await this.projects().update(projectId, input.name, input.description); if (!result) throw new ServiceError(404, "not_found", "Project not found"); return result; }
async deleteProject(projectId: string) { await this.authorize("projects:write"); const result = await this.projects().remove(projectId); if (result === "missing") throw new ServiceError(404, "not_found", "Project not found"); if (result === "nonempty") throw new ServiceError(409, "conflict", "Move or delete the project's jobs before deleting it"); return { id: projectId, deleted: true }; }
Expand Down
6 changes: 6 additions & 0 deletions packages/api/src/project-graph-contracts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { z } from "zod";

export const projectGraphResponse = z.object({
nodes: z.array(z.object({ id: z.string(), type: z.enum(["job", "webhook"]), label: z.string(), jobKind: z.enum(["Agent", "Code"]).optional(), enabled: z.boolean().optional(), provider: z.string().optional(), resource: z.string().optional() })),
edges: z.array(z.object({ id: z.string(), source: z.string(), target: z.string(), label: z.string(), kind: z.enum(["lifecycle", "idle", "manual", "webhook"]), enabled: z.boolean() })),
});
6 changes: 6 additions & 0 deletions packages/api/test/api-contract.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@ describe("versioned API contract", () => {
expect(post?.scope).toBe("jobs:write"); expect(get?.scope).toBe("jobs:read");
expect(openapi.paths["/api/v1/vm-image-verifications"].post.requestBody).toBeDefined();
});
it("publishes the authorized complete project graph operation", () => {
const operation = API_ROUTES.find(route => route.method === "GET" && route.path === "/api/v1/projects/{projectId}/graph");
expect(operation?.scope).toBe("projects:read");
expect(operation?.parameters.shape.projectId).toBeDefined();
expect(openapi.paths["/api/v1/projects/{projectId}/graph"].get["x-required-scope"]).toBe("projects:read");
});
it("has full bidirectional method/path equality with the executable catalog", () => {
const documented = Object.entries(openapi.paths).flatMap(([path, item]) =>
Object.keys(item as object)
Expand Down
62 changes: 62 additions & 0 deletions packages/api/test/project-graph.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { ApiService } from "../src/flow-service";
import { projectGraphResponse } from "../src/project-graph-contracts";

vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {} }));
afterEach(() => vi.restoreAllMocks());

describe("project graph", () => {
const tenantId = "00000000-0000-4000-8000-000000000001", projectId = "00000000-0000-4000-8000-000000000002";
const source = "00000000-0000-4000-8000-000000000003", destination = "00000000-0000-4000-8000-000000000004", other = "00000000-0000-4000-8000-000000000005";
it("returns every project job and derives stable configured edges without secret config", async () => {
const jobs = [
{ id: source, name: "Build", enabled: true, execution_config: { agentKind: "codex" }, triggers: [] },
{ id: destination, name: "Deploy", enabled: false, execution_config: { executionType: "code", agentKind: "codex" }, triggers: [
{ id: "lifecycle", kind: "jobLifecycle", enabled: true, config: { sourceJobIds: [source, other], states: ["failed", "stopped", "edited"] } },
{ id: "idle", kind: "jobIdle", enabled: false, config: { sourceJobIds: [source] } },
{ id: "manual", kind: "manual", enabled: true, config: {} },
{ id: "schedule", kind: "schedule", enabled: true, config: {} },
{ id: "hook", kind: "webhook", enabled: true, config: { provider: "github", repositoryId: 42, signingSecret: "never-return-this" } },
] },
];
const query = vi.fn(async (sql: string, values: unknown[]) => {
expect(values[0]).toBe(tenantId);
if (sql.includes("FROM app.jobs j LEFT JOIN app.triggers")) return { rows: jobs, rowCount: 2 };
if (sql.includes("FROM app.manual_invocation_permissions")) return { rows: [{ source_job_id: source, destination_job_id: destination }], rowCount: 1 };
throw new Error("Unexpected query");
});
const service = new ApiService({ DATABASE: { pool: { query } } } as any, { tenantId, userId: "owner", sessionVersion: 1, scopes: ["projects:read"] } as any);
vi.spyOn(service as any, "authorize").mockResolvedValue(undefined);
vi.spyOn(service as any, "projects").mockReturnValue({ get: async (id: string) => id === projectId ? { id } : null });
const graph = await service.getProjectGraph(projectId);
expect(projectGraphResponse.safeParse(graph).success).toBe(true);
expect(graph.nodes).toHaveLength(3);
expect(graph.nodes.find(node => node.id === destination)).toMatchObject({ jobKind: "Code", enabled: false });
expect(graph.edges.map(edge => [edge.kind, edge.label, edge.enabled])).toEqual([
["lifecycle", "Failed, Stopped, Edited", false], ["idle", "Idle", false],
["webhook", "github · Repository 42", false], ["manual", "Manual", false],
]);
expect(graph.edges.some(edge => edge.source === other)).toBe(false);
expect(JSON.stringify(graph)).not.toContain("never-return-this");
expect(query.mock.calls[0][0]).not.toContain("'config',t.config");
expect(query).toHaveBeenCalledTimes(2);
});
it("rejects missing or cross-tenant projects before reading jobs", async () => {
const query = vi.fn();
const service = new ApiService({ DATABASE: { pool: { query } } } as any, { tenantId, userId: "owner", sessionVersion: 1, scopes: ["projects:read"] } as any);
vi.spyOn(service as any, "authorize").mockResolvedValue(undefined);
vi.spyOn(service as any, "projects").mockReturnValue({ get: async (_id: string) => null });
await expect(service.getProjectGraph(projectId)).rejects.toMatchObject({ status: 404 });
expect(query).not.toHaveBeenCalled();
});
it("includes jobs beyond the regular list page without a graph limit", async () => {
const allJobs = Array.from({ length: 205 }, (_, index) => ({ id: `job-${index}`, name: `Job ${index}`, enabled: true, execution_config: {}, triggers: [] }));
const query = vi.fn(async (sql: string) => sql.includes("FROM app.jobs j LEFT JOIN app.triggers") ? { rows: allJobs, rowCount: allJobs.length } : { rows: [], rowCount: 0 });
const service = new ApiService({ DATABASE: { pool: { query } } } as any, { tenantId, userId: "owner", sessionVersion: 1, scopes: ["projects:read"] } as any);
vi.spyOn(service as any, "authorize").mockResolvedValue(undefined);
vi.spyOn(service as any, "projects").mockReturnValue({ get: async (_id: string) => ({ id: projectId }) });
const graph = await service.getProjectGraph(projectId);
expect(graph.nodes).toHaveLength(205);
expect(query.mock.calls[0][0]).not.toMatch(/\bLIMIT\b/i);
});
});
Loading
Loading