diff --git a/README.md b/README.md index 5fa26175..a1003786 100644 --- a/README.md +++ b/README.md @@ -141,13 +141,16 @@ curl -H "Authorization: Bearer $FACTORIZE_ACCESS_TOKEN" \ https://app.factorize.sh/api/v1/flows curl -H "Authorization: Bearer $FACTORIZE_ACCESS_TOKEN" \ - 'https://app.factorize.sh/api/v1/runs?flowId=FLOW_ID&state=running&limit=25' + 'https://app.factorize.sh/api/v1/runs?jobId=JOB_ID&state=running&contextQuery=customer%20impact&limit=25' + +curl -H "Authorization: Bearer $FACTORIZE_ACCESS_TOKEN" \ + https://app.factorize.sh/api/v1/runs/RUN_ID curl -X POST -H "Authorization: Bearer $FACTORIZE_ACCESS_TOKEN" \ https://app.factorize.sh/api/v1/runs/RUN_ID/stop ``` -Flow CRUD is available at `/flows` and `/flows/:id`; supporting collections are `/projects`, `/flow-options`, `/runs`, and `/flow-events`. Run and event collections return `{ "items": [...], "nextCursor": "..." }`; pass `nextCursor` back as the `cursor` query parameter. Errors consistently use `{ "error": { "code": "...", "message": "..." } }`. +Flow CRUD is available at `/flows` and `/flows/:id`; supporting collections are `/projects`, `/flow-options`, `/runs`, and `/flow-events`. Run and event collections return `{ "items": [...], "nextCursor": "..." }`; pass `nextCursor` back as the `cursor` query parameter. Runs can be filtered by `jobId`, `state`, and `contextQuery`; context queries use case-insensitive literal substring matching and matching items contain a bounded `context_excerpt`, never the full context. `GET /runs/:runId` returns the full triggered `context` and its invocation metadata (`source`, parameters, schedule occurrence, claim key, and timestamp). Legacy runs return `null` for `context` and `invocation`. Errors consistently use `{ "error": { "code": "...", "message": "..." } }`. ## MCP clients diff --git a/packages/app/src/flow-schemas.ts b/packages/app/src/flow-schemas.ts index d64beab7..3f75f271 100644 --- a/packages/app/src/flow-schemas.ts +++ b/packages/app/src/flow-schemas.ts @@ -23,6 +23,7 @@ export const flowInputSchema = z.object({ export const flowIdSchema = z.object({ flowId: z.string().min(1) }); export const listRunsSchema = z.object({ jobId: z.string().min(1).optional(), state: runStateSchema.optional(), + contextQuery: z.string().min(1).max(50_000).optional(), limit: z.coerce.number().int().min(1).max(100).default(50), cursor: z.string().min(1).optional(), }); export const runIdSchema = z.object({ runId: z.string().min(1) }); diff --git a/packages/app/src/protected-api.ts b/packages/app/src/protected-api.ts index 1ebc1de8..d233b82e 100644 --- a/packages/app/src/protected-api.ts +++ b/packages/app/src/protected-api.ts @@ -85,8 +85,8 @@ export class ProtectedApiHandler extends WorkerEntrypoint { tool("list_projects", "List Linear projects", z.object({}), () => service.listProjects()); tool("list_flow_options", "List match-rule options", z.object({}), () => service.listFlowOptions()); tool("list_exe_connections", "List safe metadata for saved exe.dev connections. Select a connectionId before creating or updating a flow; API tokens are never returned.", z.object({}), () => service.listExeConnections()); - tool("list_runs", "List and filter job runs", listRunsSchema, (input: any) => service.listRuns(queryOf(input))); - tool("get_run", "Get a run and its current output", runIdSchema, ({ runId }: any) => service.getRun(runId)); + tool("list_runs", "List and filter job runs by job ID, state, and an optional case-insensitive literal substring of the exact triggered context. Context matches include only a bounded excerpt.", listRunsSchema, (input: any) => service.listRuns(queryOf(input))); + tool("get_run", "Get a run with its full triggered context, invocation metadata, execution metadata, output, and activity", runIdSchema, ({ runId }: any) => service.getRun(runId)); tool("list_flow_events", "List webhook activity for a flow", listEventsSchema, (input: any) => service.listFlowEvents(queryOf(input))); tool("stop_run", "Stop an active run", runIdSchema, ({ runId }: any) => service.stopRun(runId)); tool("list_jobs", "List jobs", z.object({}), () => service.listJobs()); diff --git a/packages/app/src/tenant.ts b/packages/app/src/tenant.ts index 42289988..680a2899 100644 --- a/packages/app/src/tenant.ts +++ b/packages/app/src/tenant.ts @@ -568,23 +568,48 @@ export class Tenant extends DurableObject { } private listRuns(url: URL): Response { - const limit = this.pageSize(url), cursor = this.cursor(url), jobId = url.searchParams.get("jobId"), state = url.searchParams.get("state"); - const clauses: string[] = [], args: unknown[] = []; - if (jobId) { clauses.push("pipe_id = ?"); args.push(jobId); } - if (state === "succeeded") { clauses.push("state IN ('succeeded','done')"); } - else if (state === "stopped") { clauses.push("state IN ('stopped','cancelled')"); } - else if (state === "starting") { clauses.push("state IN ('starting','recovering')"); } - else if (state) { clauses.push("state = ?"); args.push(state); } - if (cursor) { clauses.push("(created_at < ? OR (created_at = ? AND id < ?))"); args.push(cursor.at, cursor.at, cursor.id); } - const rows = this.rows(`SELECT id, pipe_id AS job_id, issue_id, issue_url, agent_name, workspace_name, agent_kind, state, provider, execution_backend_kind AS backend_kind, execution_capabilities AS capabilities, destination_url, created_at, updated_at FROM runs ${clauses.length ? `WHERE ${clauses.join(" AND ")}` : ""} ORDER BY created_at DESC, id DESC LIMIT ?`, ...args, limit + 1); + const limit = this.pageSize(url), cursor = this.cursor(url), jobId = url.searchParams.get("jobId"), state = url.searchParams.get("state"), contextQuery = url.searchParams.get("contextQuery"); + const clauses: string[] = [], selectArgs: unknown[] = [], args: unknown[] = []; + if (jobId) { clauses.push("r.pipe_id = ?"); args.push(jobId); } + if (state === "succeeded") { clauses.push("r.state IN ('succeeded','done')"); } + else if (state === "stopped") { clauses.push("r.state IN ('stopped','cancelled')"); } + else if (state === "starting") { clauses.push("r.state IN ('starting','recovering')"); } + else if (state) { clauses.push("r.state = ?"); args.push(state); } + if (contextQuery) { clauses.push("instr(lower(i.context), lower(?)) > 0"); args.push(contextQuery); selectArgs.push(contextQuery, contextQuery); } + if (cursor) { clauses.push("(r.created_at < ? OR (r.created_at = ? AND r.id < ?))"); args.push(cursor.at, cursor.at, cursor.id); } + const excerpt = contextQuery + ? ", instr(lower(i.context), lower(?)) AS context_match_index, length(i.context) AS context_length, substr(i.context, max(instr(lower(i.context), lower(?)) - 80, 1), 200) AS context_excerpt" + : ", NULL AS context_excerpt"; + const rows = this.rows(`SELECT r.id, r.pipe_id AS job_id, r.issue_id, r.issue_url, r.agent_name, r.workspace_name, r.agent_kind, r.state, r.provider, r.execution_backend_kind AS backend_kind, r.execution_capabilities AS capabilities, r.destination_url, r.created_at, r.updated_at${excerpt} FROM runs r LEFT JOIN job_runs jr ON jr.id = r.id LEFT JOIN invocations i ON i.id = jr.invocation_id ${clauses.length ? `WHERE ${clauses.join(" AND ")}` : ""} ORDER BY r.created_at DESC, r.id DESC LIMIT ?`, ...selectArgs, ...args, limit + 1); const hasMore = rows.length > limit, items = rows.slice(0, limit); - for (const item of items) this.presentExecution(item); + for (const item of items) { + if (contextQuery) { + const matchIndex = Number(item.context_match_index), contextLength = Number(item.context_length), excerptValue = String(item.context_excerpt ?? ""); + const excerptStart = Math.max(matchIndex - 80, 1); + item.context_excerpt = `${excerptStart > 1 ? "…" : ""}${excerptValue}${excerptStart - 1 + excerptValue.length < contextLength ? "…" : ""}`; + delete item.context_match_index; + delete item.context_length; + } + this.presentExecution(item); + } return json({ items, nextCursor: hasMore ? this.nextCursor(items.at(-1), "created_at") : null }); } private async getRun(runId: string): Promise { - const run = this.one("SELECT id, pipe_id AS job_id, issue_id, issue_url, agent_name, workspace_name, agent_kind, state, provider, execution_backend_kind AS backend_kind, execution_capabilities AS capabilities, destination_url, result, exec_status, exec_exit_code, recovery_last_action, created_at, updated_at FROM runs WHERE id = ?", runId); + const run = this.one(`SELECT r.id, r.pipe_id AS job_id, r.issue_id, r.issue_url, r.agent_name, r.workspace_name, r.agent_kind, r.state, r.provider, r.execution_backend_kind AS backend_kind, r.execution_capabilities AS capabilities, r.destination_url, r.result, r.exec_status, r.exec_exit_code, r.recovery_last_action, r.created_at, r.updated_at, + i.id AS invocation_id, i.job_id AS invocation_job_id, i.source AS invocation_source, i.claim_key AS invocation_claim_key, i.context, i.parameters AS invocation_parameters, i.occurrence AS invocation_occurrence, i.created_at AS invocation_created_at + FROM runs r LEFT JOIN job_runs jr ON jr.id = r.id LEFT JOIN invocations i ON i.id = jr.invocation_id WHERE r.id = ?`, runId); if (!run) return new Response("Not found", { status: 404 }); + if (run.invocation_id) { + let parameters: unknown = {}, occurrence: unknown = null; + try { parameters = JSON.parse(String(run.invocation_parameters || "{}")); } catch { /* Persisted invocation remains readable if metadata is malformed. */ } + try { occurrence = run.invocation_occurrence == null ? null : JSON.parse(String(run.invocation_occurrence)); } catch { /* Persisted invocation remains readable if metadata is malformed. */ } + run.invocation = { id: run.invocation_id, job_id: run.invocation_job_id, source: run.invocation_source, claim_key: run.invocation_claim_key, parameters, occurrence, created_at: run.invocation_created_at }; + } else { + run.context = null; + run.invocation = null; + } + for (const key of ["invocation_id", "invocation_job_id", "invocation_source", "invocation_claim_key", "invocation_parameters", "invocation_occurrence", "invocation_created_at"]) delete run[key]; if (run.state !== "ignored" && typeof run.result === "string" && run.result) run.result = await decrypt(run.result, this.env.CREDENTIAL_ENCRYPTION_KEY); run.activity = this.rows("SELECT action, detail, created_at FROM run_activity WHERE run_id = ? ORDER BY created_at, id", runId); this.presentExecution(run); diff --git a/packages/app/test/flow-service.test.ts b/packages/app/test/flow-service.test.ts index a38810c5..47f26b7f 100644 --- a/packages/app/test/flow-service.test.ts +++ b/packages/app/test/flow-service.test.ts @@ -60,8 +60,9 @@ describe("shared API schemas", () => { }); it("bounds pagination and run states", () => { - expect(listRunsSchema.parse({ limit: "100", state: "running" })).toMatchObject({ limit: 100, state: "running" }); + expect(listRunsSchema.parse({ limit: "100", state: "running", contextQuery: "literal.*text" })).toMatchObject({ limit: 100, state: "running", contextQuery: "literal.*text" }); expect(() => listRunsSchema.parse({ limit: "101" })).toThrow(); + expect(() => listRunsSchema.parse({ contextQuery: "" })).toThrow(); }); it("validates job configuration and reserved invocation context", () => { diff --git a/packages/app/test/run-inspection.test.ts b/packages/app/test/run-inspection.test.ts new file mode 100644 index 00000000..a9c72b72 --- /dev/null +++ b/packages/app/test/run-inspection.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it, vi } from "vitest"; + +vi.mock("cloudflare:workers", () => ({ DurableObject: class {} })); + +import { Tenant } from "../src/tenant"; + +function tenantWithRows(rows: (query: string, ...params: unknown[]) => Record[]): Tenant { + const tenant = Object.create(Tenant.prototype) as Tenant; + (tenant as any).rows = rows; + return tenant; +} + +describe("run invocation inspection", () => { + it("combines literal context search with run filters and returns only a bounded excerpt", async () => { + let statement = ""; + let bindings: unknown[] = []; + const tenant = tenantWithRows((query, ...params) => { + statement = query; + bindings = params; + return [{ + id: "run-1", job_id: "job-1", state: "running", backend_kind: "amp", capabilities: "[]", + created_at: "2026-09-16T12:00:00Z", updated_at: "2026-09-16T12:01:00Z", + context_match_index: 100, context_length: 400, context_excerpt: "matching context window", + }]; + }); + + const response = (tenant as any).listRuns(new URL("https://tenant/v1/runs?jobId=job-1&state=running&contextQuery=%25_%5B.%2A%5D&limit=10")) as Response; + const body = await response.json() as any; + + expect(statement).toContain("instr(lower(i.context), lower(?)) > 0"); + expect(statement).not.toContain("LIKE"); + expect(bindings).toEqual(["%_[.*]", "%_[.*]", "job-1", "running", "%_[.*]", 11]); + expect(body.items[0]).toMatchObject({ state: "running", context_excerpt: "…matching context window…" }); + expect(body.items[0]).not.toHaveProperty("context"); + expect(body.items[0]).not.toHaveProperty("context_match_index"); + }); + + it("returns full canonical invocation metadata and nulls for a legacy run", async () => { + const canonical = tenantWithRows((query) => query.includes("FROM runs r") ? [{ + id: "run-1", job_id: "job-1", state: "queued", backend_kind: "amp", capabilities: "[]", result: null, + context: "Exact Triggered Context", invocation_id: "inv-1", invocation_job_id: "job-1", invocation_source: "schedule", + invocation_claim_key: "schedule:occurrence-1", invocation_parameters: '{"region":"west"}', + invocation_occurrence: '{"occurredAt":"2026-09-16T12:00:00Z"}', invocation_created_at: "2026-09-16T12:00:01Z", + }] : []); + const canonicalBody = await ((canonical as any).getRun("run-1") as Promise).then((response: Response) => response.json()) as any; + expect(canonicalBody.context).toBe("Exact Triggered Context"); + expect(canonicalBody.invocation).toEqual({ + id: "inv-1", job_id: "job-1", source: "schedule", claim_key: "schedule:occurrence-1", + parameters: { region: "west" }, occurrence: { occurredAt: "2026-09-16T12:00:00Z" }, created_at: "2026-09-16T12:00:01Z", + }); + + const legacy = tenantWithRows((query) => query.includes("FROM runs r") ? [{ id: "legacy-1", job_id: "flow-1", state: "done", backend_kind: "exe-herdr", capabilities: "[]", result: null }] : []); + const legacyBody = await ((legacy as any).getRun("legacy-1") as Promise).then((response: Response) => response.json()) as any; + expect(legacyBody).toMatchObject({ context: null, invocation: null }); + }); +});