From 00c2c144fc83928288749548c6bacfa52111968a Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Tue, 9 Jun 2026 02:05:40 -0700 Subject: [PATCH 001/210] feat: DAG-based post-processing + taxonomy handler MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refactor post-processing from single-handler to DAG orchestration: Phase 1 - Handler Dispatcher: - Add HandlerDispatcher with DAG topology from services collection - Scheduler REST endpoints: POST /notify/run-terminal, /handler-complete - Workers notify scheduler instead of direct queue enqueue (fallback kept) - Remove triggerReportGeneration (reports now DAG node via pp-report) - DB migrations: services → handler entries, run.handlerStatus field Phase 2 - Taxonomy Handler: - Zod schema for 3-layer taxonomy (scorecard, behavior, actions) - taxonomy-handler worker with Copilot SDK + multi-turn validation loop - Docker-compose service with SCHEDULER_URL wiring DAG structure: pp-atif → pp-taxonomy → pp-report Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- AGENTS.md | 2 + ENV_VARIABLES.md | 36 ++ apps/scheduler/src/handler-dispatcher.ts | 295 +++++++++++++++ apps/scheduler/src/index.ts | 34 +- apps/scheduler/src/notify-routes.test.ts | 149 ++++++++ apps/scheduler/src/notify-routes.ts | 150 ++++++++ .../post-processor/src/post-processor.ts | 72 ++-- apps/workers/taxonomy/Dockerfile | 19 + apps/workers/taxonomy/package.json | 23 ++ apps/workers/taxonomy/src/index.ts | 30 ++ apps/workers/taxonomy/src/prompt.ts | 88 +++++ .../taxonomy/src/taxonomy-queue-processor.ts | 336 ++++++++++++++++++ apps/workers/taxonomy/src/tools.ts | 156 ++++++++ apps/workers/taxonomy/tsconfig.json | 8 + docker-compose.yml | 40 ++- docs/architecture/db-migrations.md | 3 + docs/architecture/overview.md | 2 + docs/architecture/post-processing.md | 45 ++- .../src/check-migrations.test.ts | 85 +---- .../018-migrate-services-to-handler-dag.ts | 96 +++++ .../019-add-handler-status-index.ts | 72 ++++ .../migrations/020-backfill-handler-status.ts | 76 ++++ .../db-migrations/src/required-migrations.ts | 3 + packages/shared/src/index.ts | 1 + .../shared/src/queue/queue-processor.test.ts | 15 +- packages/shared/src/queue/queue-processor.ts | 76 ++-- packages/shared/src/schemas/index.ts | 1 + packages/shared/src/schemas/taxonomy.test.ts | 180 ++++++++++ packages/shared/src/schemas/taxonomy.ts | 104 ++++++ packages/shared/src/types/types.ts | 28 +- pnpm-lock.yaml | 25 ++ 31 files changed, 2066 insertions(+), 184 deletions(-) create mode 100644 apps/scheduler/src/handler-dispatcher.ts create mode 100644 apps/scheduler/src/notify-routes.test.ts create mode 100644 apps/scheduler/src/notify-routes.ts create mode 100644 apps/workers/taxonomy/Dockerfile create mode 100644 apps/workers/taxonomy/package.json create mode 100644 apps/workers/taxonomy/src/index.ts create mode 100644 apps/workers/taxonomy/src/prompt.ts create mode 100644 apps/workers/taxonomy/src/taxonomy-queue-processor.ts create mode 100644 apps/workers/taxonomy/src/tools.ts create mode 100644 apps/workers/taxonomy/tsconfig.json create mode 100644 packages/db-migrations/src/migrations/018-migrate-services-to-handler-dag.ts create mode 100644 packages/db-migrations/src/migrations/019-add-handler-status-index.ts create mode 100644 packages/db-migrations/src/migrations/020-backfill-handler-status.ts create mode 100644 packages/shared/src/schemas/taxonomy.test.ts create mode 100644 packages/shared/src/schemas/taxonomy.ts diff --git a/AGENTS.md b/AGENTS.md index de77cbeba..419fb8e6a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,6 +19,7 @@ apps/ coder-acp-copilot/ # GitHub Copilot worker (ACP SDK) coder-acp-claude-code/ # Claude Code worker (ACP SDK) report-generator/ # Post-run report generation + taxonomy/ # Post-run taxonomy generation model-scanners/ # Feature detection for Copilot and Anthropic models version-checkers/ # Poll for new agent/tool releases key-updaters/ # GitHub auth cookie management for VS Code Web @@ -53,6 +54,7 @@ Each worker implements the same queue-processor interface but adapts a different | `coder-acp-copilot` | GitHub Copilot | ACP SDK v0.14.1 | | `coder-acp-claude-code` | Claude Code | ACP SDK v0.13.1 | | `report-generator` | — | Copilot SDK | +| `taxonomy` | — | Copilot SDK | Workers consume tasks from Azure Storage Queues (named `queue-`) and write results to MongoDB and Blob Storage. Each has its own Dockerfile and docker-compose profile. diff --git a/ENV_VARIABLES.md b/ENV_VARIABLES.md index 9259bf048..5044d6c53 100644 --- a/ENV_VARIABLES.md +++ b/ENV_VARIABLES.md @@ -277,6 +277,32 @@ Timeout for the Copilot SDK session used by the report-generator worker. If the Git commit hash embedded in reporter metadata. Automatically set during CI/CD builds. Used to track which version of the report-generator produced a given report. +## Taxonomy Handler Configuration + +### AZURE_STORAGE_QUEUE_TAXONOMY +**Default:** `pp-taxonomy-queue` +**Type:** string + +Azure Storage Queue name for taxonomy-generation jobs. The scheduler enqueues `{ type: "taxonomy", requestId, runId }` messages here after the `pp-atif` dependency completes, and the taxonomy worker polls this queue. + +### TAXONOMY_MODEL +**Default:** `gpt-4.1` +**Type:** string + +The LLM model used by the taxonomy worker (via the Copilot SDK) to generate structured taxonomy JSON from run metadata and ATIF trajectories. + +### SCOPE_MT_API_URL +**Default:** `http://localhost:3001` (local), `http://api:80` (Docker) +**Type:** URL string + +Base URL of the Scope API. The taxonomy worker calls this to fetch the request document and active run state through its Copilot tools. + +### SESSION_TIMEOUT_MS +**Default:** `300000` (5 minutes) +**Type:** integer (milliseconds) + +Timeout for the Copilot SDK session used by the taxonomy worker. If the model does not finish generating a valid taxonomy JSON document within this window, the worker marks `run.handlerStatus.pp-taxonomy` as failed. + ## Scheduler Configuration ### SCHEDULER_POLL_INTERVAL_MS @@ -297,6 +323,16 @@ How often the post-processor dispatcher polls for completed runs needing post-pr Azure Storage Queue name used by both the scheduler (to enqueue post-processing work) and the post-processor worker (to dequeue). Must match between the two services. +### SCHEDULER_URL +**Default:** (not set) +**Type:** URL string + +Optional base URL for the scheduler's HTTP notification endpoints. When set, coder workers call `POST /notify/run-terminal` after a run reaches a terminal state, and post-processing handlers call `POST /notify/handler-complete` after a handler finishes. If unset, workers fall back to the legacy direct post-processor queue enqueue path and the scheduler's polling loop catches up. + +- **Docker Compose:** `http://scheduler:8080` +- **Kubernetes:** `http://scheduler-service.scoped.svc.cluster.local:8080` +- **Local dev:** Leave unset to rely on legacy queue fallback unless you are also running the scheduler locally + ## Worker Configuration ### SCOPE_RUN_HEARTBEAT_STALE_MS diff --git a/apps/scheduler/src/handler-dispatcher.ts b/apps/scheduler/src/handler-dispatcher.ts new file mode 100644 index 000000000..2c4f1b99f --- /dev/null +++ b/apps/scheduler/src/handler-dispatcher.ts @@ -0,0 +1,295 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { Collection, Db } from "mongodb"; +import { QueueClient } from "@azure/storage-queue"; +import type { RequestDocument, HandlerServiceDocument, HandlerRunStatus } from "shared"; +import { DependencyGraph } from "shared"; +import type { NotifyHandler } from "./notify-routes.js"; + +/** + * HandlerDispatcher — DAG-aware post-processing orchestrator. + * + * Reads handler topology from the `services` collection (type: "post-process-handler"), + * builds a DependencyGraph, and dispatches handlers whose dependencies are satisfied. + * + * Two trigger paths: + * 1. `onRunTerminal` — a coder worker signals run completion. Dispatches root handlers. + * 2. `onHandlerComplete` — a handler signals completion. Dispatches downstream handlers. + * + * Also runs a poll safety net to catch missed notifications. + */ +export class HandlerDispatcher implements NotifyHandler { + private interval: ReturnType | null = null; + private dispatching = false; + private queueClients = new Map(); + + constructor( + private readonly collection: Collection, + private readonly db: Db, + private readonly createQueueClient: (queueName: string) => QueueClient, + private readonly pollIntervalMs: number = 30_000, + private readonly batchSize: number = 30, + ) {} + + start(): void { + if (this.interval) return; + this.interval = setInterval(() => this.pollDispatch(), this.pollIntervalMs); + void this.pollDispatch(); + } + + async stop(): Promise { + if (this.interval) { + clearInterval(this.interval); + this.interval = null; + } + const deadline = Date.now() + 5_000; + while (this.dispatching && Date.now() < deadline) { + await new Promise((r) => setTimeout(r, 100)); + } + } + + // ── NotifyHandler implementation ──────────────────────────────────── + + async onRunTerminal(requestId: string, runId: string): Promise { + console.log(`[HandlerDispatcher] Notify: run-terminal ${requestId} (run=${runId})`); + const handlers = await this.loadHandlers(); + if (handlers.length === 0) return; + + const graph = this.buildGraph(handlers); + const roots = handlers.filter((h) => !h.dependsOn || h.dependsOn.length === 0); + + for (const handler of roots) { + await this.dispatchIfEligible(requestId, runId, handler, graph, handlers); + } + } + + async onHandlerComplete( + requestId: string, + runId: string, + handlerId: string, + status: "done" | "failed", + ): Promise { + console.log( + `[HandlerDispatcher] Notify: handler-complete ${handlerId} for ${requestId} (status=${status})`, + ); + + // Update the handler status on the run document + await this.collection.updateOne( + { _id: requestId } as any, + { + $set: { + [`run.handlerStatus.${handlerId}.status`]: status, + [`run.handlerStatus.${handlerId}.updatedAt`]: new Date(), + }, + } as any, + ); + + if (status === "failed") { + // Don't dispatch downstream on failure + return; + } + + // Find and dispatch eligible downstream handlers + const handlers = await this.loadHandlers(); + if (handlers.length === 0) return; + + const graph = this.buildGraph(handlers); + const descendants = graph.getDescendants(handlerId); + + // Only check immediate children (not all descendants) + const children = handlers.filter( + (h) => h.dependsOn?.includes(handlerId) && descendants.has(h._id), + ); + + for (const child of children) { + await this.dispatchIfEligible(requestId, runId, child, graph, handlers); + } + } + + // ── Poll safety net ───────────────────────────────────────────────── + + private async pollDispatch(): Promise { + if (this.dispatching) return; + this.dispatching = true; + try { + const handlers = await this.loadHandlers(); + if (handlers.length === 0) return; + + const graph = this.buildGraph(handlers); + + for (const handler of handlers) { + // Find runs that need this handler dispatched + for (let i = 0; i < this.batchSize; i++) { + const filter = this.buildDispatchFilter(handler, handlers, graph); + if (!filter) break; + + const claimed = await this.collection.findOneAndUpdate( + filter as any, + { + $set: { + [`run.handlerStatus.${handler._id}.status`]: "queued", + [`run.handlerStatus.${handler._id}.updatedAt`]: new Date(), + }, + } as any, + { sort: { updatedAt: -1 }, returnDocument: "after" }, + ); + + if (!claimed) break; + + await this.enqueueToHandler(handler, claimed._id, (claimed as any).run?._id); + console.log(`[HandlerDispatcher] Poll-dispatched ${handler._id} for ${claimed._id}`); + } + } + } catch (err) { + console.error("[HandlerDispatcher] Error during poll dispatch:", err); + } finally { + this.dispatching = false; + } + } + + // ── Dispatch logic ────────────────────────────────────────────────── + + private async dispatchIfEligible( + requestId: string, + _runId: string, + handler: HandlerServiceDocument, + graph: DependencyGraph, + allHandlers: HandlerServiceDocument[], + ): Promise { + // Check if all dependencies are satisfied for this request + const doc = await this.collection.findOne({ _id: requestId } as any); + if (!doc?.run || doc.run.status !== "done") return; + + const handlerStatus = (doc.run as any).handlerStatus as + | Record + | undefined; + + // Check dependencies are all "done" + if (handler.dependsOn && handler.dependsOn.length > 0) { + for (const depId of handler.dependsOn) { + const depStatus = handlerStatus?.[depId]?.status; + if (depStatus !== "done") return; // Dependency not satisfied + } + } + + // Check this handler hasn't already been dispatched + const currentStatus = handlerStatus?.[handler._id]?.status; + if (currentStatus === "queued" || currentStatus === "processing" || currentStatus === "done") { + return; + } + + // Check version — skip if already at current version + const currentVersion = handlerStatus?.[handler._id]?.version; + if (currentVersion !== undefined && currentVersion >= handler.version && !handler.autoBackfill) { + return; + } + + // Atomic claim + const claimed = await this.collection.findOneAndUpdate( + { + _id: requestId, + "run.status": "done", + [`run.handlerStatus.${handler._id}.status`]: { $nin: ["queued", "processing"] }, + } as any, + { + $set: { + [`run.handlerStatus.${handler._id}.status`]: "queued", + [`run.handlerStatus.${handler._id}.updatedAt`]: new Date(), + }, + } as any, + { returnDocument: "after" }, + ); + + if (!claimed) return; + + await this.enqueueToHandler(handler, requestId, (claimed as any).run?._id); + console.log(`[HandlerDispatcher] Dispatched ${handler._id} for ${requestId}`); + } + + // ── Helpers ───────────────────────────────────────────────────────── + + private buildDispatchFilter( + handler: HandlerServiceDocument, + allHandlers: HandlerServiceDocument[], + _graph: DependencyGraph, + ): Record | null { + const filter: Record = { + "run.status": "done", + deletedAt: { $exists: false }, + [`run.handlerStatus.${handler._id}.status`]: { $nin: ["queued", "processing", "done"] }, + }; + + // All dependencies must be "done" + if (handler.dependsOn && handler.dependsOn.length > 0) { + for (const depId of handler.dependsOn) { + filter[`run.handlerStatus.${depId}.status`] = "done"; + } + } + + // Backfill: version check + if (handler.autoBackfill) { + filter.$or = [ + { [`run.handlerStatus.${handler._id}.version`]: { $exists: false } }, + { [`run.handlerStatus.${handler._id}.version`]: { $lt: handler.version } }, + ]; + } else { + // Only dispatch if never processed + filter[`run.handlerStatus.${handler._id}.version`] = { $exists: false }; + } + + return filter; + } + + private async enqueueToHandler( + handler: HandlerServiceDocument, + requestId: string, + runId: string, + ): Promise { + const queueClient = await this.getOrCreateQueueClient(handler.queue); + const message = Buffer.from( + JSON.stringify({ + type: handler.selector, + requestId, + runId, + }), + ).toString("base64"); + + try { + await queueClient.sendMessage(message); + } catch (err) { + // Roll back status on queue failure + await this.collection.updateOne( + { _id: requestId } as any, + { $unset: { [`run.handlerStatus.${handler._id}.status`]: "" } } as any, + ); + console.error( + `[HandlerDispatcher] Queue send failed for ${handler._id}/${requestId}, rolled back:`, + err, + ); + } + } + + private async getOrCreateQueueClient(queueName: string): Promise { + let client = this.queueClients.get(queueName); + if (!client) { + client = this.createQueueClient(queueName); + await client.createIfNotExists(); + this.queueClients.set(queueName, client); + } + return client; + } + + private async loadHandlers(): Promise { + const docs = await this.db + .collection("services") + .find({ type: "post-process-handler" }) + .toArray(); + return docs as unknown as HandlerServiceDocument[]; + } + + private buildGraph(handlers: HandlerServiceDocument[]): DependencyGraph { + const nodes = handlers.map((h) => ({ id: h._id, dependsOn: h.dependsOn })); + return new DependencyGraph(nodes); + } +} diff --git a/apps/scheduler/src/index.ts b/apps/scheduler/src/index.ts index c3ed6f991..dce1509fe 100644 --- a/apps/scheduler/src/index.ts +++ b/apps/scheduler/src/index.ts @@ -2,12 +2,13 @@ // Licensed under the MIT License. import "dotenv/config"; -import http from "node:http"; import { MongoClient } from "mongodb"; import { QueueClient } from "@azure/storage-queue"; import { DefaultAzureCredential } from "@azure/identity"; import { RequestScheduler, WorkerTypeConfig } from "./request-scheduler.js"; import { PostProcessorDispatcher } from "./post-processor-dispatcher.js"; +import { HandlerDispatcher } from "./handler-dispatcher.js"; +import { createHttpServer, type NotifyHandler } from "./notify-routes.js"; import type { RequestDocument } from "shared"; // ── Configuration ──────────────────────────────────────────────────── @@ -77,16 +78,6 @@ function createQueueClient(queueName: string): QueueClient { return new QueueClient(queueUrl, credential); } -// ── Health Check Server ────────────────────────────────────────────── - -function createHealthServer(): http.Server { - const server = http.createServer((_req, res) => { - res.writeHead(200, { "Content-Type": "application/json" }); - res.end(JSON.stringify({ status: "ok", service: "scheduler" })); - }); - return server; -} - // ── Main ───────────────────────────────────────────────────────────── async function main(): Promise { @@ -145,10 +136,20 @@ async function main(): Promise { postProcessorDispatcher.start(); console.log("[Scheduler] Post-processor dispatch loop started"); - // Start health check server - const healthServer = createHealthServer(); - healthServer.listen(HEALTH_PORT, () => { - console.log(`[Scheduler] Health check listening on :${HEALTH_PORT}`); + // Start the DAG-aware handler dispatcher (replaces legacy PostProcessorDispatcher) + const handlerDispatcher = new HandlerDispatcher( + collection, + db, + createQueueClient, + ppPollIntervalMs, + ); + handlerDispatcher.start(); + console.log("[Scheduler] Handler dispatcher (DAG) started"); + + // Wire notify handler to the HandlerDispatcher + const httpServer = createHttpServer(handlerDispatcher); + httpServer.listen(HEALTH_PORT, () => { + console.log(`[Scheduler] HTTP server listening on :${HEALTH_PORT}`); }); // Graceful shutdown @@ -156,7 +157,8 @@ async function main(): Promise { console.log("[Scheduler] Shutting down..."); await scheduler.stop(); await postProcessorDispatcher.stop(); - healthServer.close(); + await handlerDispatcher.stop(); + httpServer.close(); await mongoClient.close(); console.log("[Scheduler] Shutdown complete"); process.exit(0); diff --git a/apps/scheduler/src/notify-routes.test.ts b/apps/scheduler/src/notify-routes.test.ts new file mode 100644 index 000000000..552f03243 --- /dev/null +++ b/apps/scheduler/src/notify-routes.test.ts @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import type { AddressInfo } from "node:net"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { createHttpServer, type NotifyHandler } from "./notify-routes.js"; + +async function startServer(handler: NotifyHandler): Promise<{ server: ReturnType; baseUrl: string }> { + const server = createHttpServer(handler); + + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", () => resolve()); + }); + + const address = server.address(); + if (!address || typeof address === "string") { + throw new Error("Server did not bind to an address"); + } + + return { + server, + baseUrl: `http://127.0.0.1:${(address as AddressInfo).port}`, + }; +} + +async function stopServer(server: ReturnType): Promise { + await new Promise((resolve, reject) => { + server.close((error) => { + if (error) { + reject(error); + return; + } + resolve(); + }); + }); +} + +describe("createHttpServer", () => { + const servers: Array> = []; + + afterEach(async () => { + while (servers.length > 0) { + const server = servers.pop(); + if (server) { + await stopServer(server); + } + } + }); + + it("returns 200 for the health endpoint", async () => { + const handler: NotifyHandler = { + onRunTerminal: vi.fn().mockResolvedValue(undefined), + onHandlerComplete: vi.fn().mockResolvedValue(undefined), + }; + const { server, baseUrl } = await startServer(handler); + servers.push(server); + + const response = await fetch(`${baseUrl}/health`); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ status: "ok", service: "scheduler" }); + }); + + it("calls onRunTerminal for valid run-terminal notifications", async () => { + const handler: NotifyHandler = { + onRunTerminal: vi.fn().mockResolvedValue(undefined), + onHandlerComplete: vi.fn().mockResolvedValue(undefined), + }; + const { server, baseUrl } = await startServer(handler); + servers.push(server); + + const response = await fetch(`${baseUrl}/notify/run-terminal`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ requestId: "req-1", runId: "run-1" }), + }); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ ok: true }); + expect(handler.onRunTerminal).toHaveBeenCalledWith("req-1", "run-1"); + expect(handler.onHandlerComplete).not.toHaveBeenCalled(); + }); + + it("calls onHandlerComplete for valid handler-complete notifications", async () => { + const handler: NotifyHandler = { + onRunTerminal: vi.fn().mockResolvedValue(undefined), + onHandlerComplete: vi.fn().mockResolvedValue(undefined), + }; + const { server, baseUrl } = await startServer(handler); + servers.push(server); + + const response = await fetch(`${baseUrl}/notify/handler-complete`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + requestId: "req-1", + runId: "run-1", + handlerId: "atif", + status: "done", + }), + }); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ ok: true }); + expect(handler.onHandlerComplete).toHaveBeenCalledWith("req-1", "run-1", "atif", "done"); + expect(handler.onRunTerminal).not.toHaveBeenCalled(); + }); + + it("returns 400 when required fields are missing", async () => { + const handler: NotifyHandler = { + onRunTerminal: vi.fn().mockResolvedValue(undefined), + onHandlerComplete: vi.fn().mockResolvedValue(undefined), + }; + const { server, baseUrl } = await startServer(handler); + servers.push(server); + + const response = await fetch(`${baseUrl}/notify/handler-complete`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ requestId: "req-1", runId: "run-1", status: "done" }), + }); + + expect(response.status).toBe(400); + expect(await response.json()).toEqual({ + error: "requestId, runId, handlerId, and status (done|failed) are required", + }); + expect(handler.onRunTerminal).not.toHaveBeenCalled(); + expect(handler.onHandlerComplete).not.toHaveBeenCalled(); + }); + + it("returns 404 for unknown routes", async () => { + const handler: NotifyHandler = { + onRunTerminal: vi.fn().mockResolvedValue(undefined), + onHandlerComplete: vi.fn().mockResolvedValue(undefined), + }; + const { server, baseUrl } = await startServer(handler); + servers.push(server); + + const response = await fetch(`${baseUrl}/notify/unknown`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({}), + }); + + expect(response.status).toBe(404); + expect(await response.json()).toEqual({ error: "Not found" }); + }); +}); diff --git a/apps/scheduler/src/notify-routes.ts b/apps/scheduler/src/notify-routes.ts new file mode 100644 index 000000000..445945d2d --- /dev/null +++ b/apps/scheduler/src/notify-routes.ts @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import http from "node:http"; + +export interface NotifyHandler { + onRunTerminal(requestId: string, runId: string): Promise; + onHandlerComplete( + requestId: string, + runId: string, + handlerId: string, + status: "done" | "failed", + ): Promise; +} + +interface RunTerminalRequest { + requestId: string; + runId: string; +} + +interface HandlerCompleteRequest { + requestId: string; + runId: string; + handlerId: string; + status: "done" | "failed"; +} + +function sendJson(res: http.ServerResponse, statusCode: number, body: object): void { + res.writeHead(statusCode, { "Content-Type": "application/json" }); + res.end(JSON.stringify(body)); +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null; +} + +function isNonEmptyString(value: unknown): value is string { + return typeof value === "string" && value.trim().length > 0; +} + +function parseRunTerminalRequest(body: unknown): RunTerminalRequest | null { + if (!isRecord(body)) { + return null; + } + + if (!isNonEmptyString(body.requestId) || !isNonEmptyString(body.runId)) { + return null; + } + + return { + requestId: body.requestId, + runId: body.runId, + }; +} + +function parseHandlerCompleteRequest(body: unknown): HandlerCompleteRequest | null { + if (!isRecord(body)) { + return null; + } + + if ( + !isNonEmptyString(body.requestId) || + !isNonEmptyString(body.runId) || + !isNonEmptyString(body.handlerId) || + (body.status !== "done" && body.status !== "failed") + ) { + return null; + } + + return { + requestId: body.requestId, + runId: body.runId, + handlerId: body.handlerId, + status: body.status, + }; +} + +async function readJsonBody(req: http.IncomingMessage): Promise { + const chunks: Buffer[] = []; + + for await (const chunk of req) { + chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk); + } + + const rawBody = Buffer.concat(chunks).toString("utf-8").trim(); + if (rawBody.length === 0) { + throw new Error("Request body is required"); + } + + return JSON.parse(rawBody) as unknown; +} + +export function createHttpServer(handler: NotifyHandler): http.Server { + return http.createServer(async (req, res) => { + const method = req.method ?? "GET"; + const url = new URL(req.url ?? "/", "http://localhost"); + + try { + if (method === "GET" && url.pathname === "/health") { + sendJson(res, 200, { status: "ok", service: "scheduler" }); + return; + } + + if (method === "POST" && url.pathname === "/notify/run-terminal") { + const parsedBody = parseRunTerminalRequest(await readJsonBody(req)); + if (!parsedBody) { + sendJson(res, 400, { error: "requestId and runId are required" }); + return; + } + + await handler.onRunTerminal(parsedBody.requestId, parsedBody.runId); + sendJson(res, 200, { ok: true }); + return; + } + + if (method === "POST" && url.pathname === "/notify/handler-complete") { + const parsedBody = parseHandlerCompleteRequest(await readJsonBody(req)); + if (!parsedBody) { + sendJson(res, 400, { + error: "requestId, runId, handlerId, and status (done|failed) are required", + }); + return; + } + + await handler.onHandlerComplete( + parsedBody.requestId, + parsedBody.runId, + parsedBody.handlerId, + parsedBody.status, + ); + sendJson(res, 200, { ok: true }); + return; + } + } catch (error) { + const message = error instanceof Error ? error.message : "Internal server error"; + const statusCode = + message === "Request body is required" || error instanceof SyntaxError ? 400 : 500; + + sendJson(res, statusCode, { + error: + statusCode === 400 + ? "Invalid JSON request body" + : "Internal server error", + }); + return; + } + + sendJson(res, 404, { error: "Not found" }); + }); +} diff --git a/apps/workers/post-processor/src/post-processor.ts b/apps/workers/post-processor/src/post-processor.ts index 2ffeab0b6..4b1b6e847 100644 --- a/apps/workers/post-processor/src/post-processor.ts +++ b/apps/workers/post-processor/src/post-processor.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. import type { DequeuedMessageItem } from "@azure/storage-queue"; -import { BaseQueueProcessor, BlobStorage, Retry, type BaseQueueProcessorConfig, type LogEvent, type VisibilityHeartbeat } from "shared"; +import { BaseQueueProcessor, BlobStorage, type BaseQueueProcessorConfig, type LogEvent, type VisibilityHeartbeat } from "shared"; import { POST_PROCESSOR_VERSION } from "./version.js"; import type { PostProcessHandler, PostProcessorMessage, HandlerContext } from "./types.js"; @@ -86,35 +86,45 @@ export class PostProcessor extends BaseQueueProcessor { await handler.process(msg, ctx); - // Stamp version and status on success + // Stamp version and status on success (legacy fields + new handlerStatus) + const handlerId = `pp-${msg.type}`; // e.g., "pp-atif" await this.collection.updateOne( { _id: doc._id } as any, { $set: { "run.postProcessorVersion": POST_PROCESSOR_VERSION, "run.postProcessorStatus": "done", + [`run.handlerStatus.${handlerId}.status`]: "done", + [`run.handlerStatus.${handlerId}.version`]: POST_PROCESSOR_VERSION, + [`run.handlerStatus.${handlerId}.updatedAt`]: new Date(), }, } as any, ); await log("info", `Post-processing complete (v${POST_PROCESSOR_VERSION})`); - // Trigger report generation now that enrichment is done (best-effort) - try { - await this.triggerReportGeneration(doc._id, log); - } catch (error) { - await log("warn", `Failed to trigger report generation after retries: ${error}`); - } + // Notify the scheduler that this handler is done (best-effort) + await this.notifyHandlerComplete(doc._id, doc.run?._id ?? "", handlerId, "done"); } catch (err) { const errMsg = err instanceof Error ? err.message : String(err); await log("error", `Handler '${msg.type}' failed: ${errMsg}`); // Mark as failed so scheduler doesn't immediately re-dispatch + const handlerId = `pp-${msg.type}`; await this.collection.updateOne( { _id: doc._id } as any, - { $set: { "run.postProcessorStatus": "failed" } } as any, + { + $set: { + "run.postProcessorStatus": "failed", + [`run.handlerStatus.${handlerId}.status`]: "failed", + [`run.handlerStatus.${handlerId}.updatedAt`]: new Date(), + }, + } as any, ); + // Notify scheduler of failure (best-effort — don't dispatch downstream) + await this.notifyHandlerComplete(doc._id, doc.run?._id ?? "", handlerId, "failed"); + throw err; } @@ -124,27 +134,31 @@ export class PostProcessor extends BaseQueueProcessor { } /** - * Trigger report generation via REST API. - * Called after post-processing succeeds so reports can use enriched data. + * Notify the scheduler that a handler completed (or failed). + * Best-effort — the scheduler's poll safety net will catch up if this fails. */ - @Retry({ maxRetries: 3, baseDelayMs: 1000, isRetryable: () => true }) - private async triggerReportGeneration(requestId: string, log: (level: LogEvent["level"], message: string) => Promise): Promise { - if (!this.apiBaseUrl) return; - - const response = await fetch(`${this.apiBaseUrl}/api/v1/reports/trigger`, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ requestId }), - }); - if (response.ok) { - const result = await response.json() as { triggered: number }; - await log("info", `Triggered report generation: ${result.triggered} report(s) created`); - return; - } - if (response.status >= 400 && response.status < 500) { - await log("warn", `Failed to trigger report generation (${response.status}), not retrying`); - return; + private async notifyHandlerComplete( + requestId: string, + runId: string, + handlerId: string, + status: "done" | "failed", + ): Promise { + const schedulerUrl = process.env.SCHEDULER_URL; + if (!schedulerUrl) return; + + try { + const response = await fetch(`${schedulerUrl}/notify/handler-complete`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ requestId, runId, handlerId, status }), + }); + if (response.ok) { + console.log(`[post-processor] Notified scheduler: ${handlerId} ${status} for ${requestId}`); + } else { + console.warn(`[post-processor] Scheduler notify failed: ${response.status}`); + } + } catch (err) { + console.warn(`[post-processor] Scheduler notify error for ${handlerId}/${requestId}:`, err); } - throw new Error(`Report trigger returned ${response.status} ${response.statusText}`); } } diff --git a/apps/workers/taxonomy/Dockerfile b/apps/workers/taxonomy/Dockerfile new file mode 100644 index 000000000..9e0792411 --- /dev/null +++ b/apps/workers/taxonomy/Dockerfile @@ -0,0 +1,19 @@ +FROM node:22-alpine AS builder +WORKDIR /app +COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./ +COPY packages/shared/package.json packages/shared/ +COPY apps/workers/taxonomy/package.json apps/workers/taxonomy/ +RUN corepack enable && pnpm install --frozen-lockfile +COPY packages/shared packages/shared +COPY apps/workers/taxonomy apps/workers/taxonomy +RUN pnpm --filter shared build && pnpm --filter taxonomy-handler build + +FROM node:22-alpine +WORKDIR /app +COPY --from=builder /app/node_modules ./node_modules +COPY --from=builder /app/packages/shared/dist ./packages/shared/dist +COPY --from=builder /app/packages/shared/package.json ./packages/shared/ +COPY --from=builder /app/apps/workers/taxonomy/dist ./apps/workers/taxonomy/dist +COPY --from=builder /app/apps/workers/taxonomy/package.json ./apps/workers/taxonomy/ +WORKDIR /app/apps/workers/taxonomy +CMD ["node", "dist/index.js"] diff --git a/apps/workers/taxonomy/package.json b/apps/workers/taxonomy/package.json new file mode 100644 index 000000000..aacbfc4f1 --- /dev/null +++ b/apps/workers/taxonomy/package.json @@ -0,0 +1,23 @@ +{ + "name": "taxonomy-handler", + "version": "1.0.0", + "type": "module", + "main": "dist/index.js", + "scripts": { + "build": "tsc", + "dev": "tsx watch src/index.ts", + "start": "node dist/index.js", + "lint": "eslint src/" + }, + "dependencies": { + "shared": "workspace:*", + "@azure/storage-queue": "^12.25.0", + "@github/copilot-sdk": "^0.1.17", + "dotenv": "^16.4.5" + }, + "devDependencies": { + "@types/node": "^22.7.0", + "tsx": "^4.19.0", + "typescript": "^5.6.2" + } +} diff --git a/apps/workers/taxonomy/src/index.ts b/apps/workers/taxonomy/src/index.ts new file mode 100644 index 000000000..2ee1a8118 --- /dev/null +++ b/apps/workers/taxonomy/src/index.ts @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import "dotenv/config"; +import { TaxonomyQueueProcessor, type TaxonomyQueueProcessorConfig } from "./taxonomy-queue-processor.js"; + +const config: TaxonomyQueueProcessorConfig = { + mongoUri: process.env.MONGO_CONNECTION_STRING || process.env.AZURE_COSMOS_CONNECTION_STRING || "mongodb://localhost:27017", + mongoDatabase: process.env.MONGO_DATABASE || "requests-db", + mongoCollection: "requests", + storageAccountName: process.env.AZURE_STORAGE_ACCOUNT_NAME || "devstoreaccount1", + storageConnectionString: process.env.STORAGE_CONNECTION_STRING || process.env.AZURE_STORAGE_CONNECTION_STRING || undefined, + queueName: process.env.AZURE_STORAGE_QUEUE_TAXONOMY || "pp-taxonomy-queue", + batchSize: Number(process.env.BATCH_SIZE) || 1, + pollIntervalMs: Number(process.env.POLL_INTERVAL_MS) || 5000, + redisHost: process.env.REDIS_HOST || "localhost", + redisPort: Number(process.env.REDIS_PORT) || 6379, + redisPassword: process.env.REDIS_PASSWORD || "", + taxonomyModel: process.env.TAXONOMY_MODEL || "gpt-4.1", + apiBaseUrl: process.env.SCOPE_MT_API_URL || "http://localhost:3001", + sessionTimeoutMs: Number(process.env.SESSION_TIMEOUT_MS) || 5 * 60 * 1000, + schedulerUrl: process.env.SCHEDULER_URL, + tokenManagerUrl: process.env.TOKEN_MANAGER_URL, +}; + +const processor = new TaxonomyQueueProcessor(config); +processor.start().catch((err) => { + console.error("[taxonomy-handler] Fatal error:", err); + process.exit(1); +}); diff --git a/apps/workers/taxonomy/src/prompt.ts b/apps/workers/taxonomy/src/prompt.ts new file mode 100644 index 000000000..47ea28e4d --- /dev/null +++ b/apps/workers/taxonomy/src/prompt.ts @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +export const TAXONOMY_SYSTEM_PROMPT = `You generate benchmark taxonomy documents for completed Scope runs. + +Your job is to inspect the run metadata and ATIF trajectories, then return a taxonomy JSON document that conforms exactly to the taxonomy Zod schema enforced by the worker. + +Required JSON shape: +{ + "meta": { + "generatedAt": "ISO-8601 datetime with offset", + "schemaVersion": "string", + "runId": "string", + "requestId": "string" + }, + "scorecard": { + "summary": "string", + "profileResults": [ + { + "profileId": "string", + "select": "best|median|worst", + "taskOutcome": "success|partial|failure", + "overallScore": 0-100, + "dimensions": [ + { + "name": "string", + "score": 0-100, + "rationale": "string", + "evidence": ["string"] + } + ] + } + ], + "crossProfileInsights": ["string"] + }, + "behaviorAnalysis": { + "patterns": [ + { + "id": "string", + "category": "strength|weakness|inconsistency|regression", + "title": "string", + "description": "string", + "frequency": 0-1, + "impact": "critical|high|medium|low", + "evidence": [ + { + "runId": "string", + "iteration": 0-or-greater integer, + "excerpt": "string" + } + ] + } + ], + "agentPersonality": { + "communicationStyle": "string", + "problemSolvingApproach": "string", + "errorRecoveryBehavior": "string" + } + }, + "actionList": { + "fix": [actionItem], + "improve": [actionItem], + "investigate": [actionItem] + } +} + +Each actionItem must include: +- id +- title +- priority: critical|high|medium|low +- description +- ownership: agent-team|platform-team|prompt-engineer|scenario-author +- relatedPatterns: string[] +- suggestedApproach + +Output rules: +- Return raw JSON only. +- Do not wrap the JSON in markdown fences. +- Do not include commentary before or after the JSON. +- Every field must be valid for the schema. +- Preserve the 3-layer structure: scorecard, behaviorAnalysis, actionList. +- If a value is unknown, use the schema-compatible empty/null/default value rather than inventing facts. + +Use the available tools to gather evidence before answering: +- get_run_data for the request, scenario, run, turns, and criteria outcomes. +- get_atif_trajectory for ATIF evidence from individual iterations. + +Ground every classification in the actual run evidence. Prefer precise, stable labels over verbose prose. If validation feedback is provided later in the conversation, correct the JSON and return a full replacement document.`; diff --git a/apps/workers/taxonomy/src/taxonomy-queue-processor.ts b/apps/workers/taxonomy/src/taxonomy-queue-processor.ts new file mode 100644 index 000000000..db2c7f7e3 --- /dev/null +++ b/apps/workers/taxonomy/src/taxonomy-queue-processor.ts @@ -0,0 +1,336 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { DequeuedMessageItem } from "@azure/storage-queue"; +import { CopilotClient, SessionEvent } from "@github/copilot-sdk"; +import { + BaseQueueProcessor, + BlobStorage, + type BaseQueueProcessorConfig, + type LogEvent, + type RequestDocument, + taxonomySchema, + TokenManagerClient, + type TaxonomyDocument, + type VisibilityHeartbeat, + withRetry, +} from "shared"; +import { TAXONOMY_SYSTEM_PROMPT } from "./prompt.js"; +import { createTaxonomyTools } from "./tools.js"; + +const HANDLER_ID = "pp-taxonomy"; +const HANDLER_VERSION = 1; +const DEFAULT_SESSION_TIMEOUT_MS = 5 * 60 * 1000; +const DELTA_LOG_INTERVAL = 2_000; + +interface TaxonomyQueueMessage { + type: "taxonomy"; + requestId: string; + runId?: string; +} + +export interface TaxonomyQueueProcessorConfig extends BaseQueueProcessorConfig { + taxonomyModel: string; + apiBaseUrl: string; + sessionTimeoutMs?: number; + schedulerUrl?: string; + tokenManagerUrl?: string; +} + +export class TaxonomyQueueProcessor extends BaseQueueProcessor { + private taxonomyConfig: TaxonomyQueueProcessorConfig; + private tokenClient: TokenManagerClient; + private blobStorage: BlobStorage; + + constructor(config: TaxonomyQueueProcessorConfig) { + super(config, "taxonomy-handler"); + this.taxonomyConfig = config; + this.tokenClient = new TokenManagerClient(config.tokenManagerUrl); + this.blobStorage = new BlobStorage({ + storageAccountName: config.storageAccountName, + storageConnectionString: config.storageConnectionString, + }); + } + + protected override async handleRequest( + doc: RequestDocument, + message: DequeuedMessageItem, + heartbeat: VisibilityHeartbeat, + log: (level: LogEvent["level"], msg: string, data?: Record) => Promise, + payload?: Record, + ): Promise { + const queueMessage = payload as TaxonomyQueueMessage | undefined; + const requestId = doc._id; + const activeRunId = doc.run?._id; + const runId = queueMessage?.runId ?? activeRunId ?? requestId; + + if (!queueMessage || queueMessage.type !== "taxonomy") { + await log("warn", "Discarding message with unsupported taxonomy payload", { payload }); + await this.safeDeleteMessage(message.messageId, heartbeat.stop()); + return; + } + + if (queueMessage.runId && activeRunId && queueMessage.runId !== activeRunId) { + await log("warn", "Discarding stale taxonomy message for superseded run", { + requestId, + queuedRunId: queueMessage.runId, + activeRunId, + }); + await this.safeDeleteMessage(message.messageId, heartbeat.stop()); + return; + } + + if (!doc.run) { + throw new Error(`Request ${requestId} has no active run to classify`); + } + + await withRetry(() => this.collection.updateOne( + { _id: requestId } as never, + { + $set: { + [`run.handlerStatus.${HANDLER_ID}.status`]: "processing", + [`run.handlerStatus.${HANDLER_ID}.version`]: HANDLER_VERSION, + [`run.handlerStatus.${HANDLER_ID}.updatedAt`]: new Date(), + [`run.handlerStatus.${HANDLER_ID}.error`]: null, + }, + } as never, + )); + + await log("info", "Starting taxonomy generation", { requestId, runId, model: this.taxonomyConfig.taxonomyModel }); + + try { + const taxonomy = await this.generateTaxonomy(requestId, runId, log); + const blobName = `${requestId}/runs/${runId}/taxonomy.json`; + const taxonomyUrl = await this.blobStorage.uploadJson(blobName, taxonomy); + + await withRetry(() => this.collection.updateOne( + { _id: requestId } as never, + { + $set: { + [`run.handlerStatus.${HANDLER_ID}.status`]: "done", + [`run.handlerStatus.${HANDLER_ID}.version`]: HANDLER_VERSION, + [`run.handlerStatus.${HANDLER_ID}.updatedAt`]: new Date(), + }, + $unset: { + [`run.handlerStatus.${HANDLER_ID}.error`]: "", + }, + } as never, + )); + + await log("info", "Taxonomy generation completed", { + requestId, + runId, + blobName, + taxonomyUrl, + }); + + await this.notifyHandlerComplete(requestId, runId, "done"); + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + + await withRetry(() => this.collection.updateOne( + { _id: requestId } as never, + { + $set: { + [`run.handlerStatus.${HANDLER_ID}.status`]: "failed", + [`run.handlerStatus.${HANDLER_ID}.version`]: HANDLER_VERSION, + [`run.handlerStatus.${HANDLER_ID}.updatedAt`]: new Date(), + [`run.handlerStatus.${HANDLER_ID}.error`]: errorMessage, + }, + } as never, + )); + + await log("error", `Taxonomy generation failed: ${errorMessage}`, { requestId, runId }); + await this.notifyHandlerComplete(requestId, runId, "failed"); + throw error; + } + + const finalPopReceipt = heartbeat.stop(); + await this.safeDeleteMessage(message.messageId, finalPopReceipt); + } + + private async generateTaxonomy( + requestId: string, + runId: string, + log: (level: LogEvent["level"], msg: string, data?: Record) => Promise, + ): Promise { + const githubToken = await this.tokenClient.acquireToken("copilot-sdk"); + const client = new CopilotClient({ githubToken }); + const tools = createTaxonomyTools(this.taxonomyConfig.apiBaseUrl, requestId, this.blobStorage); + const timeoutMs = this.taxonomyConfig.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS; + + let streamedResponse = ""; + let latestMessage = ""; + let lastLoggedCharCount = 0; + const toolNames = new Map(); + + try { + await log("info", "Acquired Copilot SDK token"); + + const session = await client.createSession({ + model: this.taxonomyConfig.taxonomyModel, + streaming: true, + tools, + systemMessage: { mode: "replace", content: TAXONOMY_SYSTEM_PROMPT }, + }); + + session.on((event: SessionEvent) => { + switch (event.type) { + case "session.start": + void log("info", "Copilot session started", { + sessionId: event.data.sessionId, + model: event.data.selectedModel, + }); + break; + case "session.error": + void log("error", `Session error: ${event.data.message}`, { errorType: event.data.errorType }); + break; + case "tool.execution_start": + toolNames.set(event.data.toolCallId, event.data.toolName); + void log("info", `Tool call: ${event.data.toolName}`, { + toolCallId: event.data.toolCallId, + arguments: event.data.arguments as Record | undefined, + }); + break; + case "tool.execution_complete": { + const toolName = toolNames.get(event.data.toolCallId) ?? "unknown"; + toolNames.delete(event.data.toolCallId); + void log("info", `Tool result: ${toolName} (${event.data.success ? "success" : "failed"})`, { + toolCallId: event.data.toolCallId, + error: event.data.error?.message, + }); + break; + } + case "assistant.message_delta": + streamedResponse += event.data.deltaContent; + if (streamedResponse.length - lastLoggedCharCount >= DELTA_LOG_INTERVAL) { + lastLoggedCharCount = streamedResponse.length; + void log("info", `Generating taxonomy… (${streamedResponse.length} chars so far)`); + } + break; + case "assistant.message": + latestMessage = event.data.content; + break; + } + }); + + let attempts = 0; + const maxAttempts = 3; + let prompt = [ + `Generate taxonomy JSON for request ${requestId} and run ${runId}.`, + "Use get_run_data first, then inspect ATIF trajectories that materially affect the classification.", + "Return only raw JSON that satisfies the taxonomy schema.", + ].join(" "); + let lastJson: string | undefined; + + while (attempts < maxAttempts) { + attempts += 1; + streamedResponse = ""; + latestMessage = ""; + lastLoggedCharCount = 0; + + await log("info", `Sending taxonomy prompt to Copilot SDK (attempt ${attempts}/${maxAttempts})`, { + requestId, + runId, + timeoutMs, + }); + + const response = await session.sendAndWait({ prompt }, timeoutMs); + const responseText = response?.data.content?.trim() || latestMessage.trim() || streamedResponse.trim(); + + if (!responseText) { + throw new Error("Copilot SDK returned an empty taxonomy response"); + } + + const jsonText = extractJson(responseText); + lastJson = jsonText; + + let parsedJson: unknown; + try { + parsedJson = JSON.parse(jsonText) as unknown; + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + if (attempts >= maxAttempts) { + throw new Error(`Taxonomy response was not valid JSON after ${maxAttempts} attempts: ${errorMessage}`); + } + + prompt = [ + "Your previous response was not valid JSON.", + `JSON parse error: ${errorMessage}.`, + "Return the full taxonomy document again as raw JSON only, with no markdown fences or commentary.", + "Replace the entire response with corrected JSON.", + ].join(" "); + continue; + } + + const validation = taxonomySchema.safeParse(parsedJson); + if (validation.success) { + return validation.data; + } + + const validationErrors = formatValidationErrors(validation.error.issues); + await log("warn", `Taxonomy validation failed on attempt ${attempts}`, { + issues: validationErrors, + }); + + if (attempts >= maxAttempts) { + throw new Error( + `Taxonomy schema validation failed after ${maxAttempts} attempts: ${validationErrors.join(" | ")}`, + ); + } + + prompt = [ + "Your previous taxonomy JSON did not satisfy the schema.", + "Correct the document and return the entire replacement JSON object.", + "Do not include markdown fences or commentary.", + `Validation errors: ${validationErrors.join("; ")}`, + lastJson ? `Previous JSON: ${lastJson}` : "", + ].filter(Boolean).join(" "); + } + + throw new Error("Taxonomy generation ended without a valid document"); + } finally { + await client.stop().catch(() => undefined); + } + } + + private async notifyHandlerComplete( + requestId: string, + runId: string, + status: "done" | "failed", + ): Promise { + const schedulerUrl = this.taxonomyConfig.schedulerUrl; + if (!schedulerUrl) return; + + try { + const response = await fetch(`${schedulerUrl}/notify/handler-complete`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ requestId, runId, handlerId: HANDLER_ID, status }), + }); + + if (!response.ok) { + console.warn(`[taxonomy-handler] Scheduler notify failed: ${response.status}`); + } + } catch (error) { + console.warn(`[taxonomy-handler] Scheduler notify error for ${requestId}/${runId}:`, error); + } + } +} + +function extractJson(responseText: string): string { + const trimmed = responseText.trim(); + if (!trimmed.startsWith("```")) { + return trimmed; + } + + const fenceMatch = trimmed.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i); + return fenceMatch?.[1]?.trim() ?? trimmed; +} + +function formatValidationErrors(issues: Array<{ path: PropertyKey[]; message: string }>): string[] { + return issues.map((issue) => { + const path = issue.path.length > 0 ? issue.path.map((segment) => String(segment)).join(".") : ""; + return `${path}: ${issue.message}`; + }); +} diff --git a/apps/workers/taxonomy/src/tools.ts b/apps/workers/taxonomy/src/tools.ts new file mode 100644 index 000000000..9c92b5b18 --- /dev/null +++ b/apps/workers/taxonomy/src/tools.ts @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { defineTool } from "@github/copilot-sdk"; +import { BlobStorage, type ConversationTurn, type RequestDocument } from "shared"; + +interface GetAtifTrajectoryArgs { + iteration?: number; +} + +function resolveSnapshotsBlobName(blobUrl: string): string { + const url = new URL(blobUrl); + const containerPrefix = "/snapshots/"; + const containerIndex = url.pathname.indexOf(containerPrefix); + if (containerIndex === -1) { + throw new Error(`Blob URL does not contain the snapshots container: ${blobUrl}`); + } + return decodeURIComponent(url.pathname.substring(containerIndex + containerPrefix.length)); +} + +function selectTurnWithAtif(turns: ConversationTurn[] | undefined, requestedIteration?: number): ConversationTurn | undefined { + if (!turns?.length) return undefined; + + if (requestedIteration !== undefined) { + return turns.find((turn) => turn.iteration === requestedIteration && typeof turn.atifUrl === "string"); + } + + return [...turns] + .filter((turn) => typeof turn.atifUrl === "string") + .sort((a, b) => b.iteration - a.iteration)[0]; +} + +export function createTaxonomyTools( + apiBaseUrl: string, + requestId: string, + blobStorage: BlobStorage, +) { + const getRunData = defineTool("get_run_data", { + description: + "Fetch the full request document plus the active run state, including scenario, persona, turns, criteria results, and handler status.", + parameters: { + type: "object", + properties: {}, + }, + handler: async () => { + try { + const response = await fetch(`${apiBaseUrl}/api/v1/requests/${requestId}`); + if (!response.ok) { + return { error: `Failed to fetch request: ${response.status} ${response.statusText}` }; + } + + const request: RequestDocument = await response.json(); + const run = request.run; + + return { + request: { + id: request._id, + workerType: request.workerType, + model: request.model, + reasoningEffort: request.reasoningEffort, + maxIterations: request.maxIterations, + createdAt: request.createdAt, + updatedAt: request.updatedAt, + persona: request.persona, + personaInstructions: request.personaInstructions, + mcpServers: request.mcpServers, + skillRevisions: request.skillRevisions, + extensions: request.extensions, + priority: request.priority, + scenario: request.scenario, + }, + run: run ? { + id: run._id, + attemptNumber: run.attemptNumber, + status: run.status, + outcome: run.outcome, + result: run.result, + error: run.error, + startedAt: run.startedAt, + finishedAt: run.finishedAt, + updatedAt: run.updatedAt, + aiCallCount: run.aiCallCount, + tokenUsage: run.tokenUsage, + handlerStatus: run.handlerStatus, + turns: run.turns?.map((turn) => ({ + iteration: turn.iteration, + passed: turn.passed, + timestamp: turn.timestamp, + startedAt: turn.startedAt, + durationMs: turn.durationMs, + judgeFeedback: turn.judgeFeedback, + codingAgentResponse: turn.codingAgentResponse, + aiCallCount: turn.aiCallCount, + tokenUsage: turn.tokenUsage, + snapshotUrl: turn.snapshotUrl, + rawChatUrl: turn.rawChatUrl, + rawChatFormat: turn.rawChatFormat, + toolCallsUrl: turn.toolCallsUrl, + toolCallCount: turn.toolCallCount, + atifUrl: turn.atifUrl, + criteriaResults: turn.criteriaResults, + })) ?? [], + } : null, + }; + } catch (err) { + return { error: `Failed to fetch run data: ${err}` }; + } + }, + }); + + const getAtifTrajectory = defineTool("get_atif_trajectory", { + description: + "Fetch an ATIF trajectory JSON document for a specific iteration, or the latest available iteration when omitted.", + parameters: { + type: "object", + properties: { + iteration: { + type: "number", + description: "Optional 1-based iteration number. If omitted, the latest available ATIF trajectory is returned.", + }, + }, + }, + handler: async (args: GetAtifTrajectoryArgs) => { + try { + const response = await fetch(`${apiBaseUrl}/api/v1/requests/${requestId}`); + if (!response.ok) { + return { error: `Failed to fetch request: ${response.status} ${response.statusText}` }; + } + + const request: RequestDocument = await response.json(); + const selectedTurn = selectTurnWithAtif(request.run?.turns, args.iteration); + + if (!selectedTurn?.atifUrl) { + return { + error: args.iteration !== undefined + ? `No ATIF trajectory available for iteration ${args.iteration}` + : "No ATIF trajectory is available for this run", + }; + } + + const blobName = resolveSnapshotsBlobName(selectedTurn.atifUrl); + const buffer = await blobStorage.downloadBlobToBuffer(blobName); + const trajectory: unknown = JSON.parse(buffer.toString("utf-8")); + + return { + iteration: selectedTurn.iteration, + trajectory, + }; + } catch (err) { + return { error: `Failed to fetch ATIF trajectory: ${err}` }; + } + }, + }); + + return [getRunData, getAtifTrajectory]; +} diff --git a/apps/workers/taxonomy/tsconfig.json b/apps/workers/taxonomy/tsconfig.json new file mode 100644 index 000000000..bf012ecbb --- /dev/null +++ b/apps/workers/taxonomy/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./src" + }, + "include": ["src/**/*"] +} diff --git a/docker-compose.yml b/docker-compose.yml index d1ca5dcb0..a4503d104 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -9,6 +9,7 @@ # docker compose --profile vscode-web up # + VS Code Web worker # docker compose --profile claude-code --profile copilot up # multiple workers # docker compose --profile report up # + Report Generator worker +# docker compose --profile taxonomy up # + Taxonomy handler worker # docker compose up mongodb redis azurite # infra only (run app services natively) # # Host-native debugging: @@ -35,6 +36,7 @@ x-worker-env: &worker-env <<: *common-env JUDGE_SERVICE_URL: http://judge:80 SCOPE_MT_API_URL: http://api:80 + SCHEDULER_URL: http://scheduler:8080 TOKEN_MANAGER_URL: http://token-manager:80 x-worker-deps: &worker-deps @@ -138,7 +140,7 @@ services: timeout: 5s retries: 5 - # Creates the 'har' blob container in Azurite for the gateway HAR plugin. + # Creates the 'har' blob container and handler queues in Azurite. azurite-init: image: mcr.microsoft.com/azure-cli:2.68.0 restart: "no" @@ -146,9 +148,12 @@ services: azurite: condition: service_healthy environment: - AZURE_STORAGE_CONNECTION_STRING: "DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://azurite:10000/devstoreaccount1;" + AZURE_STORAGE_CONNECTION_STRING: "DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;QueueEndpoint=http://azurite:10001/devstoreaccount1;BlobEndpoint=http://azurite:10000/devstoreaccount1;" command: > - sh -c "az storage container create --name har --connection-string \"$$AZURE_STORAGE_CONNECTION_STRING\" || true" + sh -c "az storage container create --name har --connection-string \"$$AZURE_STORAGE_CONNECTION_STRING\" || true && + az storage queue create --name report-queue --connection-string \"$$AZURE_STORAGE_CONNECTION_STRING\" || true && + az storage queue create --name post-processor-queue --connection-string \"$$AZURE_STORAGE_CONNECTION_STRING\" || true && + az storage queue create --name pp-taxonomy-queue --connection-string \"$$AZURE_STORAGE_CONNECTION_STRING\" || true" # =========================================================================== # Application services @@ -638,6 +643,34 @@ services: api: condition: service_started + taxonomy-handler: + build: + context: . + dockerfile: apps/workers/taxonomy/Dockerfile + profiles: [taxonomy, all] + environment: + <<: *common-env + AZURE_STORAGE_QUEUE_TAXONOMY: pp-taxonomy-queue + TAXONOMY_MODEL: ${TAXONOMY_MODEL:-gpt-4.1} + SCOPE_MT_API_URL: http://api:80 + SCHEDULER_URL: http://scheduler:8080 + GITHUB_TOKEN: ${GITHUB_TOKEN:-} + TOKEN_MANAGER_URL: http://token-manager:80 + GIT_COMMIT: ${GIT_COMMIT:-development} + SESSION_TIMEOUT_MS: ${SESSION_TIMEOUT_MS:-300000} + depends_on: + mongodb: + condition: service_healthy + required: false + redis: + condition: service_healthy + azurite: + condition: service_healthy + api: + condition: service_started + scheduler: + condition: service_started + register-version-post-processor: build: context: . @@ -661,6 +694,7 @@ services: <<: *common-env AZURE_STORAGE_QUEUE_POSTPROCESSOR: post-processor-queue SCOPE_MT_API_URL: http://api:80 + SCHEDULER_URL: http://scheduler:8080 depends_on: mongodb: condition: service_healthy diff --git a/docs/architecture/db-migrations.md b/docs/architecture/db-migrations.md index 9cfd9540e..fbe5b1cd4 100644 --- a/docs/architecture/db-migrations.md +++ b/docs/architecture/db-migrations.md @@ -102,6 +102,9 @@ When you run a command: | `007-rename-exhausted-to-finished` | Renames outcome `exhausted` → `finished` | | `008-backfill-ai-call-count` | Downloads HARs from blob storage to count AI completion calls per turn | | `009-add-requests-filter-indexes` | Adds indexes on `taskPromptId`, `status`, `outcome`, `workerType`, `deletedAt` for server-side filtering/grouping | +| `018-migrate-services-to-handler-dag` | Replaces the legacy single `post-processor` service row with per-handler service registrations and dependencies | +| `019-add-handler-status-index` | Adds handler-specific dispatch indexes for `pp-atif`, `pp-taxonomy`, and `pp-report` polling | +| `020-backfill-handler-status` | Backfills `run.handlerStatus.pp-atif` from deprecated `run.postProcessorStatus` / `run.postProcessorVersion` fields | ## CI/CD diff --git a/docs/architecture/overview.md b/docs/architecture/overview.md index 8c919498b..7550c5703 100644 --- a/docs/architecture/overview.md +++ b/docs/architecture/overview.md @@ -79,6 +79,8 @@ flowchart TB | `shared` | Shared types and utilities | | `workers/coder-acp-claude-code` | Claude Code agent via Agent Client Protocol (ACP) | | `workers/coder-acp-copilot` | GitHub Copilot agent via Agent Client Protocol (ACP) | +| `workers/report-generator` | Copilot SDK worker that generates post-run markdown reports | +| `workers/taxonomy` | Copilot SDK worker that generates validated post-run taxonomy JSON | | `gateway` | AI Gateway — shared Rust TLS-intercepting proxy with plugin architecture (HAR capture, future: token refresh, rate limiting) | ## Data Flow diff --git a/docs/architecture/post-processing.md b/docs/architecture/post-processing.md index c351b830c..7bdf7e2e8 100644 --- a/docs/architecture/post-processing.md +++ b/docs/architecture/post-processing.md @@ -14,8 +14,9 @@ flowchart LR Two paths trigger post-processing: -1. **Event-driven (primary):** Coder workers enqueue a post-processing message immediately when a run completes, setting `run.postProcessorStatus: "queued"` atomically in the same DB write. -2. **Scheduler backfill:** The `PostProcessorDispatcher` polls every 30 seconds for runs that have `status: "done"` but no `postProcessorStatus` set (or a `postProcessorVersion` below the current target). This catches runs that completed before the event-driven dispatch was deployed, or that need re-processing after a version bump. +1. **Event-driven (primary):** Coder workers enqueue a post-processing message immediately when a run completes, currently setting the deprecated `run.postProcessorStatus: "queued"` compatibility field atomically in the same DB write while the system migrates to per-handler status. +2. **Scheduler backfill:** The `PostProcessorDispatcher` polls every 30 seconds for runs that have `status: "done"` but no post-processing marker set (or a stale handler version). During the migration window this may consult the deprecated flat fields; the long-term source of truth is `run.handlerStatus[handlerId]`. This catches runs that completed before the event-driven dispatch was deployed, or that need re-processing after a version bump. +3. **Scheduler notify server:** The scheduler also exposes `GET /health`, `POST /notify/run-terminal`, and `POST /notify/handler-complete` on a lightweight `node:http` server. Workers and post-process handlers use these endpoints to notify the scheduler when terminal states are reached so it can re-evaluate which root or downstream handlers are ready to dispatch. ## ATIF Generation @@ -32,8 +33,24 @@ Two paths trigger post-processing: - Uploads `atif.trajectory.json` to blob storage at `{requestId}/runs/{runId}/iteration-{N}/atif.trajectory.json` - Updates `run.turns.$.atifUrl` in the request document -4. On success, stamps `run.postProcessorVersion` and sets `run.postProcessorStatus: "done"` -5. Triggers report generation via the API (best-effort, with retry) +4. On success, stamps `run.handlerStatus["pp-atif"] = { status: "done", version: N }` (while legacy `run.postProcessorVersion` / `run.postProcessorStatus` may still be mirrored during the transition) +5. Triggers downstream taxonomy/report handlers once the scheduler sees the dependency graph is satisfied + +## Taxonomy Generation + +The taxonomy handler (`apps/workers/taxonomy/`) consumes messages from the dedicated `pp-taxonomy-queue` and produces a structured JSON artifact for a completed run. It uses the GitHub Copilot SDK with a tool-backed session to fetch run metadata from the API and ATIF trajectories from blob storage, then validates the generated JSON against the shared taxonomy Zod schema. + +### Flow + +1. Queue message arrives: `{ type: "taxonomy", requestId, runId }` +2. Worker fetches the request document from MongoDB and marks `run.handlerStatus["pp-taxonomy"].status = "processing"` +3. Copilot SDK session calls: + - `get_run_data` to fetch the request + active run from the API + - `get_atif_trajectory` to fetch per-iteration ATIF JSON from blob storage +4. The worker validates the assistant response with `taxonomySchema.safeParse()` +5. If validation fails, the worker feeds the schema errors back into the same session and retries up to 3 total attempts +6. On success, the worker uploads `taxonomy.json` to `{requestId}/runs/{runId}/taxonomy.json` +7. The worker stamps `run.handlerStatus["pp-taxonomy"] = { status: "done", version: 1 }` and calls `POST /notify/handler-complete` ### Blob Storage Layout @@ -98,10 +115,10 @@ processor.start(); The post-processor uses a version-based re-processing scheme: -- The worker declares its version in `src/version.ts` (e.g., `export const POST_PROCESSOR_VERSION = 1`) -- On each deploy, a registration Job writes `{ _id: "post-processor", version: N }` to the `services` collection -- The scheduler's `PostProcessorDispatcher` compares each request's `run.postProcessorVersion` against the registered version -- Requests with a lower version are re-dispatched for processing with the new handler logic +- Each handler is registered independently in the `services` collection using a `post-process-handler` document keyed by handler ID (for example `pp-atif`, `pp-taxonomy`, `pp-report`) +- Each registration stores the handler `version`, queue name, selector, `autoBackfill` behavior, and `dependsOn` DAG edges +- The scheduler compares each request's per-handler status/version state (for example `run.handlerStatus["pp-atif"]`) against the registered handler entry for that selector +- Requests with missing or outdated handler state are re-dispatched for that specific handler once its dependencies are satisfied This allows deploying handler improvements and having them automatically applied to historical data. @@ -127,16 +144,20 @@ stateDiagram-v2 | Environment Variable | Default | Description | | --- | --- | --- | -| `AZURE_STORAGE_QUEUE_POSTPROCESSOR` | `post-processor-queue` | Queue name for post-processor messages | +| `AZURE_STORAGE_QUEUE_POSTPROCESSOR` | `post-processor-queue` | Queue name for ATIF post-processor messages | +| `AZURE_STORAGE_QUEUE_TAXONOMY` | `pp-taxonomy-queue` | Queue name for taxonomy-generation jobs | | `SCHEDULER_PP_POLL_INTERVAL_MS` | `30000` | Scheduler backfill polling interval | | `BATCH_SIZE` | `1` | Messages to process per poll (worker-side) | | `POLL_INTERVAL_MS` | `5000` | Worker queue polling interval | -| `SCOPE_MT_API_URL` / `API_BASE_URL` | `http://localhost:3001` | API URL for report generation trigger | +| `SCOPE_MT_API_URL` / `API_BASE_URL` | `http://localhost:3001` | API URL used by report/taxonomy Copilot tools | +| `TAXONOMY_MODEL` | `gpt-4.1` | Copilot SDK model used by the taxonomy handler | +| `SESSION_TIMEOUT_MS` | `300000` | Timeout for report/taxonomy Copilot SDK sessions | +| `SCHEDULER_URL` | _(unset)_ | Optional scheduler notify base URL for downstream handler dispatch | ## Infrastructure -- **Queue:** Azure Storage Queue (`post-processor-queue`) +- **Queues:** Azure Storage Queues (`post-processor-queue` for ATIF, `pp-taxonomy-queue` for taxonomy, `report-queue` for reports) - **Blob Storage:** `snapshots` container (shared with HAR, tool-calls, and other artifacts) -- **Database:** MongoDB `requests` collection (`run.postProcessorStatus`, `run.postProcessorVersion` fields) +- **Database:** MongoDB `requests` collection (`run.handlerStatus` map keyed by handler ID, with deprecated `run.postProcessorStatus` / `run.postProcessorVersion` compatibility fields during migration) - **KEDA:** ScaledObject scales the worker to zero when queue is empty - **Version registration:** Kubernetes Job runs on each deploy; Docker Compose uses an init service \ No newline at end of file diff --git a/packages/db-migrations/src/check-migrations.test.ts b/packages/db-migrations/src/check-migrations.test.ts index 6c631b83e..7a7a07b63 100644 --- a/packages/db-migrations/src/check-migrations.test.ts +++ b/packages/db-migrations/src/check-migrations.test.ts @@ -7,6 +7,7 @@ import { resetMigrationCheckCache, type MigrationCheckResult, } from "./check-migrations.js"; +import { REQUIRED_MIGRATIONS } from "./required-migrations.js"; // Mock Db function makeMockDb(appliedFiles: string[]) { @@ -30,55 +31,19 @@ describe("checkMigrations", () => { }); it("returns ready when all required migrations are applied", async () => { - const db = makeMockDb([ - "001-backfill-task-prompts.ts", - "002-create-indexes.ts", - "003-create-skill-indexes.ts", - "004-add-submission-id-index.ts", - "005-backfill-iteration-durations.ts", - "006-split-status-outcome.ts", - "007-rename-exhausted-to-finished.ts", - "008-backfill-ai-call-count.ts", - "009-add-requests-filter-indexes.ts", - "010-add-requests-pagination-index.ts", - "011-add-profile-indexes.ts", - "012-add-profile-name-index.ts", - "013-remove-logs-from-docs.ts", - "014-introduce-runs-and-run.ts", - "015-add-priority-and-scheduler-index.ts", - "016-fix-scheduler-sort-index.ts", - "017-add-post-processor-dispatch-index.ts", - ]); + const db = makeMockDb([...REQUIRED_MIGRATIONS]); const result = await checkMigrations(db); expect(result.ready).toBe(true); expect(result.pending).toEqual([]); - expect(result.totalApplied).toBe(17); - expect(result.applied).toEqual([ - "001-backfill-task-prompts.ts", - "002-create-indexes.ts", - "003-create-skill-indexes.ts", - "004-add-submission-id-index.ts", - "005-backfill-iteration-durations.ts", - "006-split-status-outcome.ts", - "007-rename-exhausted-to-finished.ts", - "008-backfill-ai-call-count.ts", - "009-add-requests-filter-indexes.ts", - "010-add-requests-pagination-index.ts", - "011-add-profile-indexes.ts", - "012-add-profile-name-index.ts", - "013-remove-logs-from-docs.ts", - "014-introduce-runs-and-run.ts", - "015-add-priority-and-scheduler-index.ts", - "016-fix-scheduler-sort-index.ts", - "017-add-post-processor-dispatch-index.ts", - ]); + expect(result.totalApplied).toBe(REQUIRED_MIGRATIONS.length); + expect(result.applied).toEqual(REQUIRED_MIGRATIONS); }); it("returns not ready when migrations are missing", async () => { const db = makeMockDb(["001-backfill-task-prompts.ts"]); const result = await checkMigrations(db); expect(result.ready).toBe(false); - expect(result.pending).toEqual(["002-create-indexes.ts", "003-create-skill-indexes.ts", "004-add-submission-id-index.ts", "005-backfill-iteration-durations.ts", "006-split-status-outcome.ts", "007-rename-exhausted-to-finished.ts", "008-backfill-ai-call-count.ts", "009-add-requests-filter-indexes.ts", "010-add-requests-pagination-index.ts", "011-add-profile-indexes.ts", "012-add-profile-name-index.ts", "013-remove-logs-from-docs.ts", "014-introduce-runs-and-run.ts", "015-add-priority-and-scheduler-index.ts", "016-fix-scheduler-sort-index.ts", "017-add-post-processor-dispatch-index.ts"]); + expect(result.pending).toEqual(REQUIRED_MIGRATIONS.slice(1)); expect(result.applied).toEqual(["001-backfill-task-prompts.ts"]); expect(result.totalApplied).toBe(1); }); @@ -87,54 +52,20 @@ describe("checkMigrations", () => { const db = makeMockDb([]); const result = await checkMigrations(db); expect(result.ready).toBe(false); - expect(result.pending).toEqual([ - "001-backfill-task-prompts.ts", - "002-create-indexes.ts", - "003-create-skill-indexes.ts", - "004-add-submission-id-index.ts", - "005-backfill-iteration-durations.ts", - "006-split-status-outcome.ts", - "007-rename-exhausted-to-finished.ts", - "008-backfill-ai-call-count.ts", - "009-add-requests-filter-indexes.ts", - "010-add-requests-pagination-index.ts", - "011-add-profile-indexes.ts", - "012-add-profile-name-index.ts", - "013-remove-logs-from-docs.ts", - "014-introduce-runs-and-run.ts", - "015-add-priority-and-scheduler-index.ts", - "016-fix-scheduler-sort-index.ts", - "017-add-post-processor-dispatch-index.ts", - ]); + expect(result.pending).toEqual(REQUIRED_MIGRATIONS); expect(result.applied).toEqual([]); expect(result.totalApplied).toBe(0); }); it("ignores extra applied migrations not in the required list", async () => { const db = makeMockDb([ - "001-backfill-task-prompts.ts", - "002-create-indexes.ts", - "003-create-skill-indexes.ts", - "004-add-submission-id-index.ts", - "005-backfill-iteration-durations.ts", - "006-split-status-outcome.ts", - "007-rename-exhausted-to-finished.ts", - "008-backfill-ai-call-count.ts", - "009-add-requests-filter-indexes.ts", - "010-add-requests-pagination-index.ts", - "011-add-profile-indexes.ts", - "012-add-profile-name-index.ts", - "013-remove-logs-from-docs.ts", - "014-introduce-runs-and-run.ts", - "015-add-priority-and-scheduler-index.ts", - "016-fix-scheduler-sort-index.ts", - "017-add-post-processor-dispatch-index.ts", + ...REQUIRED_MIGRATIONS, "999-future-migration.ts", ]); const result = await checkMigrations(db); expect(result.ready).toBe(true); expect(result.pending).toEqual([]); - expect(result.totalApplied).toBe(18); + expect(result.totalApplied).toBe(REQUIRED_MIGRATIONS.length + 1); }); it("caches results within TTL", async () => { diff --git a/packages/db-migrations/src/migrations/018-migrate-services-to-handler-dag.ts b/packages/db-migrations/src/migrations/018-migrate-services-to-handler-dag.ts new file mode 100644 index 000000000..9ea8644fe --- /dev/null +++ b/packages/db-migrations/src/migrations/018-migrate-services-to-handler-dag.ts @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import type { Db } from "mongodb"; +import type { MigrationInterface } from "mongo-migrate-ts"; + +interface ServiceDocument { + _id: string; + version: number; + type?: "post-process-handler"; + queue?: string; + selector?: string; + autoBackfill?: boolean; + dependsOn?: string[]; +} + +type HandlerServiceSeed = Required & { + type: "post-process-handler"; +}; + +const HANDLER_SERVICES: readonly HandlerServiceSeed[] = [ + { + _id: "pp-atif", + type: "post-process-handler", + version: 2, + queue: "post-processor-queue", + selector: "atif", + autoBackfill: true, + dependsOn: [], + }, + { + _id: "pp-taxonomy", + type: "post-process-handler", + version: 1, + queue: "pp-taxonomy-queue", + selector: "taxonomy", + autoBackfill: false, + dependsOn: ["pp-atif"], + }, + { + _id: "pp-report", + type: "post-process-handler", + version: 1, + queue: "report-queue", + selector: "report", + autoBackfill: false, + dependsOn: ["pp-atif", "pp-taxonomy"], + }, +]; + +export class MigrateServicesToHandlerDag implements MigrationInterface { + async up(db: Db): Promise { + const services = db.collection("services"); + + await services.deleteOne({ _id: "post-processor" }); + console.log("[018] Deleted legacy post-processor service entry if it existed"); + + for (const service of HANDLER_SERVICES) { + const { _id, ...fields } = service; + await services.updateOne( + { _id }, + { + $set: { + ...fields, + dependsOn: [...fields.dependsOn], + }, + }, + { upsert: true }, + ); + console.log(`[018] Upserted handler service ${_id}`); + } + } + + async down(db: Db): Promise { + const services = db.collection("services"); + + await services.deleteMany({ _id: { $in: HANDLER_SERVICES.map((service) => service._id) } }); + console.log("[018-down] Deleted handler service entries"); + + await services.updateOne( + { _id: "post-processor" }, + { + $set: { version: 2 }, + $unset: { + type: "", + queue: "", + selector: "", + autoBackfill: "", + dependsOn: "", + }, + }, + { upsert: true }, + ); + console.log("[018-down] Restored legacy post-processor service entry"); + } +} diff --git a/packages/db-migrations/src/migrations/019-add-handler-status-index.ts b/packages/db-migrations/src/migrations/019-add-handler-status-index.ts new file mode 100644 index 000000000..ecdb0352a --- /dev/null +++ b/packages/db-migrations/src/migrations/019-add-handler-status-index.ts @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import type { Db } from "mongodb"; +import type { MigrationInterface } from "mongo-migrate-ts"; + +const HANDLER_STATUS_INDEXES = [ + { + name: "idx_handler_dispatch_atif", + key: { + "run.handlerStatus.pp-atif.status": 1 as const, + "run.status": 1 as const, + updatedAt: -1 as const, + }, + }, + { + name: "idx_handler_dispatch_taxonomy", + key: { + "run.handlerStatus.pp-taxonomy.status": 1 as const, + "run.status": 1 as const, + updatedAt: -1 as const, + }, + }, + { + name: "idx_handler_dispatch_report", + key: { + "run.handlerStatus.pp-report.status": 1 as const, + "run.status": 1 as const, + updatedAt: -1 as const, + }, + }, +] as const; + +export class AddHandlerStatusIndex implements MigrationInterface { + async up(db: Db): Promise { + const requests = db.collection("requests"); + + for (const index of HANDLER_STATUS_INDEXES) { + try { + const createdName = await requests.createIndex(index.key, { name: index.name }); + const exists = await requests.indexExists(createdName); + console.log( + exists + ? `[019] Created ${index.name} index on requests` + : `[019] ${index.name} was requested but is not visible in getIndexes()`, + ); + } catch (err: unknown) { + const message = err instanceof Error ? err.message : String(err); + console.log(`[019] ${index.name} already exists or couldn't be created: ${message}`); + } + } + } + + async down(db: Db): Promise { + const requests = db.collection("requests"); + + for (const index of HANDLER_STATUS_INDEXES) { + try { + await requests.dropIndex(index.name); + console.log(`[019-down] Dropped ${index.name} index`); + } catch (err: unknown) { + const codeName = typeof err === "object" && err !== null && "codeName" in err + ? String((err as { codeName?: unknown }).codeName) + : undefined; + if (codeName !== "IndexNotFound") { + const message = err instanceof Error ? err.message : String(err); + console.log(`[019-down] ${index.name} not found: ${message}`); + } + } + } + } +} diff --git a/packages/db-migrations/src/migrations/020-backfill-handler-status.ts b/packages/db-migrations/src/migrations/020-backfill-handler-status.ts new file mode 100644 index 000000000..ac5326afd --- /dev/null +++ b/packages/db-migrations/src/migrations/020-backfill-handler-status.ts @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import type { AnyBulkWriteOperation, Db } from "mongodb"; +import type { MigrationInterface } from "mongo-migrate-ts"; + +const BATCH_SIZE = 100; + +type RequestWithPostProcessorState = { + _id: string; + run?: { + postProcessorStatus?: "queued" | "processing" | "done" | "failed"; + postProcessorVersion?: number; + }; +}; + +export class BackfillHandlerStatus implements MigrationInterface { + async up(db: Db): Promise { + const requests = db.collection("requests"); + const cursor = requests.find( + { "run.postProcessorVersion": { $exists: true } }, + { + projection: { + _id: 1, + "run.postProcessorStatus": 1, + "run.postProcessorVersion": 1, + }, + batchSize: BATCH_SIZE, + }, + ); + + let processed = 0; + let modified = 0; + let batch: AnyBulkWriteOperation[] = []; + + for await (const doc of cursor) { + const version = doc.run?.postProcessorVersion; + if (version === undefined) { + continue; + } + + batch.push({ + updateOne: { + filter: { _id: doc._id, "run.postProcessorVersion": { $exists: true } }, + update: { + $set: { + "run.handlerStatus.pp-atif": { + status: doc.run?.postProcessorStatus ?? "done", + version, + }, + }, + }, + }, + }); + + if (batch.length >= BATCH_SIZE) { + const result = await requests.bulkWrite(batch, { ordered: false }); + processed += batch.length; + modified += result.modifiedCount; + batch = []; + } + } + + if (batch.length > 0) { + const result = await requests.bulkWrite(batch, { ordered: false }); + processed += batch.length; + modified += result.modifiedCount; + } + + console.log(` Backfilled handlerStatus for ${modified} runs (processed ${processed})`); + } + + async down(_db: Db): Promise { + // No-op: deprecated flat fields remain intact for rollback compatibility. + } +} diff --git a/packages/db-migrations/src/required-migrations.ts b/packages/db-migrations/src/required-migrations.ts index 120a54d0d..c1f1079d3 100644 --- a/packages/db-migrations/src/required-migrations.ts +++ b/packages/db-migrations/src/required-migrations.ts @@ -30,4 +30,7 @@ export const REQUIRED_MIGRATIONS: readonly string[] = [ "015-add-priority-and-scheduler-index.ts", "016-fix-scheduler-sort-index.ts", "017-add-post-processor-dispatch-index.ts", + "018-migrate-services-to-handler-dag.ts", + "019-add-handler-status-index.ts", + "020-backfill-handler-status.ts", ]; diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 392a9cde2..e2af74303 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -21,4 +21,5 @@ export * from "./devproxy/index.js"; export * from "./har/index.js"; export * from "./utils/index.js"; export * from "./schemas/index.js"; +export * from "./schemas/taxonomy.js"; export * from "./cursor.js"; diff --git a/packages/shared/src/queue/queue-processor.test.ts b/packages/shared/src/queue/queue-processor.test.ts index fb2a1dc95..2323e0057 100644 --- a/packages/shared/src/queue/queue-processor.test.ts +++ b/packages/shared/src/queue/queue-processor.test.ts @@ -269,8 +269,9 @@ describe("CodingAgentQueueProcessor.handleRequest redelivery handling", () => { }); // ─── Post-processor event-driven dispatch ──────────────────────────────────── -describe("CodingAgentQueueProcessor.enqueuePostProcessing", () => { - it("sends a post-processor queue message when postProcessorQueueName is configured", async () => { +describe("CodingAgentQueueProcessor.notifyRunTerminal", () => { + it("sends a post-processor queue message via legacy fallback when SCHEDULER_URL is not set", async () => { + delete process.env.SCHEDULER_URL; const configWithPP: QueueProcessorConfig = { ...testConfig, postProcessorQueueName: "post-processor-queue", @@ -280,7 +281,7 @@ describe("CodingAgentQueueProcessor.enqueuePostProcessing", () => { const sendMessage = vi.fn().mockResolvedValue({}); (qp as any).postProcessorQueueClient = { sendMessage }; - await (qp as any).enqueuePostProcessing("req-123", "run-456"); + await (qp as any).notifyRunTerminal("req-123", "run-456"); expect(sendMessage).toHaveBeenCalledTimes(1); const decoded = JSON.parse( @@ -289,13 +290,15 @@ describe("CodingAgentQueueProcessor.enqueuePostProcessing", () => { expect(decoded).toEqual({ type: "atif", requestId: "req-123", runId: "run-456" }); }); - it("does nothing when postProcessorQueueClient is null", async () => { + it("does nothing when postProcessorQueueClient is null and SCHEDULER_URL not set", async () => { + delete process.env.SCHEDULER_URL; const qp = new CodingAgentQueueProcessor(testConfig, stubProcessor); expect((qp as any).postProcessorQueueClient).toBeNull(); - await (qp as any).enqueuePostProcessing("req-123", "run-456"); + await (qp as any).notifyRunTerminal("req-123", "run-456"); }); it("logs a warning but does not throw on queue send failure", async () => { + delete process.env.SCHEDULER_URL; const configWithPP: QueueProcessorConfig = { ...testConfig, postProcessorQueueName: "post-processor-queue", @@ -306,7 +309,7 @@ describe("CodingAgentQueueProcessor.enqueuePostProcessing", () => { (qp as any).postProcessorQueueClient = { sendMessage }; const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); - await (qp as any).enqueuePostProcessing("req-123", "run-456"); + await (qp as any).notifyRunTerminal("req-123", "run-456"); expect(warnSpy).toHaveBeenCalledWith( expect.stringContaining("Failed to enqueue post-processing"), expect.any(Error), diff --git a/packages/shared/src/queue/queue-processor.ts b/packages/shared/src/queue/queue-processor.ts index f663284f7..0324499b4 100644 --- a/packages/shared/src/queue/queue-processor.ts +++ b/packages/shared/src/queue/queue-processor.ts @@ -44,7 +44,7 @@ export class CodingAgentQueueProcessor extends BaseQueueProcessor { + private async notifyRunTerminal(requestId: string, runId: string): Promise { + const schedulerUrl = process.env.SCHEDULER_URL; + if (schedulerUrl) { + try { + const response = await fetch(`${schedulerUrl}/notify/run-terminal`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ requestId, runId }), + }); + if (response.ok) { + console.log(`[${this.workerName}] Notified scheduler: run-terminal for ${requestId}`); + } else { + console.warn(`[${this.workerName}] Scheduler notify failed: ${response.status} — poll will catch up`); + } + return; + } catch (err) { + console.warn(`[${this.workerName}] Scheduler notify error for ${requestId} — poll will catch up:`, err); + return; + } + } + + // Legacy fallback: direct queue enqueue + await this.enqueuePostProcessingLegacy(requestId, runId); + } + + /** + * @deprecated Legacy direct queue enqueue. Use notifyRunTerminal instead. + * Kept as fallback when SCHEDULER_URL is not configured. + */ + private async enqueuePostProcessingLegacy(requestId: string, runId: string): Promise { if (!this.postProcessorQueueClient) return; try { const message = Buffer.from( @@ -79,9 +109,9 @@ export class CodingAgentQueueProcessor extends BaseQueueProcessor { - await this.enqueuePostProcessing(requestId, runId); + await this.notifyRunTerminal(requestId, runId); } /** Build workerVersion and OS fields for stamping on request documents. @@ -243,8 +273,8 @@ export class CodingAgentQueueProcessor extends BaseQueueProcessor { - const apiBaseUrl = (this.config as QueueProcessorConfig).apiBaseUrl; - if (!apiBaseUrl) return; - - try { - const response = await fetch(`${apiBaseUrl}/api/v1/reports/trigger`, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ requestId }), - }); - if (response.ok) { - const result = await response.json() as { triggered: number }; - console.log(`[${this.workerName}] Triggered report generation for request ${requestId}: ${result.triggered} report(s) created`); - } else { - console.warn(`[${this.workerName}] Failed to trigger report generation: ${response.status} ${response.statusText}`); - } - } catch (error) { - console.warn(`[${this.workerName}] Failed to trigger report generation: ${error}`); - } - } - /** * Extract skill archives to the workspace filesystem so agents can discover them. * Must be called after setup() so that processor.workspacePath points to the @@ -597,8 +601,8 @@ export class CodingAgentQueueProcessor extends BaseQueueProcessor { + const validFixture = { + meta: { + generatedAt: "2025-02-01T12:00:00Z", + schemaVersion: "1.0.0", + runId: "run-123", + requestId: "req-456", + }, + scorecard: { + summary: "The agent usually succeeds but struggles with recovery quality.", + profileResults: [ + { + profileId: "profile-best", + select: "best", + taskOutcome: "success", + overallScore: 92, + dimensions: [ + { + name: "Correctness", + score: 95, + rationale: "Implemented the requested behavior fully.", + evidence: ["All acceptance criteria passed", "No regressions observed"], + }, + ], + }, + ], + crossProfileInsights: [ + "The agent communicates clearly across profiles.", + "Stress conditions reduce recovery quality.", + ], + }, + behaviorAnalysis: { + patterns: [ + { + id: "pattern-1", + category: "strength", + title: "Consistent planning", + description: "The agent outlines a clear plan before making changes.", + frequency: 0.75, + impact: "high", + evidence: [ + { + runId: "run-123", + iteration: 1, + excerpt: "Plan: inspect the failing endpoint, then patch the handler.", + }, + ], + }, + ], + agentPersonality: { + communicationStyle: "Concise and structured", + problemSolvingApproach: "Hypothesis-driven debugging", + errorRecoveryBehavior: "Retries with targeted fixes after inspecting evidence", + }, + }, + actionList: { + fix: [ + { + id: "action-1", + title: "Stabilize recovery prompts", + priority: "critical", + description: "Reduce failures when the first attempt is rejected.", + ownership: "prompt-engineer", + relatedPatterns: ["pattern-1"], + suggestedApproach: "Add explicit fallback guidance for failed first passes.", + }, + ], + improve: [ + { + id: "action-2", + title: "Expand planning examples", + priority: "medium", + description: "Reinforce successful planning behavior.", + ownership: "agent-team", + relatedPatterns: ["pattern-1"], + suggestedApproach: "Fine-tune on traces with strong upfront decomposition.", + }, + ], + investigate: [ + { + id: "action-3", + title: "Review profile variance", + priority: "low", + description: "Understand why profile-specific regressions appear sporadically.", + ownership: "scenario-author", + relatedPatterns: ["pattern-1"], + suggestedApproach: "Compare scenario wording against affected profile runs.", + }, + ], + }, + }; + + it("accepts a valid taxonomy fixture", () => { + const result = taxonomySchema.safeParse(validFixture); + expect(result.success).toBe(true); + }); + + it("rejects fixtures missing required fields with precise paths", () => { + const invalidFixture = { + ...validFixture, + scorecard: { + ...validFixture.scorecard, + profileResults: [ + { + ...validFixture.scorecard.profileResults[0], + dimensions: [ + { + name: "Correctness", + score: 95, + evidence: ["All acceptance criteria passed"], + }, + ], + }, + ], + }, + behaviorAnalysis: { + ...validFixture.behaviorAnalysis, + agentPersonality: { + communicationStyle: "Concise and structured", + errorRecoveryBehavior: "Retries with targeted fixes after inspecting evidence", + }, + }, + }; + + const result = taxonomySchema.safeParse(invalidFixture); + expect(result.success).toBe(false); + if (result.success) { + throw new Error("Expected invalid taxonomy fixture to fail parsing"); + } + + const issuePaths = result.error.issues.map((issue) => issue.path); + expect(issuePaths).toContainEqual([ + "scorecard", + "profileResults", + 0, + "dimensions", + 0, + "rationale", + ]); + expect(issuePaths).toContainEqual([ + "behaviorAnalysis", + "agentPersonality", + "problemSolvingApproach", + ]); + }); + + it("enforces enum values", () => { + const invalidFixture = { + ...validFixture, + actionList: { + ...validFixture.actionList, + fix: [ + { + ...validFixture.actionList.fix[0], + priority: "urgent", + }, + ], + }, + }; + + const result = taxonomySchema.safeParse(invalidFixture); + expect(result.success).toBe(false); + if (result.success) { + throw new Error("Expected invalid enum fixture to fail parsing"); + } + + expect(result.error.issues.map((issue) => issue.path)).toContainEqual([ + "actionList", + "fix", + 0, + "priority", + ]); + }); +}); diff --git a/packages/shared/src/schemas/taxonomy.ts b/packages/shared/src/schemas/taxonomy.ts new file mode 100644 index 000000000..a837d4f91 --- /dev/null +++ b/packages/shared/src/schemas/taxonomy.ts @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { z } from "zod"; + +const scoreSchema = z.number().min(0).max(100); +const frequencySchema = z.number().min(0).max(1); + +/** Taxonomy document metadata. */ +export const taxonomyMetaSchema = z.object({ + generatedAt: z.string().datetime({ offset: true }), + schemaVersion: z.string().min(1), + runId: z.string().min(1), + requestId: z.string().min(1), +}); + +/** Scorecard dimension result for a single profile. */ +export const scorecardDimensionSchema = z.object({ + name: z.string().min(1), + score: scoreSchema, + rationale: z.string().min(1), + evidence: z.array(z.string().min(1)), +}); + +/** Scorecard result for a specific profile slice. */ +export const profileResultSchema = z.object({ + profileId: z.string().min(1), + select: z.enum(["best", "median", "worst"]), + taskOutcome: z.enum(["success", "partial", "failure"]), + overallScore: scoreSchema, + dimensions: z.array(scorecardDimensionSchema), +}); + +/** Top-level scorecard section summarizing profile results. */ +export const scorecardSchema = z.object({ + summary: z.string().min(1), + profileResults: z.array(profileResultSchema), + crossProfileInsights: z.array(z.string().min(1)), +}); + +/** Evidence excerpt supporting an observed behavior pattern. */ +export const behaviorEvidenceSchema = z.object({ + runId: z.string().min(1), + iteration: z.number().int().min(0), + excerpt: z.string().min(1), +}); + +/** Cross-run behavioral pattern identified by the taxonomy analysis. */ +export const behaviorPatternSchema = z.object({ + id: z.string().min(1), + category: z.enum(["strength", "weakness", "inconsistency", "regression"]), + title: z.string().min(1), + description: z.string().min(1), + frequency: frequencySchema, + impact: z.enum(["critical", "high", "medium", "low"]), + evidence: z.array(behaviorEvidenceSchema), +}); + +/** Qualitative description of the agent's personality traits. */ +export const agentPersonalitySchema = z.object({ + communicationStyle: z.string().min(1), + problemSolvingApproach: z.string().min(1), + errorRecoveryBehavior: z.string().min(1), +}); + +/** Behavior analysis section describing patterns and personality. */ +export const behaviorAnalysisSchema = z.object({ + patterns: z.array(behaviorPatternSchema), + agentPersonality: agentPersonalitySchema, +}); + +/** Action item emitted by the taxonomy analysis. */ +export const actionItemSchema = z.object({ + id: z.string().min(1), + title: z.string().min(1), + priority: z.enum(["critical", "high", "medium", "low"]), + description: z.string().min(1), + ownership: z.enum([ + "agent-team", + "platform-team", + "prompt-engineer", + "scenario-author", + ]), + relatedPatterns: z.array(z.string().min(1)), + suggestedApproach: z.string().min(1), +}); + +/** Prioritized action lists grouped by remediation intent. */ +export const actionListSchema = z.object({ + fix: z.array(actionItemSchema), + improve: z.array(actionItemSchema), + investigate: z.array(actionItemSchema), +}); + +/** Complete taxonomy document produced by the taxonomy post-processor. */ +export const taxonomySchema = z.object({ + meta: taxonomyMetaSchema, + scorecard: scorecardSchema, + behaviorAnalysis: behaviorAnalysisSchema, + actionList: actionListSchema, +}); + +/** Inferred TypeScript type for the taxonomy document. */ +export type TaxonomyDocument = z.infer; diff --git a/packages/shared/src/types/types.ts b/packages/shared/src/types/types.ts index c23444417..77fcb57b4 100644 --- a/packages/shared/src/types/types.ts +++ b/packages/shared/src/types/types.ts @@ -206,6 +206,14 @@ export interface QueueMessagePayload { runId?: string; } +/** Status of a single post-process handler for a specific run. */ +export interface HandlerRunStatus { + status: "queued" | "processing" | "done" | "failed"; + version?: number; + updatedAt?: Date; + error?: string; +} + /** * RunState — represents one execution attempt of a request. * @@ -270,12 +278,11 @@ export interface RunState { aiCallCount?: number; rawChatUrl?: string; rawChatFormat?: string; - /** Version of the post-processor that last successfully processed this run. - * Used by the scheduler to detect runs needing (re-)processing when the - * post-processor version advances. */ + /** Per-handler post-processing status. Keys are handler IDs (e.g. "pp-atif", "pp-taxonomy", "pp-report"). */ + handlerStatus?: Record; + /** @deprecated Use handlerStatus["pp-atif"].version instead. Kept for migration compatibility. */ postProcessorVersion?: number; - /** Lifecycle status of post-processing for this run. Prevents duplicate - * enqueuing and tracks processing progress. */ + /** @deprecated Use handlerStatus["pp-atif"].status instead. Kept for migration compatibility. */ postProcessorStatus?: "queued" | "processing" | "done" | "failed"; } @@ -287,6 +294,17 @@ export interface RunHistoryDocument extends RunState { requestId: string; // FK → RequestDocument._id } +/** A post-process handler registered in the `services` collection. */ +export interface HandlerServiceDocument { + _id: string; + type: "post-process-handler"; + version: number; + queue: string; + selector: string; + autoBackfill: boolean; + dependsOn: string[]; +} + /** * Field names whose values move from `RequestDocument` (top-level, legacy * shape) into `RequestDocument.run: RunState` (new shape introduced for diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 339c191ba..a7903fc00 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -705,6 +705,31 @@ importers: specifier: ^5.6.2 version: 5.9.3 + apps/workers/taxonomy: + dependencies: + '@azure/storage-queue': + specifier: ^12.25.0 + version: 12.29.0 + '@github/copilot-sdk': + specifier: ^0.1.17 + version: 0.1.23 + dotenv: + specifier: ^16.4.5 + version: 16.6.1 + shared: + specifier: workspace:* + version: link:../../../packages/shared + devDependencies: + '@types/node': + specifier: ^22.7.0 + version: 22.19.10 + tsx: + specifier: ^4.19.0 + version: 4.21.0 + typescript: + specifier: ^5.6.2 + version: 5.9.3 + packages/copilot-driver-ext: devDependencies: '@types/node': From e9bf6ad106cb0cd8135164ca0220a2d69908d3fd Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Tue, 9 Jun 2026 02:15:31 -0700 Subject: [PATCH 002/210] feat: add taxonomy API route and archive bundling (Phase 3) - Add GET /api/v1/requests/:id/taxonomy endpoint - Bundle taxonomy.json in run download tar.gz archive - Add taxonomyUrl to RunState type and request schema - Update taxonomy worker to persist run.taxonomyUrl - Update OpenAPI snapshot and post-processing docs Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../openapi-snapshot.test.ts.snap | 63 +++++++++++ apps/api/src/archive-har.test.ts | 41 +++++++ apps/api/src/archive-har.ts | 29 ++++- apps/api/src/index.ts | 2 + apps/api/src/routes/requests/taxonomy.test.ts | 107 ++++++++++++++++++ apps/api/src/routes/requests/taxonomy.ts | 30 +++++ .../taxonomy/src/taxonomy-queue-processor.ts | 1 + docs/architecture/post-processing.md | 7 +- packages/shared/src/schemas/request.ts | 1 + packages/shared/src/types/types.ts | 2 + 10 files changed, 281 insertions(+), 2 deletions(-) create mode 100644 apps/api/src/routes/requests/taxonomy.test.ts create mode 100644 apps/api/src/routes/requests/taxonomy.ts diff --git a/apps/api/src/__snapshots__/openapi-snapshot.test.ts.snap b/apps/api/src/__snapshots__/openapi-snapshot.test.ts.snap index 7912955e3..16ee7fc6d 100644 --- a/apps/api/src/__snapshots__/openapi-snapshot.test.ts.snap +++ b/apps/api/src/__snapshots__/openapi-snapshot.test.ts.snap @@ -2313,6 +2313,9 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` ], "type": "string", }, + "taxonomyUrl": { + "type": "string", + }, "tokenUsage": { "$ref": "#/components/schemas/TokenUsage", }, @@ -7981,6 +7984,40 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` ], }, }, + "/api/v1/requests/{id}/runs/{runId}/taxonomy": { + "get": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "string", + }, + }, + { + "in": "path", + "name": "runId", + "required": true, + "schema": { + "type": "string", + }, + }, + ], + "responses": { + "200": { + "description": "Taxonomy v1 JSON document (scorecard, behavior analysis, action list)", + }, + "404": { + "description": "Not found — taxonomy not yet generated", + }, + }, + "summary": "Download taxonomy JSON for a specific attempt", + "tags": [ + "Requests", + ], + }, + }, "/api/v1/requests/{id}/runs/{runId}/tool-calls": { "get": { "parameters": [ @@ -8083,6 +8120,32 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` ], }, }, + "/api/v1/requests/{id}/taxonomy": { + "get": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "string", + }, + }, + ], + "responses": { + "200": { + "description": "Taxonomy v1 JSON document (scorecard, behavior analysis, action list)", + }, + "404": { + "description": "Not found — taxonomy not yet generated", + }, + }, + "summary": "Download taxonomy JSON for the run", + "tags": [ + "Requests", + ], + }, + }, "/api/v1/requests/{id}/tool-calls": { "get": { "parameters": [ diff --git a/apps/api/src/archive-har.test.ts b/apps/api/src/archive-har.test.ts index f83d846ac..51d5e36f2 100644 --- a/apps/api/src/archive-har.test.ts +++ b/apps/api/src/archive-har.test.ts @@ -99,6 +99,17 @@ describe("rewriteHarUrlsForArchive", () => { expect(result.run!.turns![1].toolCallsUrl).toBe("iteration-2.tool-calls.jsonl"); expect(result.run!.turns![2].toolCallsUrl).toBeUndefined(); }); + + it("rewrites run.taxonomyUrl to taxonomy.json", () => { + const resource = { + run: { + taxonomyUrl: "https://storage.blob.core.windows.net/snapshots/abc123/runs/attempt-1/taxonomy.json", + turns: [], + }, + }; + const result = rewriteHarUrlsForArchive(resource); + expect(result.run!.taxonomyUrl).toBe("taxonomy.json"); + }); }); // --- blobNameFromSnapshotsUrl --- @@ -844,4 +855,34 @@ describe("packRunIntoTar", () => { expect(yaml).toContain("iteration-1.chat-result.json"); expect(yaml).not.toContain("blob.core.windows.net"); }); + + it("bundles run-level taxonomy.json and rewrites taxonomyUrl", async () => { + const { pack } = await import("tar-stream"); + const p = pack(); + const taxonomyData = Buffer.from('{"topics":["agent"]}'); + const container = makeMockBlobContainer({ + "run-010/runs/attempt-1/taxonomy.json": { body: taxonomyData, length: taxonomyData.length }, + }); + + const run: ArchivableRun = { + _id: "run-010", + run: { + taxonomyUrl: "https://storage.blob.core.windows.net/snapshots/run-010/runs/attempt-1/taxonomy.json", + turns: [], + }, + }; + + const entriesPromise = collectPackEntries(p); + await packRunIntoTar(p, run, container, "run-010", () => true); + p.finalize(); + + const entries = await entriesPromise; + const names = entries.map(e => e.name); + expect(names).toContain("run-010/taxonomy.json"); + expect(entries.find(e => e.name === "run-010/taxonomy.json")!.data).toEqual(taxonomyData); + + const yaml = entries.find(e => e.name === "run-010/run.yaml")!.data.toString(); + expect(yaml).toContain("taxonomy.json"); + expect(yaml).not.toContain("blob.core.windows.net"); + }); }); diff --git a/apps/api/src/archive-har.ts b/apps/api/src/archive-har.ts index 21f922179..86cfeb1ee 100644 --- a/apps/api/src/archive-har.ts +++ b/apps/api/src/archive-har.ts @@ -41,11 +41,12 @@ export function blobNameFromLogsUrl(url: string): string | null { /** * Deep-clone a run resource and rewrite `harUrl`, `rawChatUrl`, - * `chatResultUrl`, and `toolCallsUrl` fields to relative archive paths. + * `taxonomyUrl`, `chatResultUrl`, and `toolCallsUrl` fields to relative archive paths. * * - `run.harUrl` → `"run.har"` * - Per-turn `harUrl` → `"iteration-{N}.har"` * - `run.rawChatUrl` → `"run.chat-export.json"` + * - `run.taxonomyUrl` → `"taxonomy.json"` * - Per-turn `rawChatUrl` → `"iteration-{N}.chat-export.json"` * - Per-turn `chatResultUrl` → `"iteration-{N}.chat-result.json"` * - Per-turn `toolCallsUrl` → `"iteration-{N}.tool-calls.jsonl"` @@ -54,6 +55,7 @@ export function rewriteHarUrlsForArchive; [key: string]: unknown; }; @@ -66,6 +68,9 @@ export function rewriteHarUrlsForArchive ({ + checkMigrations: vi.fn().mockResolvedValue({ ready: true, applied: ["001", "002"], pending: [] }), +})); + +vi.hoisted(() => { + process.env.STORAGE_CONNECTION_STRING = "DefaultEndpointsProtocol=https;AccountName=mockaccount;AccountKey=bW9jaw==;EndpointSuffix=core.windows.net"; +}); + +vi.mock("../../llm.js", () => ({ isLlmAvailable: vi.fn().mockReturnValue(false) })); +vi.mock("../../prompt-feature-llm.js", () => ({ isLlmAvailable: vi.fn().mockReturnValue(false) })); +vi.mock("../../task-prompt-llm.js", () => ({ isTaskPromptLlmAvailable: vi.fn().mockReturnValue(false) })); + +const { mockDownload, mockGetProperties, mockGetBlockBlobClient, mockGetBlobClient, mockGetContainerClient } = vi.hoisted(() => { + const mockDownload = vi.fn(); + const mockGetProperties = vi.fn(); + const mockGetBlockBlobClient = vi.fn().mockReturnValue({ download: mockDownload, getProperties: mockGetProperties }); + const mockGetBlobClient = vi.fn().mockReturnValue({ download: mockDownload, getProperties: mockGetProperties }); + const mockGetContainerClient = vi.fn().mockReturnValue({ getBlockBlobClient: mockGetBlockBlobClient, getBlobClient: mockGetBlobClient }); + return { mockDownload, mockGetProperties, mockGetBlockBlobClient, mockGetBlobClient, mockGetContainerClient }; +}); + +vi.mock("@azure/storage-blob", async (importOriginal) => { + const original = await importOriginal(); + return { + ...original, + BlobServiceClient: { fromConnectionString: vi.fn().mockReturnValue({ getContainerClient: mockGetContainerClient }) }, + }; +}); + +describe("taxonomy endpoints", () => { + let mocks: ReturnType; + + beforeAll(() => { + mocks = createAllMockDependencies(); + _injectTestDependencies(mocks); + }); + + beforeEach(() => { + vi.clearAllMocks(); + mocks = createAllMockDependencies(); + _injectTestDependencies(mocks); + rewireBlobMocks({ mockDownload, mockGetProperties, mockGetBlockBlobClient, mockGetBlobClient, mockGetContainerClient }); + mockDownload.mockResolvedValue({ readableStreamBody: readableFrom('{"status":"ok"}'), contentLength: 15 }); + mockGetProperties.mockResolvedValue({ contentLength: 15 }); + }); + + describe.each(VARIANTS)("$label", (variant) => { + const taxonomyUrl = (id: string) => variant.url(id) + "taxonomy"; + + it("returns 404 when request not found", async () => { + (mocks.collection.findOne as ReturnType).mockResolvedValue(null); + const res = await supertest(app).get(taxonomyUrl("missing")); + expect(res.status).toBe(404); + expect(res.body).toMatchObject({ error: "Request not found" }); + }); + + it("returns 404 when taxonomyUrl is not set", async () => { + variant.mockRequest(mocks, "req-1", { _id: "run-1", attemptNumber: 1, status: "done" }); + const res = await supertest(app).get(taxonomyUrl("req-1")); + expect(res.status).toBe(404); + expect(res.body).toMatchObject({ error: "Taxonomy not yet generated for this run" }); + }); + + it("returns taxonomy JSON when taxonomyUrl is set", async () => { + variant.mockRequest(mocks, "req-1", { + _id: "run-1", + attemptNumber: 1, + status: "done", + taxonomyUrl: blobUrl("req-1/taxonomy.json"), + }); + + const res = await supertest(app).get(taxonomyUrl("req-1")).buffer(true).parse(rawParser); + expect(res.status).toBe(200); + expect(res.headers["content-type"]).toMatch("application/json"); + expect(res.headers["content-disposition"]).toContain("req-1-taxonomy.json"); + expect(mockGetBlockBlobClient).toHaveBeenCalledWith("req-1/taxonomy.json"); + }); + }); + + it("works with per-run variant", async () => { + RUN_LEVEL.mockRequest(mocks, "req-1", { + _id: "run-1", + attemptNumber: 1, + status: "done", + taxonomyUrl: blobUrl("req-1/runs/run-1/taxonomy.json"), + }); + + const res = await supertest(app).get(RUN_LEVEL.url("req-1") + "taxonomy").buffer(true).parse(rawParser); + expect(res.status).toBe(200); + expect(res.headers["content-disposition"]).toContain("req-1-taxonomy.json"); + expect(mockGetBlockBlobClient).toHaveBeenCalledWith("req-1/runs/run-1/taxonomy.json"); + }); +}); diff --git a/apps/api/src/routes/requests/taxonomy.ts b/apps/api/src/routes/requests/taxonomy.ts new file mode 100644 index 000000000..e74d303f6 --- /dev/null +++ b/apps/api/src/routes/requests/taxonomy.ts @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import type { RouteContext } from "../../route-context.js"; +import { downloadBlobToResponse } from "./blob-helpers.js"; +import { registerArtifactRoutes } from "./artifact-route.js"; + +export function registerRequestsTaxonomyRoutes(ctx: RouteContext): void { + registerArtifactRoutes(ctx, { + path: "taxonomy", + summary: "Download taxonomy JSON for the run", + perRunSummary: "Download taxonomy JSON for a specific attempt", + responseDescription: "Taxonomy v1 JSON document (scorecard, behavior analysis, action list)", + errorResponses: { 404: { description: "Not found — taxonomy not yet generated" } }, + blobNotFoundMessage: "Taxonomy file not found — the blob may have been deleted or is no longer available", + handler: async (ctx, _req, res, targetRun, id) => { + const taxonomyUrl = targetRun.taxonomyUrl; + if (!taxonomyUrl) { + res.status(404).json({ error: "Taxonomy not yet generated for this run" }); + return; + } + + await downloadBlobToResponse(ctx, res, taxonomyUrl, { + contentType: "application/json", + filename: `${id}-taxonomy.json`, + label: "Taxonomy", + }); + }, + }); +} diff --git a/apps/workers/taxonomy/src/taxonomy-queue-processor.ts b/apps/workers/taxonomy/src/taxonomy-queue-processor.ts index db2c7f7e3..29fb3b61a 100644 --- a/apps/workers/taxonomy/src/taxonomy-queue-processor.ts +++ b/apps/workers/taxonomy/src/taxonomy-queue-processor.ts @@ -107,6 +107,7 @@ export class TaxonomyQueueProcessor extends BaseQueueProcessor { _id: requestId } as never, { $set: { + [`run.taxonomyUrl`]: taxonomyUrl, [`run.handlerStatus.${HANDLER_ID}.status`]: "done", [`run.handlerStatus.${HANDLER_ID}.version`]: HANDLER_VERSION, [`run.handlerStatus.${HANDLER_ID}.updatedAt`]: new Date(), diff --git a/docs/architecture/post-processing.md b/docs/architecture/post-processing.md index 7bdf7e2e8..df326d5e4 100644 --- a/docs/architecture/post-processing.md +++ b/docs/architecture/post-processing.md @@ -61,16 +61,21 @@ The taxonomy handler (`apps/workers/taxonomy/`) consumes messages from the dedic atif.trajectory.json iteration-2/ atif.trajectory.json + taxonomy.json ``` +The completed run stores the taxonomy blob URL on `run.taxonomyUrl`. + ### API Endpoints | Endpoint | Description | | --- | --- | | `GET /api/v1/requests/:id/atif?iteration=N` | Download ATIF for the latest run | | `GET /api/v1/requests/:id/runs/:runId/atif?iteration=N` | Download ATIF for a specific run | +| `GET /api/v1/requests/:id/taxonomy` | Download taxonomy JSON for the latest run | +| `GET /api/v1/requests/:id/runs/:runId/taxonomy` | Download taxonomy JSON for a specific run | -The `iteration` query parameter is mandatory. ATIF files are also included in archive exports as `iteration-{N}.atif.trajectory.json`. +The `iteration` query parameter is mandatory only for the ATIF endpoints. ATIF files are also included in archive exports as `iteration-{N}.atif.trajectory.json`. ## Handler Interface diff --git a/packages/shared/src/schemas/request.ts b/packages/shared/src/schemas/request.ts index bdcf6cc88..ea6f3d4da 100644 --- a/packages/shared/src/schemas/request.ts +++ b/packages/shared/src/schemas/request.ts @@ -173,6 +173,7 @@ export const RunStateSchema = z podName: z.string().optional(), }).optional(), harUrl: z.string().optional(), + taxonomyUrl: z.string().optional(), videoUrls: z.array(z.string()).optional(), setupVideoUrls: z.array(z.string()).optional(), tokenUsage: TokenUsageSchema.optional(), diff --git a/packages/shared/src/types/types.ts b/packages/shared/src/types/types.ts index 77fcb57b4..ccd7d7805 100644 --- a/packages/shared/src/types/types.ts +++ b/packages/shared/src/types/types.ts @@ -272,6 +272,7 @@ export interface RunState { podName?: string; }; harUrl?: string; + taxonomyUrl?: string; videoUrls?: string[]; setupVideoUrls?: string[]; tokenUsage?: TokenUsage; @@ -323,6 +324,7 @@ export const RUN_STATE_FIELD_NAMES = [ "lastHeartbeatAt", "worker", "harUrl", + "taxonomyUrl", "videoUrls", "setupVideoUrls", "tokenUsage", From 227328624e3f91c61abaef1331af6584cef0207b Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Tue, 9 Jun 2026 02:38:12 -0700 Subject: [PATCH 003/210] fix: taxonomy handler Dockerfile and docker-compose dev setup - Use multi-stage Dockerfile matching report-generator pattern - Add tsconfig.base.json, proper COPY layers, --prod install in prod stage - Add dev stage for hot-reload with tsx watch - Add taxonomy-handler to docker-compose.dev.yml watch config - Add --profile taxonomy to docker:dev:copilot and docker:dev:all scripts Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- apps/workers/taxonomy/Dockerfile | 55 ++++++++++++++++++++++++-------- docker-compose.dev.yml | 16 ++++++++++ package.json | 4 +-- 3 files changed, 60 insertions(+), 15 deletions(-) diff --git a/apps/workers/taxonomy/Dockerfile b/apps/workers/taxonomy/Dockerfile index 9e0792411..6114e03a8 100644 --- a/apps/workers/taxonomy/Dockerfile +++ b/apps/workers/taxonomy/Dockerfile @@ -1,19 +1,48 @@ -FROM node:22-alpine AS builder +FROM node:22.22.0-slim AS builder + +RUN corepack enable && corepack prepare pnpm@10.29.1 --activate + WORKDIR /app -COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./ -COPY packages/shared/package.json packages/shared/ -COPY apps/workers/taxonomy/package.json apps/workers/taxonomy/ -RUN corepack enable && pnpm install --frozen-lockfile -COPY packages/shared packages/shared -COPY apps/workers/taxonomy apps/workers/taxonomy + +COPY package.json pnpm-workspace.yaml pnpm-lock.yaml ./ +COPY tsconfig.base.json ./ +COPY packages/shared/package.json ./packages/shared/ +COPY apps/workers/taxonomy/package.json ./apps/workers/taxonomy/ + +RUN pnpm install --frozen-lockfile + +COPY packages/shared/tsconfig.json ./packages/shared/ +COPY packages/shared/src ./packages/shared/src/ +COPY apps/workers/taxonomy/tsconfig.json ./apps/workers/taxonomy/ +COPY apps/workers/taxonomy/src ./apps/workers/taxonomy/src/ + RUN pnpm --filter shared build && pnpm --filter taxonomy-handler build -FROM node:22-alpine +# --- Dev stage: hot reload with tsx watch --- +FROM builder AS dev +ENV NODE_ENV=development +ENV SERVICE_DIR=workers/taxonomy +COPY scripts/dev-entrypoint.sh /app/scripts/dev-entrypoint.sh +EXPOSE 80 +ENV PORT=80 +CMD ["/app/scripts/dev-entrypoint.sh"] + +# --- Production stage --- +FROM node:22.22.0-slim + +RUN corepack enable && corepack prepare pnpm@10.29.1 --activate + WORKDIR /app -COPY --from=builder /app/node_modules ./node_modules -COPY --from=builder /app/packages/shared/dist ./packages/shared/dist -COPY --from=builder /app/packages/shared/package.json ./packages/shared/ -COPY --from=builder /app/apps/workers/taxonomy/dist ./apps/workers/taxonomy/dist -COPY --from=builder /app/apps/workers/taxonomy/package.json ./apps/workers/taxonomy/ + +COPY package.json pnpm-workspace.yaml pnpm-lock.yaml ./ +COPY packages/shared/package.json ./packages/shared/ +COPY apps/workers/taxonomy/package.json ./apps/workers/taxonomy/ + +RUN pnpm install --frozen-lockfile --prod + +COPY --from=builder /app/packages/shared/dist ./packages/shared/dist/ +COPY --from=builder /app/apps/workers/taxonomy/dist ./apps/workers/taxonomy/dist/ + WORKDIR /app/apps/workers/taxonomy + CMD ["node", "dist/index.js"] diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml index aac741607..c571a727d 100644 --- a/docker-compose.dev.yml +++ b/docker-compose.dev.yml @@ -180,6 +180,22 @@ services: - action: rebuild path: ./pnpm-lock.yaml + taxonomy-handler: + build: + target: dev + develop: + watch: + - action: sync + path: ./apps/workers/taxonomy/src + target: /app/apps/workers/taxonomy/src + - action: sync + path: ./packages/shared/src + target: /app/packages/shared/src + - action: rebuild + path: ./apps/workers/taxonomy/package.json + - action: rebuild + path: ./pnpm-lock.yaml + register-version-post-processor: build: target: dev diff --git a/package.json b/package.json index 46b946a51..62ce2760d 100644 --- a/package.json +++ b/package.json @@ -25,9 +25,9 @@ "docker:up:portal": "scripts/worktree-env.sh && scripts/dev-compose.sh --profile portal up --build", "docker:dev": "scripts/worktree-env.sh && COMPOSE_EXPERIMENTAL_WATCH_POLL=1 scripts/dev-compose.sh -f docker-compose.yml -f docker-compose.dev.yml up --build --watch", "docker:dev:claude-code": "scripts/worktree-env.sh && GIT_BRANCH=$(git rev-parse --abbrev-ref HEAD) COMPOSE_EXPERIMENTAL_WATCH_POLL=1 scripts/dev-compose.sh --env-file .env --env-file apps/workers/coder-acp-claude-code/versions.env -f docker-compose.yml -f docker-compose.dev.yml --profile claude-code --profile report --profile post-processor --profile portal up --build --watch", - "docker:dev:copilot": "scripts/worktree-env.sh && GIT_BRANCH=$(git rev-parse --abbrev-ref HEAD) COMPOSE_EXPERIMENTAL_WATCH_POLL=1 scripts/dev-compose.sh --env-file .env --env-file apps/workers/coder-acp-copilot/versions.env -f docker-compose.yml -f docker-compose.dev.yml --profile copilot --profile report --profile post-processor --profile portal up --build --watch", + "docker:dev:copilot": "scripts/worktree-env.sh && GIT_BRANCH=$(git rev-parse --abbrev-ref HEAD) COMPOSE_EXPERIMENTAL_WATCH_POLL=1 scripts/dev-compose.sh --env-file .env --env-file apps/workers/coder-acp-copilot/versions.env -f docker-compose.yml -f docker-compose.dev.yml --profile copilot --profile report --profile post-processor --profile taxonomy --profile portal up --build --watch", "docker:dev:portal": "scripts/worktree-env.sh && GIT_BRANCH=$(git rev-parse --abbrev-ref HEAD) COMPOSE_EXPERIMENTAL_WATCH_POLL=1 scripts/dev-compose.sh -f docker-compose.yml -f docker-compose.dev.yml --profile portal up --build --watch", - "docker:dev:all": "scripts/worktree-env.sh && GIT_BRANCH=$(git rev-parse --abbrev-ref HEAD) COMPOSE_EXPERIMENTAL_WATCH_POLL=1 scripts/dev-compose.sh --env-file .env --env-file apps/workers/coder-acp-copilot/versions.env --env-file apps/workers/coder-acp-claude-code/versions.env -f docker-compose.yml -f docker-compose.dev.yml --profile claude-code --profile copilot --profile report --profile post-processor --profile portal up --build --watch", + "docker:dev:all": "scripts/worktree-env.sh && GIT_BRANCH=$(git rev-parse --abbrev-ref HEAD) COMPOSE_EXPERIMENTAL_WATCH_POLL=1 scripts/dev-compose.sh --env-file .env --env-file apps/workers/coder-acp-copilot/versions.env --env-file apps/workers/coder-acp-claude-code/versions.env -f docker-compose.yml -f docker-compose.dev.yml --profile claude-code --profile copilot --profile report --profile post-processor --profile taxonomy --profile portal up --build --watch", "docker:dev:build": "scripts/worktree-env.sh && GIT_BRANCH=$(git rev-parse --abbrev-ref HEAD) scripts/dev-compose.sh --env-file .env --env-file apps/workers/coder-acp-copilot/versions.env --env-file apps/workers/coder-acp-claude-code/versions.env -f docker-compose.yml -f docker-compose.dev.yml --profile claude-code --profile copilot --profile report --profile portal build", "docker:down": "scripts/worktree-env.sh && scripts/dev-compose.sh --env-file .env --env-file apps/workers/coder-acp-copilot/versions.env --env-file apps/workers/coder-acp-claude-code/versions.env --profile claude-code --profile copilot --profile report --profile portal down --volumes", "docker:build": "scripts/worktree-env.sh && scripts/dev-compose.sh --env-file .env --env-file apps/workers/coder-acp-copilot/versions.env --env-file apps/workers/coder-acp-claude-code/versions.env --profile claude-code --profile copilot --profile report build", From 4507fb81d05d70ec4d11199238e0f05440338c76 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Tue, 9 Jun 2026 10:03:52 -0700 Subject: [PATCH 004/210] feat: add taxonomy tab to portal run detail view Adds a Taxonomy tab to the run detail page that shows: - Scorecard with visual score bars per dimension - Behavior analysis patterns with impact badges - Action items with priority indicators - Collapsible raw JSON view The tab only appears when taxonomy data is available (run.taxonomyUrl set). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- apps/portal/src/components/TaxonomyTab.tsx | 248 +++++++++++++++++++++ apps/portal/src/lib/api.ts | 10 + apps/portal/src/pages/RunDetail.tsx | 10 + apps/portal/src/types.ts | 1 + 4 files changed, 269 insertions(+) create mode 100644 apps/portal/src/components/TaxonomyTab.tsx diff --git a/apps/portal/src/components/TaxonomyTab.tsx b/apps/portal/src/components/TaxonomyTab.tsx new file mode 100644 index 000000000..e97c8c8c4 --- /dev/null +++ b/apps/portal/src/components/TaxonomyTab.tsx @@ -0,0 +1,248 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { useQuery } from "@tanstack/react-query"; +import { api } from "@/lib/api"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Loader2, Download, ChevronDown, ChevronRight } from "lucide-react"; +import { useState } from "react"; + +interface TaxonomyDimension { + name: string; + score: number; + maxScore: number; + justification: string; +} + +interface BehaviorPattern { + id: string; + category: string; + observation: string; + evidence: string[]; + impact: "positive" | "negative" | "neutral"; +} + +interface ActionItem { + id: string; + priority: "high" | "medium" | "low"; + title: string; + description: string; + category: string; +} + +interface TaxonomyData { + meta?: { + schemaVersion?: string; + generatedAt?: string; + requestId?: string; + runId?: string; + model?: string; + }; + scorecard?: { + overall?: number; + dimensions?: TaxonomyDimension[]; + }; + behaviorAnalysis?: { + patterns?: BehaviorPattern[]; + }; + actionList?: { + items?: ActionItem[]; + }; +} + +function ScoreBar({ score, maxScore }: { score: number; maxScore: number }) { + const pct = Math.round((score / maxScore) * 100); + const color = pct >= 80 ? "bg-green-500" : pct >= 50 ? "bg-yellow-500" : "bg-red-500"; + return ( +
+
+
+
+ {score}/{maxScore} +
+ ); +} + +function ImpactBadge({ impact }: { impact: string }) { + const variant = impact === "positive" ? "default" : impact === "negative" ? "destructive" : "secondary"; + return {impact}; +} + +function PriorityBadge({ priority }: { priority: string }) { + const colors: Record = { + high: "bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300", + medium: "bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300", + low: "bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300", + }; + return {priority}; +} + +function CollapsibleSection({ title, defaultOpen = true, children }: { title: string; defaultOpen?: boolean; children: React.ReactNode }) { + const [open, setOpen] = useState(defaultOpen); + return ( +
+ + {open &&
{children}
} +
+ ); +} + +export function TaxonomyTab({ runId, attemptRunId }: { runId: string; attemptRunId?: string }) { + const url = attemptRunId ? api.runTaxonomyUrl(runId, attemptRunId) : api.taxonomyUrl(runId); + + const { data: taxonomy, isLoading, error } = useQuery({ + queryKey: ["run-taxonomy", runId, attemptRunId], + queryFn: async () => { + const res = await fetch(url); + if (!res.ok) { + if (res.status === 404) return null; + throw new Error(`Failed to fetch taxonomy: ${res.statusText}`); + } + return res.json(); + }, + }); + + if (isLoading) { + return ( +
+ + Loading taxonomy… +
+ ); + } + + if (error) { + return ( +
+

Failed to load taxonomy: {(error as Error).message}

+
+ ); + } + + if (!taxonomy) { + return ( +
+

Taxonomy not yet generated for this run.

+

It will appear here once post-processing completes.

+
+ ); + } + + const { meta, scorecard, behaviorAnalysis, actionList } = taxonomy; + + return ( +
+ {/* Header with download */} +
+
+

Run Taxonomy

+ {meta?.generatedAt && ( +

+ Generated {new Date(meta.generatedAt).toLocaleString()} + {meta.model && <> · Model: {meta.model}} +

+ )} +
+ +
+ + {/* Scorecard */} + {scorecard && ( + + + + Scorecard + {scorecard.overall !== undefined && ( + {scorecard.overall}% + )} + + + + {scorecard.dimensions?.map((dim) => ( +
+
+ {dim.name} +
+ +

{dim.justification}

+
+ ))} +
+
+ )} + + {/* Behavior Analysis */} + {behaviorAnalysis?.patterns && behaviorAnalysis.patterns.length > 0 && ( + + + + Behavior Analysis ({behaviorAnalysis.patterns.length}) + + + + +
+ {behaviorAnalysis.patterns.map((pattern) => ( +
+
+ {pattern.category} + +
+

{pattern.observation}

+ {pattern.evidence.length > 0 && ( +
    + {pattern.evidence.map((e, i) =>
  • {e}
  • )} +
+ )} +
+ ))} +
+
+
+
+ )} + + {/* Action List */} + {actionList?.items && actionList.items.length > 0 && ( + + + + Action Items ({actionList.items.length}) + + + + +
+ {actionList.items.map((item) => ( +
+ +
+

{item.title}

+

{item.description}

+ {item.category} +
+
+ ))} +
+
+
+
+ )} + + {/* Raw JSON fallback — collapsed by default */} + +
+          {JSON.stringify(taxonomy, null, 2)}
+        
+
+
+ ); +} diff --git a/apps/portal/src/lib/api.ts b/apps/portal/src/lib/api.ts index ea16aeabb..144b41c73 100644 --- a/apps/portal/src/lib/api.ts +++ b/apps/portal/src/lib/api.ts @@ -217,6 +217,16 @@ export const api = { return `${BASE}/requests/${id}/atif${qs}`; }, + /** Get taxonomy JSON URL for a request (latest run) */ + taxonomyUrl: (id: string): string => { + return `${BASE}/requests/${id}/taxonomy`; + }, + + /** Get taxonomy JSON URL for a specific attempt */ + runTaxonomyUrl: (requestId: string, runId: string): string => { + return `${BASE}/requests/${requestId}/runs/${runId}/taxonomy`; + }, + /** Download a batch archive of multiple runs as a single .tar.gz */ batchArchive: async (ids: string[]): Promise => { const resp = await fetch(`${BASE}/requests/archive`, { diff --git a/apps/portal/src/pages/RunDetail.tsx b/apps/portal/src/pages/RunDetail.tsx index ee42b2467..789e74743 100644 --- a/apps/portal/src/pages/RunDetail.tsx +++ b/apps/portal/src/pages/RunDetail.tsx @@ -24,6 +24,7 @@ import { CriteriaGraphView } from "@/components/CriteriaGraphView"; import { HarNetworkViewer } from "@/components/HarNetworkViewer"; import { ConversationView } from "@/components/ConversationView"; import { VideoPlayer } from "@/components/VideoPlayer"; +import { TaxonomyTab } from "@/components/TaxonomyTab"; import { useLogStream } from "@/hooks/use-log-stream"; import { useAllTurnsToolCalls } from "@/hooks/useHarExtraction"; import { MarkdownRenderer } from "@/components/MarkdownRenderer"; @@ -325,6 +326,7 @@ export function RunDetail() { } const hasHarData = !!(activeRun?.harUrl || activeRun?.turns?.some(t => t.harUrl)); + const hasTaxonomy = !!activeRun?.taxonomyUrl; const hasVideoData = !!(activeRun?.videoUrls?.length || activeRun?.setupVideoUrls?.length || activeRun?.turns?.some(t => t.videoUrls?.length)); const videoCount = (activeRun?.setupVideoUrls?.length ?? 0) + (activeRun?.videoUrls?.length ?? 0) @@ -652,6 +654,7 @@ export function RunDetail() { )} {hasHarData && Network} {hasHarData && Tool Calls} + {hasTaxonomy && Taxonomy} {hasVideoData && } Logs @@ -684,6 +687,13 @@ export function RunDetail() { )} + {/* Taxonomy tab — structured scorecard + behavior analysis + action items */} + {hasTaxonomy && ( + + + + )} + {/* Video tab — session recording player */} {hasVideoData && ( diff --git a/apps/portal/src/types.ts b/apps/portal/src/types.ts index 7b7e4c0f2..019f77a9f 100644 --- a/apps/portal/src/types.ts +++ b/apps/portal/src/types.ts @@ -112,6 +112,7 @@ export interface RunState { resumedAt?: string; postProcessorVersion?: number; postProcessorStatus?: "queued" | "processing" | "done" | "failed"; + taxonomyUrl?: string; } export interface Run { From 3756ccc2f7ac6646a1e11167aa8f3cbf233caccf Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Tue, 9 Jun 2026 10:13:14 -0700 Subject: [PATCH 005/210] refactor: move handler registration from migration to worker registration jobs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each post-processing handler now owns its own service entry registration via a register-version.ts script (run as K8s Job on deploy): - pp-atif: apps/workers/post-processor/src/register-version.ts - pp-taxonomy: apps/workers/taxonomy/src/register-version.ts - pp-report: apps/workers/report-generator/src/register-version.ts Migration 018 is reduced to only cleaning up the legacy 'post-processor' entry. Each handler defines its own dependencies (dependsOn), queue, version, and selector — decoupling the DAG topology from a single migration. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../post-processor/src/register-version.ts | 21 +++-- apps/workers/report-generator/package.json | 3 +- .../report-generator/src/register-version.ts | 51 ++++++++++++ apps/workers/taxonomy/package.json | 3 +- apps/workers/taxonomy/src/register-version.ts | 51 ++++++++++++ docker-compose.dev.yml | 8 ++ docker-compose.yml | 41 ++++++++-- .../018-migrate-services-to-handler-dag.ts | 81 +++---------------- pnpm-lock.yaml | 6 ++ 9 files changed, 183 insertions(+), 82 deletions(-) create mode 100644 apps/workers/report-generator/src/register-version.ts create mode 100644 apps/workers/taxonomy/src/register-version.ts diff --git a/apps/workers/post-processor/src/register-version.ts b/apps/workers/post-processor/src/register-version.ts index 6eb0ca889..1d3e062e3 100644 --- a/apps/workers/post-processor/src/register-version.ts +++ b/apps/workers/post-processor/src/register-version.ts @@ -3,8 +3,9 @@ /** * Standalone script run by the K8s Job on each deployment. - * Writes the current post-processor version to MongoDB so the scheduler - * can detect runs needing (re-)processing. + * Registers the post-processor (pp-atif handler) in the services collection + * with its version, queue, and dependency information so the scheduler + * can orchestrate the DAG-based post-processing pipeline. */ import "dotenv/config"; import { MongoClient } from "mongodb"; @@ -24,13 +25,23 @@ async function main(): Promise { .db(MONGO_DATABASE) .collection("services") .updateOne( - { _id: "post-processor" } as any, - { $set: { version: POST_PROCESSOR_VERSION, updatedAt: new Date() } }, + { _id: "pp-atif" } as any, + { + $set: { + type: "post-process-handler", + version: POST_PROCESSOR_VERSION, + queue: "post-processor-queue", + selector: "atif", + autoBackfill: true, + dependsOn: [], + updatedAt: new Date(), + }, + }, { upsert: true }, ); await mongo.close(); - console.log(`[register-version] Registered post-processor version: ${POST_PROCESSOR_VERSION}`); + console.log(`[register-version] Registered pp-atif handler version: ${POST_PROCESSOR_VERSION}`); } main().catch((err) => { diff --git a/apps/workers/report-generator/package.json b/apps/workers/report-generator/package.json index d296fc738..367bdb307 100644 --- a/apps/workers/report-generator/package.json +++ b/apps/workers/report-generator/package.json @@ -13,7 +13,8 @@ "shared": "workspace:*", "@azure/storage-queue": "^12.25.0", "@github/copilot-sdk": "^0.1.17", - "dotenv": "^16.4.5" + "dotenv": "^16.4.5", + "mongodb": "^6.10.0" }, "devDependencies": { "@types/node": "^22.7.0", diff --git a/apps/workers/report-generator/src/register-version.ts b/apps/workers/report-generator/src/register-version.ts new file mode 100644 index 000000000..ed423546b --- /dev/null +++ b/apps/workers/report-generator/src/register-version.ts @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * Standalone script run by the K8s Job on each deployment. + * Registers the report-generator handler in the services collection + * with its version, queue, and dependency information so the scheduler + * can orchestrate the DAG-based post-processing pipeline. + */ +import "dotenv/config"; +import { MongoClient } from "mongodb"; + +const REPORT_HANDLER_VERSION = 1; + +const MONGO_URI = + process.env.MONGO_CONNECTION_STRING || + process.env.AZURE_COSMOS_CONNECTION_STRING || + "mongodb://localhost:27017"; +const MONGO_DATABASE = process.env.MONGO_DATABASE || "requests-db"; + +async function main(): Promise { + const mongo = new MongoClient(MONGO_URI); + await mongo.connect(); + + await mongo + .db(MONGO_DATABASE) + .collection("services") + .updateOne( + { _id: "pp-report" } as any, + { + $set: { + type: "post-process-handler", + version: REPORT_HANDLER_VERSION, + queue: "report-queue", + selector: "report", + autoBackfill: false, + dependsOn: ["pp-atif", "pp-taxonomy"], + updatedAt: new Date(), + }, + }, + { upsert: true }, + ); + + await mongo.close(); + console.log(`[register-version] Registered pp-report handler version: ${REPORT_HANDLER_VERSION}`); +} + +main().catch((err) => { + console.error("[register-version] Fatal error:", err); + process.exit(1); +}); diff --git a/apps/workers/taxonomy/package.json b/apps/workers/taxonomy/package.json index aacbfc4f1..1f496a50c 100644 --- a/apps/workers/taxonomy/package.json +++ b/apps/workers/taxonomy/package.json @@ -13,7 +13,8 @@ "shared": "workspace:*", "@azure/storage-queue": "^12.25.0", "@github/copilot-sdk": "^0.1.17", - "dotenv": "^16.4.5" + "dotenv": "^16.4.5", + "mongodb": "^6.10.0" }, "devDependencies": { "@types/node": "^22.7.0", diff --git a/apps/workers/taxonomy/src/register-version.ts b/apps/workers/taxonomy/src/register-version.ts new file mode 100644 index 000000000..e30425c35 --- /dev/null +++ b/apps/workers/taxonomy/src/register-version.ts @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * Standalone script run by the K8s Job on each deployment. + * Registers the taxonomy handler in the services collection + * with its version, queue, and dependency information so the scheduler + * can orchestrate the DAG-based post-processing pipeline. + */ +import "dotenv/config"; +import { MongoClient } from "mongodb"; + +const TAXONOMY_HANDLER_VERSION = 1; + +const MONGO_URI = + process.env.MONGO_CONNECTION_STRING || + process.env.AZURE_COSMOS_CONNECTION_STRING || + "mongodb://localhost:27017"; +const MONGO_DATABASE = process.env.MONGO_DATABASE || "requests-db"; + +async function main(): Promise { + const mongo = new MongoClient(MONGO_URI); + await mongo.connect(); + + await mongo + .db(MONGO_DATABASE) + .collection("services") + .updateOne( + { _id: "pp-taxonomy" } as any, + { + $set: { + type: "post-process-handler", + version: TAXONOMY_HANDLER_VERSION, + queue: "pp-taxonomy-queue", + selector: "taxonomy", + autoBackfill: false, + dependsOn: ["pp-atif"], + updatedAt: new Date(), + }, + }, + { upsert: true }, + ); + + await mongo.close(); + console.log(`[register-version] Registered pp-taxonomy handler version: ${TAXONOMY_HANDLER_VERSION}`); +} + +main().catch((err) => { + console.error("[register-version] Fatal error:", err); + process.exit(1); +}); diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml index c571a727d..bdfd84780 100644 --- a/docker-compose.dev.yml +++ b/docker-compose.dev.yml @@ -200,6 +200,14 @@ services: build: target: dev + register-version-taxonomy: + build: + target: dev + + register-version-report-generator: + build: + target: dev + post-processor: build: target: dev diff --git a/docker-compose.yml b/docker-compose.yml index a4503d104..9b56ad1b0 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -140,7 +140,7 @@ services: timeout: 5s retries: 5 - # Creates the 'har' blob container and handler queues in Azurite. + # Creates the 'har' blob container in Azurite. azurite-init: image: mcr.microsoft.com/azure-cli:2.68.0 restart: "no" @@ -148,12 +148,9 @@ services: azurite: condition: service_healthy environment: - AZURE_STORAGE_CONNECTION_STRING: "DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;QueueEndpoint=http://azurite:10001/devstoreaccount1;BlobEndpoint=http://azurite:10000/devstoreaccount1;" + AZURE_STORAGE_CONNECTION_STRING: "DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://azurite:10000/devstoreaccount1;" command: > - sh -c "az storage container create --name har --connection-string \"$$AZURE_STORAGE_CONNECTION_STRING\" || true && - az storage queue create --name report-queue --connection-string \"$$AZURE_STORAGE_CONNECTION_STRING\" || true && - az storage queue create --name post-processor-queue --connection-string \"$$AZURE_STORAGE_CONNECTION_STRING\" || true && - az storage queue create --name pp-taxonomy-queue --connection-string \"$$AZURE_STORAGE_CONNECTION_STRING\" || true" + sh -c "az storage container create --name har --connection-string \"$$AZURE_STORAGE_CONNECTION_STRING\" || true" # =========================================================================== # Application services @@ -642,6 +639,8 @@ services: condition: service_healthy api: condition: service_started + register-version-report-generator: + condition: service_completed_successfully taxonomy-handler: build: @@ -670,6 +669,36 @@ services: condition: service_started scheduler: condition: service_started + register-version-taxonomy: + condition: service_completed_successfully + + register-version-taxonomy: + build: + context: . + dockerfile: apps/workers/taxonomy/Dockerfile + profiles: [taxonomy, all] + environment: + <<: *common-env + depends_on: + mongodb: + condition: service_healthy + required: false + restart: "no" + entrypoint: ["npx", "tsx", "apps/workers/taxonomy/src/register-version.ts"] + + register-version-report-generator: + build: + context: . + dockerfile: apps/workers/report-generator/Dockerfile + profiles: [report] + environment: + <<: *common-env + depends_on: + mongodb: + condition: service_healthy + required: false + restart: "no" + entrypoint: ["npx", "tsx", "apps/workers/report-generator/src/register-version.ts"] register-version-post-processor: build: diff --git a/packages/db-migrations/src/migrations/018-migrate-services-to-handler-dag.ts b/packages/db-migrations/src/migrations/018-migrate-services-to-handler-dag.ts index 9ea8644fe..b82b4335c 100644 --- a/packages/db-migrations/src/migrations/018-migrate-services-to-handler-dag.ts +++ b/packages/db-migrations/src/migrations/018-migrate-services-to-handler-dag.ts @@ -4,81 +4,24 @@ import type { Db } from "mongodb"; import type { MigrationInterface } from "mongo-migrate-ts"; -interface ServiceDocument { - _id: string; - version: number; - type?: "post-process-handler"; - queue?: string; - selector?: string; - autoBackfill?: boolean; - dependsOn?: string[]; -} - -type HandlerServiceSeed = Required & { - type: "post-process-handler"; -}; - -const HANDLER_SERVICES: readonly HandlerServiceSeed[] = [ - { - _id: "pp-atif", - type: "post-process-handler", - version: 2, - queue: "post-processor-queue", - selector: "atif", - autoBackfill: true, - dependsOn: [], - }, - { - _id: "pp-taxonomy", - type: "post-process-handler", - version: 1, - queue: "pp-taxonomy-queue", - selector: "taxonomy", - autoBackfill: false, - dependsOn: ["pp-atif"], - }, - { - _id: "pp-report", - type: "post-process-handler", - version: 1, - queue: "report-queue", - selector: "report", - autoBackfill: false, - dependsOn: ["pp-atif", "pp-taxonomy"], - }, -]; - +/** + * Migration 018: Remove the legacy "post-processor" service entry. + * + * Handler service registration (pp-atif, pp-taxonomy, pp-report) is now owned + * by each worker's register-version.ts script, run as a K8s Job on deploy. + * This migration only cleans up the old single-entry format. + */ export class MigrateServicesToHandlerDag implements MigrationInterface { async up(db: Db): Promise { - const services = db.collection("services"); - - await services.deleteOne({ _id: "post-processor" }); - console.log("[018] Deleted legacy post-processor service entry if it existed"); - - for (const service of HANDLER_SERVICES) { - const { _id, ...fields } = service; - await services.updateOne( - { _id }, - { - $set: { - ...fields, - dependsOn: [...fields.dependsOn], - }, - }, - { upsert: true }, - ); - console.log(`[018] Upserted handler service ${_id}`); - } + const services = db.collection("services"); + await services.deleteOne({ _id: "post-processor" } as any); + console.log("[018] Deleted legacy post-processor service entry (handler registration now owned by workers)"); } async down(db: Db): Promise { - const services = db.collection("services"); - - await services.deleteMany({ _id: { $in: HANDLER_SERVICES.map((service) => service._id) } }); - console.log("[018-down] Deleted handler service entries"); - + const services = db.collection("services"); await services.updateOne( - { _id: "post-processor" }, + { _id: "post-processor" } as any, { $set: { version: 2 }, $unset: { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a7903fc00..6f1c765b7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -691,6 +691,9 @@ importers: dotenv: specifier: ^16.4.5 version: 16.6.1 + mongodb: + specifier: ^6.10.0 + version: 6.21.0 shared: specifier: workspace:* version: link:../../../packages/shared @@ -716,6 +719,9 @@ importers: dotenv: specifier: ^16.4.5 version: 16.6.1 + mongodb: + specifier: ^6.10.0 + version: 6.21.0 shared: specifier: workspace:* version: link:../../../packages/shared From d02ec6863a4d9d67a9c9f9410ec66487adb7c734 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Tue, 9 Jun 2026 11:57:43 -0700 Subject: [PATCH 006/210] refactor: YAML-driven handler registration via scheduler endpoint Replace the three inlined register-version.ts scripts (which wrote handler metadata directly to MongoDB) with a declarative, YAML-driven approach that mirrors the coding-agent registration pattern. - Add per-worker handler.yaml (pp-atif, pp-taxonomy, pp-report) as the single source of truth for handler metadata. - Add generic packages/shared/src/scripts/register-handler.ts that reads HANDLER_YAML_PATH, waits for the scheduler /health, and POSTs to POST /handlers/register with retry. - Add scheduler POST /handlers/register endpoint (notify-routes.ts) + HandlerDispatcher.registerHandler (cycle-checked upsert). Scheduler is now the sole writer of the services collection. - Remove the 3 register-version.ts scripts and the mongodb dep from the taxonomy + report-generator workers. - Wire compose (register-handler-* services) and K8s (scheduler Service, register-handler-post-processor Job, SCHEDULER_URL, /health probes). - Update docs/architecture/post-processing.md. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- apps/scheduler/src/handler-dispatcher.ts | 27 +++ apps/scheduler/src/notify-routes.test.ts | 55 ++++++ apps/scheduler/src/notify-routes.ts | 57 ++++++ apps/workers/post-processor/Dockerfile | 2 + apps/workers/post-processor/handler.yaml | 10 ++ .../post-processor/src/register-version.ts | 50 ------ apps/workers/report-generator/Dockerfile | 2 + apps/workers/report-generator/handler.yaml | 12 ++ apps/workers/report-generator/package.json | 3 +- .../report-generator/src/register-version.ts | 51 ------ apps/workers/taxonomy/Dockerfile | 2 + apps/workers/taxonomy/handler.yaml | 11 ++ apps/workers/taxonomy/package.json | 3 +- apps/workers/taxonomy/src/register-version.ts | 51 ------ docker-compose.dev.yml | 6 +- docker-compose.yml | 39 ++-- docs/architecture/post-processing.md | 39 +++- .../src/scripts/register-handler.test.ts | 54 ++++++ .../shared/src/scripts/register-handler.ts | 170 ++++++++++++++++++ pnpm-lock.yaml | 6 - 20 files changed, 464 insertions(+), 186 deletions(-) create mode 100644 apps/workers/post-processor/handler.yaml delete mode 100644 apps/workers/post-processor/src/register-version.ts create mode 100644 apps/workers/report-generator/handler.yaml delete mode 100644 apps/workers/report-generator/src/register-version.ts create mode 100644 apps/workers/taxonomy/handler.yaml delete mode 100644 apps/workers/taxonomy/src/register-version.ts create mode 100644 packages/shared/src/scripts/register-handler.test.ts create mode 100644 packages/shared/src/scripts/register-handler.ts diff --git a/apps/scheduler/src/handler-dispatcher.ts b/apps/scheduler/src/handler-dispatcher.ts index 2c4f1b99f..09b461def 100644 --- a/apps/scheduler/src/handler-dispatcher.ts +++ b/apps/scheduler/src/handler-dispatcher.ts @@ -107,6 +107,33 @@ export class HandlerDispatcher implements NotifyHandler { } } + async registerHandler(doc: HandlerServiceDocument): Promise { + // Validate the resulting topology has no cycles before persisting. + const existing = await this.loadHandlers(); + const merged = [ + ...existing.filter((h) => h._id !== doc._id), + doc, + ]; + // Throws on cycle — rejects invalid registrations. + this.buildGraph(merged); + + const { _id, ...fields } = doc; + await this.db.collection("services").updateOne( + { _id } as any, + { + $set: { + ...fields, + dependsOn: [...fields.dependsOn], + updatedAt: new Date(), + }, + } as any, + { upsert: true }, + ); + console.log( + `[HandlerDispatcher] Registered handler ${_id} (version=${doc.version}, queue=${doc.queue}, dependsOn=[${doc.dependsOn.join(", ")}])`, + ); + } + // ── Poll safety net ───────────────────────────────────────────────── private async pollDispatch(): Promise { diff --git a/apps/scheduler/src/notify-routes.test.ts b/apps/scheduler/src/notify-routes.test.ts index 552f03243..00968ba29 100644 --- a/apps/scheduler/src/notify-routes.test.ts +++ b/apps/scheduler/src/notify-routes.test.ts @@ -52,6 +52,7 @@ describe("createHttpServer", () => { const handler: NotifyHandler = { onRunTerminal: vi.fn().mockResolvedValue(undefined), onHandlerComplete: vi.fn().mockResolvedValue(undefined), + registerHandler: vi.fn().mockResolvedValue(undefined), }; const { server, baseUrl } = await startServer(handler); servers.push(server); @@ -66,6 +67,7 @@ describe("createHttpServer", () => { const handler: NotifyHandler = { onRunTerminal: vi.fn().mockResolvedValue(undefined), onHandlerComplete: vi.fn().mockResolvedValue(undefined), + registerHandler: vi.fn().mockResolvedValue(undefined), }; const { server, baseUrl } = await startServer(handler); servers.push(server); @@ -86,6 +88,7 @@ describe("createHttpServer", () => { const handler: NotifyHandler = { onRunTerminal: vi.fn().mockResolvedValue(undefined), onHandlerComplete: vi.fn().mockResolvedValue(undefined), + registerHandler: vi.fn().mockResolvedValue(undefined), }; const { server, baseUrl } = await startServer(handler); servers.push(server); @@ -111,6 +114,7 @@ describe("createHttpServer", () => { const handler: NotifyHandler = { onRunTerminal: vi.fn().mockResolvedValue(undefined), onHandlerComplete: vi.fn().mockResolvedValue(undefined), + registerHandler: vi.fn().mockResolvedValue(undefined), }; const { server, baseUrl } = await startServer(handler); servers.push(server); @@ -133,6 +137,7 @@ describe("createHttpServer", () => { const handler: NotifyHandler = { onRunTerminal: vi.fn().mockResolvedValue(undefined), onHandlerComplete: vi.fn().mockResolvedValue(undefined), + registerHandler: vi.fn().mockResolvedValue(undefined), }; const { server, baseUrl } = await startServer(handler); servers.push(server); @@ -146,4 +151,54 @@ describe("createHttpServer", () => { expect(response.status).toBe(404); expect(await response.json()).toEqual({ error: "Not found" }); }); + + it("calls registerHandler for valid handler registrations", async () => { + const handler: NotifyHandler = { + onRunTerminal: vi.fn().mockResolvedValue(undefined), + onHandlerComplete: vi.fn().mockResolvedValue(undefined), + registerHandler: vi.fn().mockResolvedValue(undefined), + }; + const { server, baseUrl } = await startServer(handler); + servers.push(server); + + const doc = { + _id: "pp-taxonomy", + type: "post-process-handler", + version: 1, + queue: "pp-taxonomy-queue", + selector: "taxonomy", + autoBackfill: false, + dependsOn: ["pp-atif"], + }; + + const response = await fetch(`${baseUrl}/handlers/register`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(doc), + }); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ ok: true, handlerId: "pp-taxonomy" }); + expect(handler.registerHandler).toHaveBeenCalledWith(doc); + }); + + it("returns 400 for invalid handler registrations", async () => { + const handler: NotifyHandler = { + onRunTerminal: vi.fn().mockResolvedValue(undefined), + onHandlerComplete: vi.fn().mockResolvedValue(undefined), + registerHandler: vi.fn().mockResolvedValue(undefined), + }; + const { server, baseUrl } = await startServer(handler); + servers.push(server); + + const response = await fetch(`${baseUrl}/handlers/register`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + // Missing queue/selector, wrong type, dependsOn not array + body: JSON.stringify({ _id: "bad", type: "wrong", version: "x" }), + }); + + expect(response.status).toBe(400); + expect(handler.registerHandler).not.toHaveBeenCalled(); + }); }); diff --git a/apps/scheduler/src/notify-routes.ts b/apps/scheduler/src/notify-routes.ts index 445945d2d..577478b64 100644 --- a/apps/scheduler/src/notify-routes.ts +++ b/apps/scheduler/src/notify-routes.ts @@ -2,6 +2,7 @@ // Licensed under the MIT License. import http from "node:http"; +import type { HandlerServiceDocument } from "shared"; export interface NotifyHandler { onRunTerminal(requestId: string, runId: string): Promise; @@ -11,6 +12,7 @@ export interface NotifyHandler { handlerId: string, status: "done" | "failed", ): Promise; + registerHandler(doc: HandlerServiceDocument): Promise; } interface RunTerminalRequest { @@ -75,6 +77,46 @@ function parseHandlerCompleteRequest(body: unknown): HandlerCompleteRequest | nu }; } +function parseHandlerRegisterRequest(body: unknown): HandlerServiceDocument | null { + if (!isRecord(body)) { + return null; + } + + const { + _id, + type, + version, + queue, + selector, + autoBackfill, + dependsOn, + } = body; + + if ( + !isNonEmptyString(_id) || + type !== "post-process-handler" || + typeof version !== "number" || + !Number.isFinite(version) || + !isNonEmptyString(queue) || + !isNonEmptyString(selector) || + typeof autoBackfill !== "boolean" || + !Array.isArray(dependsOn) || + !dependsOn.every((d) => isNonEmptyString(d)) + ) { + return null; + } + + return { + _id, + type, + version, + queue, + selector, + autoBackfill, + dependsOn: dependsOn as string[], + }; +} + async function readJsonBody(req: http.IncomingMessage): Promise { const chunks: Buffer[] = []; @@ -131,6 +173,21 @@ export function createHttpServer(handler: NotifyHandler): http.Server { sendJson(res, 200, { ok: true }); return; } + + if (method === "POST" && url.pathname === "/handlers/register") { + const parsedBody = parseHandlerRegisterRequest(await readJsonBody(req)); + if (!parsedBody) { + sendJson(res, 400, { + error: + "Invalid handler registration: _id, type='post-process-handler', version (number), queue, selector, autoBackfill (boolean), and dependsOn (string[]) are required", + }); + return; + } + + await handler.registerHandler(parsedBody); + sendJson(res, 200, { ok: true, handlerId: parsedBody._id }); + return; + } } catch (error) { const message = error instanceof Error ? error.message : "Internal server error"; const statusCode = diff --git a/apps/workers/post-processor/Dockerfile b/apps/workers/post-processor/Dockerfile index d69ca9cb1..6d6bf8e04 100644 --- a/apps/workers/post-processor/Dockerfile +++ b/apps/workers/post-processor/Dockerfile @@ -15,6 +15,7 @@ COPY packages/shared/tsconfig.json ./packages/shared/ COPY packages/shared/src ./packages/shared/src/ COPY apps/workers/post-processor/tsconfig.json ./apps/workers/post-processor/ COPY apps/workers/post-processor/src ./apps/workers/post-processor/src/ +COPY apps/workers/post-processor/handler.yaml ./apps/workers/post-processor/ RUN pnpm --filter shared build && pnpm --filter post-processor build @@ -43,6 +44,7 @@ RUN pnpm install --frozen-lockfile --prod COPY --from=builder /app/packages/shared/dist ./packages/shared/dist/ COPY --from=builder /app/apps/workers/post-processor/dist ./apps/workers/post-processor/dist/ +COPY --from=builder /app/apps/workers/post-processor/handler.yaml ./apps/workers/post-processor/handler.yaml WORKDIR /app/apps/workers/post-processor diff --git a/apps/workers/post-processor/handler.yaml b/apps/workers/post-processor/handler.yaml new file mode 100644 index 000000000..dc3c1f348 --- /dev/null +++ b/apps/workers/post-processor/handler.yaml @@ -0,0 +1,10 @@ +# Post-process handler registration metadata. +# Read by the generic register-handler script and POSTed to the +# scheduler's POST /handlers/register endpoint on deploy. +_id: pp-atif +type: post-process-handler +version: 1 +queue: post-processor-queue +selector: atif +autoBackfill: true +dependsOn: [] diff --git a/apps/workers/post-processor/src/register-version.ts b/apps/workers/post-processor/src/register-version.ts deleted file mode 100644 index 1d3e062e3..000000000 --- a/apps/workers/post-processor/src/register-version.ts +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * Standalone script run by the K8s Job on each deployment. - * Registers the post-processor (pp-atif handler) in the services collection - * with its version, queue, and dependency information so the scheduler - * can orchestrate the DAG-based post-processing pipeline. - */ -import "dotenv/config"; -import { MongoClient } from "mongodb"; -import { POST_PROCESSOR_VERSION } from "./version.js"; - -const MONGO_URI = - process.env.MONGO_CONNECTION_STRING || - process.env.AZURE_COSMOS_CONNECTION_STRING || - "mongodb://localhost:27017"; -const MONGO_DATABASE = process.env.MONGO_DATABASE || "requests-db"; - -async function main(): Promise { - const mongo = new MongoClient(MONGO_URI); - await mongo.connect(); - - await mongo - .db(MONGO_DATABASE) - .collection("services") - .updateOne( - { _id: "pp-atif" } as any, - { - $set: { - type: "post-process-handler", - version: POST_PROCESSOR_VERSION, - queue: "post-processor-queue", - selector: "atif", - autoBackfill: true, - dependsOn: [], - updatedAt: new Date(), - }, - }, - { upsert: true }, - ); - - await mongo.close(); - console.log(`[register-version] Registered pp-atif handler version: ${POST_PROCESSOR_VERSION}`); -} - -main().catch((err) => { - console.error("[register-version] Fatal error:", err); - process.exit(1); -}); diff --git a/apps/workers/report-generator/Dockerfile b/apps/workers/report-generator/Dockerfile index 3cfd18150..62a5f2646 100644 --- a/apps/workers/report-generator/Dockerfile +++ b/apps/workers/report-generator/Dockerfile @@ -15,6 +15,7 @@ COPY packages/shared/tsconfig.json ./packages/shared/ COPY packages/shared/src ./packages/shared/src/ COPY apps/workers/report-generator/tsconfig.json ./apps/workers/report-generator/ COPY apps/workers/report-generator/src ./apps/workers/report-generator/src/ +COPY apps/workers/report-generator/handler.yaml ./apps/workers/report-generator/ RUN pnpm --filter shared build && pnpm --filter report-generator build @@ -43,6 +44,7 @@ RUN pnpm install --frozen-lockfile --prod COPY --from=builder /app/packages/shared/dist ./packages/shared/dist/ COPY --from=builder /app/apps/workers/report-generator/dist ./apps/workers/report-generator/dist/ +COPY --from=builder /app/apps/workers/report-generator/handler.yaml ./apps/workers/report-generator/handler.yaml WORKDIR /app/apps/workers/report-generator diff --git a/apps/workers/report-generator/handler.yaml b/apps/workers/report-generator/handler.yaml new file mode 100644 index 000000000..f7e14d83e --- /dev/null +++ b/apps/workers/report-generator/handler.yaml @@ -0,0 +1,12 @@ +# Post-process handler registration metadata. +# Read by the generic register-handler script and POSTed to the +# scheduler's POST /handlers/register endpoint on deploy. +_id: pp-report +type: post-process-handler +version: 1 +queue: report-queue +selector: report +autoBackfill: false +dependsOn: + - pp-atif + - pp-taxonomy diff --git a/apps/workers/report-generator/package.json b/apps/workers/report-generator/package.json index 367bdb307..d296fc738 100644 --- a/apps/workers/report-generator/package.json +++ b/apps/workers/report-generator/package.json @@ -13,8 +13,7 @@ "shared": "workspace:*", "@azure/storage-queue": "^12.25.0", "@github/copilot-sdk": "^0.1.17", - "dotenv": "^16.4.5", - "mongodb": "^6.10.0" + "dotenv": "^16.4.5" }, "devDependencies": { "@types/node": "^22.7.0", diff --git a/apps/workers/report-generator/src/register-version.ts b/apps/workers/report-generator/src/register-version.ts deleted file mode 100644 index ed423546b..000000000 --- a/apps/workers/report-generator/src/register-version.ts +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * Standalone script run by the K8s Job on each deployment. - * Registers the report-generator handler in the services collection - * with its version, queue, and dependency information so the scheduler - * can orchestrate the DAG-based post-processing pipeline. - */ -import "dotenv/config"; -import { MongoClient } from "mongodb"; - -const REPORT_HANDLER_VERSION = 1; - -const MONGO_URI = - process.env.MONGO_CONNECTION_STRING || - process.env.AZURE_COSMOS_CONNECTION_STRING || - "mongodb://localhost:27017"; -const MONGO_DATABASE = process.env.MONGO_DATABASE || "requests-db"; - -async function main(): Promise { - const mongo = new MongoClient(MONGO_URI); - await mongo.connect(); - - await mongo - .db(MONGO_DATABASE) - .collection("services") - .updateOne( - { _id: "pp-report" } as any, - { - $set: { - type: "post-process-handler", - version: REPORT_HANDLER_VERSION, - queue: "report-queue", - selector: "report", - autoBackfill: false, - dependsOn: ["pp-atif", "pp-taxonomy"], - updatedAt: new Date(), - }, - }, - { upsert: true }, - ); - - await mongo.close(); - console.log(`[register-version] Registered pp-report handler version: ${REPORT_HANDLER_VERSION}`); -} - -main().catch((err) => { - console.error("[register-version] Fatal error:", err); - process.exit(1); -}); diff --git a/apps/workers/taxonomy/Dockerfile b/apps/workers/taxonomy/Dockerfile index 6114e03a8..b6be8f2ad 100644 --- a/apps/workers/taxonomy/Dockerfile +++ b/apps/workers/taxonomy/Dockerfile @@ -15,6 +15,7 @@ COPY packages/shared/tsconfig.json ./packages/shared/ COPY packages/shared/src ./packages/shared/src/ COPY apps/workers/taxonomy/tsconfig.json ./apps/workers/taxonomy/ COPY apps/workers/taxonomy/src ./apps/workers/taxonomy/src/ +COPY apps/workers/taxonomy/handler.yaml ./apps/workers/taxonomy/ RUN pnpm --filter shared build && pnpm --filter taxonomy-handler build @@ -42,6 +43,7 @@ RUN pnpm install --frozen-lockfile --prod COPY --from=builder /app/packages/shared/dist ./packages/shared/dist/ COPY --from=builder /app/apps/workers/taxonomy/dist ./apps/workers/taxonomy/dist/ +COPY --from=builder /app/apps/workers/taxonomy/handler.yaml ./apps/workers/taxonomy/handler.yaml WORKDIR /app/apps/workers/taxonomy diff --git a/apps/workers/taxonomy/handler.yaml b/apps/workers/taxonomy/handler.yaml new file mode 100644 index 000000000..b479f905e --- /dev/null +++ b/apps/workers/taxonomy/handler.yaml @@ -0,0 +1,11 @@ +# Post-process handler registration metadata. +# Read by the generic register-handler script and POSTed to the +# scheduler's POST /handlers/register endpoint on deploy. +_id: pp-taxonomy +type: post-process-handler +version: 1 +queue: pp-taxonomy-queue +selector: taxonomy +autoBackfill: false +dependsOn: + - pp-atif diff --git a/apps/workers/taxonomy/package.json b/apps/workers/taxonomy/package.json index 1f496a50c..aacbfc4f1 100644 --- a/apps/workers/taxonomy/package.json +++ b/apps/workers/taxonomy/package.json @@ -13,8 +13,7 @@ "shared": "workspace:*", "@azure/storage-queue": "^12.25.0", "@github/copilot-sdk": "^0.1.17", - "dotenv": "^16.4.5", - "mongodb": "^6.10.0" + "dotenv": "^16.4.5" }, "devDependencies": { "@types/node": "^22.7.0", diff --git a/apps/workers/taxonomy/src/register-version.ts b/apps/workers/taxonomy/src/register-version.ts deleted file mode 100644 index e30425c35..000000000 --- a/apps/workers/taxonomy/src/register-version.ts +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * Standalone script run by the K8s Job on each deployment. - * Registers the taxonomy handler in the services collection - * with its version, queue, and dependency information so the scheduler - * can orchestrate the DAG-based post-processing pipeline. - */ -import "dotenv/config"; -import { MongoClient } from "mongodb"; - -const TAXONOMY_HANDLER_VERSION = 1; - -const MONGO_URI = - process.env.MONGO_CONNECTION_STRING || - process.env.AZURE_COSMOS_CONNECTION_STRING || - "mongodb://localhost:27017"; -const MONGO_DATABASE = process.env.MONGO_DATABASE || "requests-db"; - -async function main(): Promise { - const mongo = new MongoClient(MONGO_URI); - await mongo.connect(); - - await mongo - .db(MONGO_DATABASE) - .collection("services") - .updateOne( - { _id: "pp-taxonomy" } as any, - { - $set: { - type: "post-process-handler", - version: TAXONOMY_HANDLER_VERSION, - queue: "pp-taxonomy-queue", - selector: "taxonomy", - autoBackfill: false, - dependsOn: ["pp-atif"], - updatedAt: new Date(), - }, - }, - { upsert: true }, - ); - - await mongo.close(); - console.log(`[register-version] Registered pp-taxonomy handler version: ${TAXONOMY_HANDLER_VERSION}`); -} - -main().catch((err) => { - console.error("[register-version] Fatal error:", err); - process.exit(1); -}); diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml index bdfd84780..a2fbe32b5 100644 --- a/docker-compose.dev.yml +++ b/docker-compose.dev.yml @@ -196,15 +196,15 @@ services: - action: rebuild path: ./pnpm-lock.yaml - register-version-post-processor: + register-handler-post-processor: build: target: dev - register-version-taxonomy: + register-handler-taxonomy: build: target: dev - register-version-report-generator: + register-handler-report-generator: build: target: dev diff --git a/docker-compose.yml b/docker-compose.yml index 9b56ad1b0..53cdc0da1 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -639,7 +639,7 @@ services: condition: service_healthy api: condition: service_started - register-version-report-generator: + register-handler-report-generator: condition: service_completed_successfully taxonomy-handler: @@ -669,50 +669,53 @@ services: condition: service_started scheduler: condition: service_started - register-version-taxonomy: + register-handler-taxonomy: condition: service_completed_successfully - register-version-taxonomy: + register-handler-taxonomy: build: context: . dockerfile: apps/workers/taxonomy/Dockerfile profiles: [taxonomy, all] environment: <<: *common-env + HANDLER_YAML_PATH: apps/workers/taxonomy/handler.yaml + SCHEDULER_URL: http://scheduler:8080 depends_on: - mongodb: - condition: service_healthy - required: false + scheduler: + condition: service_started restart: "no" - entrypoint: ["npx", "tsx", "apps/workers/taxonomy/src/register-version.ts"] + entrypoint: ["npx", "tsx", "packages/shared/src/scripts/register-handler.ts"] - register-version-report-generator: + register-handler-report-generator: build: context: . dockerfile: apps/workers/report-generator/Dockerfile profiles: [report] environment: <<: *common-env + HANDLER_YAML_PATH: apps/workers/report-generator/handler.yaml + SCHEDULER_URL: http://scheduler:8080 depends_on: - mongodb: - condition: service_healthy - required: false + scheduler: + condition: service_started restart: "no" - entrypoint: ["npx", "tsx", "apps/workers/report-generator/src/register-version.ts"] + entrypoint: ["npx", "tsx", "packages/shared/src/scripts/register-handler.ts"] - register-version-post-processor: + register-handler-post-processor: build: context: . dockerfile: apps/workers/post-processor/Dockerfile profiles: [post-processor] environment: <<: *common-env + HANDLER_YAML_PATH: apps/workers/post-processor/handler.yaml + SCHEDULER_URL: http://scheduler:8080 depends_on: - mongodb: - condition: service_healthy - required: false + scheduler: + condition: service_started restart: "no" - entrypoint: ["npx", "tsx", "apps/workers/post-processor/src/register-version.ts"] + entrypoint: ["npx", "tsx", "packages/shared/src/scripts/register-handler.ts"] post-processor: build: @@ -734,7 +737,7 @@ services: condition: service_healthy api: condition: service_started - register-version-post-processor: + register-handler-post-processor: condition: service_completed_successfully volumes: diff --git a/docs/architecture/post-processing.md b/docs/architecture/post-processing.md index df326d5e4..d16d6294f 100644 --- a/docs/architecture/post-processing.md +++ b/docs/architecture/post-processing.md @@ -16,7 +16,7 @@ Two paths trigger post-processing: 1. **Event-driven (primary):** Coder workers enqueue a post-processing message immediately when a run completes, currently setting the deprecated `run.postProcessorStatus: "queued"` compatibility field atomically in the same DB write while the system migrates to per-handler status. 2. **Scheduler backfill:** The `PostProcessorDispatcher` polls every 30 seconds for runs that have `status: "done"` but no post-processing marker set (or a stale handler version). During the migration window this may consult the deprecated flat fields; the long-term source of truth is `run.handlerStatus[handlerId]`. This catches runs that completed before the event-driven dispatch was deployed, or that need re-processing after a version bump. -3. **Scheduler notify server:** The scheduler also exposes `GET /health`, `POST /notify/run-terminal`, and `POST /notify/handler-complete` on a lightweight `node:http` server. Workers and post-process handlers use these endpoints to notify the scheduler when terminal states are reached so it can re-evaluate which root or downstream handlers are ready to dispatch. +3. **Scheduler notify & registration server:** The scheduler also exposes `GET /health`, `POST /notify/run-terminal`, `POST /notify/handler-complete`, and `POST /handlers/register` on a lightweight `node:http` server. Workers and post-process handlers use the notify endpoints to signal terminal states so the scheduler can re-evaluate which root or downstream handlers are ready to dispatch. The `/handlers/register` endpoint is the single writer to the `services` collection — see [Handler Registration](#handler-registration). ## ATIF Generation @@ -127,6 +127,38 @@ The post-processor uses a version-based re-processing scheme: This allows deploying handler improvements and having them automatically applied to historical data. +## Handler Registration + +Each post-process handler declares its DAG metadata in a `handler.yaml` file colocated with the worker (e.g. `apps/workers/taxonomy/handler.yaml`). This mirrors the coding-agent `agent.yaml` registration pattern. + +```yaml +# apps/workers/taxonomy/handler.yaml +_id: pp-taxonomy +type: post-process-handler +version: 1 +queue: pp-taxonomy-queue +selector: taxonomy +autoBackfill: false +dependsOn: + - pp-atif +``` + +On deploy, a generic registration script — `packages/shared/src/scripts/register-handler.ts` — reads the `handler.yaml` pointed to by `HANDLER_YAML_PATH`, waits for the scheduler's `/health`, and POSTs the parsed document to `${SCHEDULER_URL}/handlers/register` (with retry). The scheduler validates the document, runs a cycle check against the existing topology, and upserts it into the `services` collection via `HandlerDispatcher.registerHandler`. **Workers never write to the `services` collection directly** — the scheduler is the sole owner. + +```mermaid +flowchart LR + YAML[handler.yaml] --> SCRIPT[register-handler.ts] + SCRIPT -->|"POST /handlers/register"| SCH[Scheduler] + SCH -->|"validate + cycle check + upsert"| SVC[(services collection)] +``` + +**Where it runs:** + +- **Docker Compose:** one `register-handler-` init service per handler (`pp-atif`, `pp-taxonomy`, `pp-report`) runs the generic script via `tsx`, gated on the scheduler being up. The worker waits for its registration service to complete. +- **Kubernetes:** a `register-handler-post-processor` Job runs the compiled script (`node packages/shared/dist/scripts/register-handler.js`) on each deploy. Only `pp-atif` is registered in K8s today because it is the only post-process handler deployed to the cluster; `pp-taxonomy` and `pp-report` are registered in Compose only until the taxonomy worker is deployed to K8s and report generation moves onto the DAG. The scheduler exposes a `Service` (`scheduler.scoped.svc.cluster.local:8080`) so Jobs and workers can reach `/handlers/register` and the notify endpoints. + +To **add or change a handler**, edit its `handler.yaml` (bump `version`, adjust `dependsOn`, etc.) — no code or migration changes are needed for registration. + ## Status Lifecycle ```mermaid @@ -157,7 +189,8 @@ stateDiagram-v2 | `SCOPE_MT_API_URL` / `API_BASE_URL` | `http://localhost:3001` | API URL used by report/taxonomy Copilot tools | | `TAXONOMY_MODEL` | `gpt-4.1` | Copilot SDK model used by the taxonomy handler | | `SESSION_TIMEOUT_MS` | `300000` | Timeout for report/taxonomy Copilot SDK sessions | -| `SCHEDULER_URL` | _(unset)_ | Optional scheduler notify base URL for downstream handler dispatch | +| `SCHEDULER_URL` | _(unset)_ | Scheduler base URL — used by handlers to notify completion and by the register-handler script to reach `/handlers/register` | +| `HANDLER_YAML_PATH` | _(unset)_ | Path to a handler's `handler.yaml`, read by the generic `register-handler` script | ## Infrastructure @@ -165,4 +198,4 @@ stateDiagram-v2 - **Blob Storage:** `snapshots` container (shared with HAR, tool-calls, and other artifacts) - **Database:** MongoDB `requests` collection (`run.handlerStatus` map keyed by handler ID, with deprecated `run.postProcessorStatus` / `run.postProcessorVersion` compatibility fields during migration) - **KEDA:** ScaledObject scales the worker to zero when queue is empty -- **Version registration:** Kubernetes Job runs on each deploy; Docker Compose uses an init service \ No newline at end of file +- **Handler registration:** declarative `handler.yaml` per worker → generic `register-handler` script → scheduler `POST /handlers/register` (sole writer to the `services` collection). A Kubernetes Job runs the script on each deploy; Docker Compose uses per-handler init services. See [Handler Registration](#handler-registration). \ No newline at end of file diff --git a/packages/shared/src/scripts/register-handler.test.ts b/packages/shared/src/scripts/register-handler.test.ts new file mode 100644 index 000000000..0c3858b58 --- /dev/null +++ b/packages/shared/src/scripts/register-handler.test.ts @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { describe, expect, it } from "vitest"; +import { parseHandlerDocument } from "./register-handler.js"; + +describe("parseHandlerDocument", () => { + const valid = { + _id: "pp-taxonomy", + type: "post-process-handler", + version: 1, + queue: "pp-taxonomy-queue", + selector: "taxonomy", + autoBackfill: false, + dependsOn: ["pp-atif"], + }; + + it("accepts a valid handler document", () => { + expect(parseHandlerDocument(valid)).toEqual(valid); + }); + + it("defaults dependsOn to an empty array when omitted", () => { + const { dependsOn, ...withoutDeps } = valid; + expect(parseHandlerDocument(withoutDeps).dependsOn).toEqual([]); + }); + + it("rejects a missing _id", () => { + expect(() => parseHandlerDocument({ ...valid, _id: "" })).toThrow(/_id/); + }); + + it("rejects a wrong type", () => { + expect(() => parseHandlerDocument({ ...valid, type: "agent" })).toThrow(/type/); + }); + + it("rejects a non-numeric version", () => { + expect(() => parseHandlerDocument({ ...valid, version: "1" })).toThrow(/version/); + }); + + it("rejects a non-boolean autoBackfill", () => { + expect(() => parseHandlerDocument({ ...valid, autoBackfill: "yes" })).toThrow( + /autoBackfill/, + ); + }); + + it("rejects a dependsOn that is not an array of strings", () => { + expect(() => parseHandlerDocument({ ...valid, dependsOn: [1, 2] })).toThrow( + /dependsOn/, + ); + }); + + it("rejects a non-object input", () => { + expect(() => parseHandlerDocument("nope")).toThrow(/mapping/); + }); +}); diff --git a/packages/shared/src/scripts/register-handler.ts b/packages/shared/src/scripts/register-handler.ts new file mode 100644 index 000000000..c585e9eb1 --- /dev/null +++ b/packages/shared/src/scripts/register-handler.ts @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * Generic post-process handler registration script. + * + * Replaces the per-worker, inlined `register-version.ts` scripts that wrote + * directly to MongoDB. Reads a declarative `handler.yaml` (path from + * HANDLER_YAML_PATH) and POSTs it to the scheduler's + * `POST /handlers/register` endpoint (the scheduler owns the `services` + * collection). Used identically by docker-compose init services and the K8s + * registration Jobs. + * + * Mirrors the coding-agent registration pattern (`agent.yaml` → + * `POST /api/v1/agents`). + * + * Environment: + * HANDLER_YAML_PATH Path to the handler.yaml file (required) + * SCHEDULER_URL Base URL of the scheduler HTTP server, e.g. + * http://scheduler:8080 (required) + */ +import { readFile } from "node:fs/promises"; +import { parse as parseYaml } from "yaml"; +import type { HandlerServiceDocument } from "../types/types.js"; + +const HEALTH_RETRIES = 30; +const HEALTH_DELAY_MS = 3_000; +const POST_RETRIES = 10; +const POST_DELAY_MS = 3_000; + +function isNonEmptyString(value: unknown): value is string { + return typeof value === "string" && value.trim().length > 0; +} + +/** Validate the parsed YAML conforms to the HandlerServiceDocument shape. */ +export function parseHandlerDocument(raw: unknown): HandlerServiceDocument { + if (typeof raw !== "object" || raw === null) { + throw new Error("handler.yaml must contain a mapping"); + } + const doc = raw as Record; + + if (!isNonEmptyString(doc._id)) { + throw new Error("handler.yaml: '_id' is required"); + } + if (doc.type !== "post-process-handler") { + throw new Error("handler.yaml: 'type' must be 'post-process-handler'"); + } + if (typeof doc.version !== "number" || !Number.isFinite(doc.version)) { + throw new Error("handler.yaml: 'version' must be a number"); + } + if (!isNonEmptyString(doc.queue)) { + throw new Error("handler.yaml: 'queue' is required"); + } + if (!isNonEmptyString(doc.selector)) { + throw new Error("handler.yaml: 'selector' is required"); + } + if (typeof doc.autoBackfill !== "boolean") { + throw new Error("handler.yaml: 'autoBackfill' must be a boolean"); + } + const dependsOn = doc.dependsOn ?? []; + if (!Array.isArray(dependsOn) || !dependsOn.every((d) => isNonEmptyString(d))) { + throw new Error("handler.yaml: 'dependsOn' must be an array of strings"); + } + + return { + _id: doc._id, + type: "post-process-handler", + version: doc.version, + queue: doc.queue, + selector: doc.selector, + autoBackfill: doc.autoBackfill, + dependsOn: dependsOn as string[], + }; +} + +async function delay(ms: number): Promise { + await new Promise((resolve) => setTimeout(resolve, ms)); +} + +async function waitForScheduler(schedulerUrl: string): Promise { + for (let attempt = 1; attempt <= HEALTH_RETRIES; attempt++) { + try { + const res = await fetch(`${schedulerUrl}/health`); + if (res.ok) { + return; + } + } catch { + // not ready yet + } + console.log( + `[register-handler] Scheduler not ready (attempt ${attempt}/${HEALTH_RETRIES}), retrying in ${HEALTH_DELAY_MS}ms...`, + ); + await delay(HEALTH_DELAY_MS); + } + throw new Error(`Scheduler did not become healthy at ${schedulerUrl}`); +} + +async function postRegistration( + schedulerUrl: string, + doc: HandlerServiceDocument, +): Promise { + for (let attempt = 1; attempt <= POST_RETRIES; attempt++) { + try { + const res = await fetch(`${schedulerUrl}/handlers/register`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(doc), + }); + if (res.ok) { + return; + } + const body = await res.text(); + console.log( + `[register-handler] Register failed (attempt ${attempt}/${POST_RETRIES}): HTTP ${res.status} ${body}`, + ); + } catch (err) { + console.log( + `[register-handler] Register error (attempt ${attempt}/${POST_RETRIES}): ${ + err instanceof Error ? err.message : String(err) + }`, + ); + } + await delay(POST_DELAY_MS); + } + throw new Error(`Failed to register handler ${doc._id} after ${POST_RETRIES} attempts`); +} + +export async function registerHandlerFromYaml( + yamlPath: string, + schedulerUrl: string, +): Promise { + const content = await readFile(yamlPath, "utf-8"); + const doc = parseHandlerDocument(parseYaml(content)); + + console.log( + `[register-handler] Registering ${doc._id} (version=${doc.version}, queue=${doc.queue}) at ${schedulerUrl}`, + ); + + await waitForScheduler(schedulerUrl); + await postRegistration(schedulerUrl, doc); + + console.log(`[register-handler] Registered ${doc._id} successfully`); + return doc; +} + +async function main(): Promise { + const yamlPath = process.env.HANDLER_YAML_PATH; + const schedulerUrl = process.env.SCHEDULER_URL; + + if (!yamlPath) { + throw new Error("HANDLER_YAML_PATH is required"); + } + if (!schedulerUrl) { + throw new Error("SCHEDULER_URL is required"); + } + + await registerHandlerFromYaml(yamlPath, schedulerUrl.replace(/\/+$/, "")); +} + +// Only run when executed directly (not when imported by tests). +const isDirectRun = + process.argv[1] !== undefined && + import.meta.url === new URL(`file://${process.argv[1]}`).href; + +if (isDirectRun) { + main().catch((err) => { + console.error("[register-handler] Fatal error:", err); + process.exit(1); + }); +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6f1c765b7..a7903fc00 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -691,9 +691,6 @@ importers: dotenv: specifier: ^16.4.5 version: 16.6.1 - mongodb: - specifier: ^6.10.0 - version: 6.21.0 shared: specifier: workspace:* version: link:../../../packages/shared @@ -719,9 +716,6 @@ importers: dotenv: specifier: ^16.4.5 version: 16.6.1 - mongodb: - specifier: ^6.10.0 - version: 6.21.0 shared: specifier: workspace:* version: link:../../../packages/shared From 02900bda44f5f43aa8368d72b960b825d5456cdc Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Tue, 9 Jun 2026 13:34:08 -0700 Subject: [PATCH 007/210] feat: scheduler triggers report generation when handler DAG drains MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reports were modeled as a DAG handler node (pp-report, dependsOn [pp-atif, pp-taxonomy]), but the report-generator worker is keyed by reportId and requires a templateId, while the DAG dispatches a generic {type, requestId, runId} message — so pp-report could never process a DAG message. Reports are also parameterized, N-per-run, and trigger-gated, so they don't fit the idempotent per-run DAG-node model. Take reports off the DAG. The scheduler now detects when a run's handler DAG has drained (every registered handler terminal: done | failed | blocked-by-failed-dependency) and calls the existing POST /api/v1/reports/trigger endpoint, which evaluates each template's trigger and creates a properly-templated ReportDocument + enqueues {reportId} per match. - HandlerDispatcher: isHandlerTerminal/isDagDrained/maybeTriggerReports/ triggerReports + pollTriggerReports safety net. Exactly-once via an atomic run.reportsTriggeredAt guard, scoped by run._id so a stale notify or concurrent retry can never trigger reports for — or roll back the guard of — a different attempt. Fires on run-terminal (zero-handler / already-drained), both branches of handler-complete (a failure can drain the DAG), and the 30s poll loop. Rolls back the guard on POST failure. - Inject API_URL into the dispatcher; add API_URL to scheduler env in docker-compose.yml and deploy/base/scheduler.yaml. - Remove pp-report as a DAG node: delete report-generator/handler.yaml, its Dockerfile COPY lines, the register-handler-report-generator compose service, the dead idx_handler_dispatch_report index in migration 019, and stale comments. No migration to delete pp-report is needed — nothing is deployed, so a fresh environment never registers it. - Add reportsTriggeredAt to RunState. - Tests: 13 dispatcher tests (drain detection, exactly-once guard, attempt-scoped claim/rollback, stale-runId rejection, POST payload). - Docs: post-processing.md "Report Triggering on DAG Drain" section + ENV_VARIABLES API_URL. Verified E2E: run -> pp-atif(done) -> pp-taxonomy(failed) -> DAG drains -> scheduler POST /reports/trigger -> API matches template -> ReportDocument (templateId) enqueued -> report-generator -> report done. Confirms reports fire even when a handler fails. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ENV_VARIABLES.md | 9 + apps/scheduler/src/handler-dispatcher.test.ts | 251 ++++++++++++++++++ apps/scheduler/src/handler-dispatcher.ts | 221 ++++++++++++--- apps/scheduler/src/index.ts | 3 + apps/workers/report-generator/Dockerfile | 2 - apps/workers/report-generator/handler.yaml | 12 - docker-compose.dev.yml | 4 - docker-compose.yml | 18 +- docs/architecture/post-processing.md | 59 +++- .../018-migrate-services-to-handler-dag.ts | 7 +- .../019-add-handler-status-index.ts | 8 - packages/shared/src/types/types.ts | 7 +- 12 files changed, 520 insertions(+), 81 deletions(-) create mode 100644 apps/scheduler/src/handler-dispatcher.test.ts delete mode 100644 apps/workers/report-generator/handler.yaml diff --git a/ENV_VARIABLES.md b/ENV_VARIABLES.md index 5044d6c53..5d62a193a 100644 --- a/ENV_VARIABLES.md +++ b/ENV_VARIABLES.md @@ -333,6 +333,15 @@ Optional base URL for the scheduler's HTTP notification endpoints. When set, cod - **Kubernetes:** `http://scheduler-service.scoped.svc.cluster.local:8080` - **Local dev:** Leave unset to rely on legacy queue fallback unless you are also running the scheduler locally +### API_URL +**Default:** `http://api:80` +**Type:** URL string + +Base URL the **scheduler** uses to reach the API's `POST /api/v1/reports/trigger` endpoint. When a run's post-processing handler DAG drains (every registered handler reaches a terminal state), the scheduler calls this endpoint so the API can evaluate each report template's trigger and create the templated report job(s). Reports are deliberately not DAG handlers — see [docs/architecture/post-processing.md](docs/architecture/post-processing.md#report-triggering-on-dag-drain). + +- **Docker Compose:** `http://api:80` +- **Kubernetes:** `http://api.scoped.svc.cluster.local:80` + ## Worker Configuration ### SCOPE_RUN_HEARTBEAT_STALE_MS diff --git a/apps/scheduler/src/handler-dispatcher.test.ts b/apps/scheduler/src/handler-dispatcher.test.ts new file mode 100644 index 000000000..080b2b4a7 --- /dev/null +++ b/apps/scheduler/src/handler-dispatcher.test.ts @@ -0,0 +1,251 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import type { HandlerServiceDocument } from "shared"; +import { HandlerDispatcher } from "./handler-dispatcher.js"; + +const HANDLERS: HandlerServiceDocument[] = [ + { + _id: "pp-atif", + type: "post-process-handler", + version: 1, + queue: "post-processor-queue", + selector: "atif", + autoBackfill: true, + dependsOn: [], + }, + { + _id: "pp-taxonomy", + type: "post-process-handler", + version: 1, + queue: "pp-taxonomy-queue", + selector: "taxonomy", + autoBackfill: false, + dependsOn: ["pp-atif"], + }, +]; + +function createMockCollection() { + return { + findOne: vi.fn(), + findOneAndUpdate: vi.fn(), + updateOne: vi.fn().mockResolvedValue(undefined), + find: vi.fn(), + } as any; +} + +function createMockDb(handlers: HandlerServiceDocument[]) { + return { + collection: vi.fn().mockReturnValue({ + find: vi.fn().mockReturnValue({ toArray: vi.fn().mockResolvedValue(handlers) }), + updateOne: vi.fn().mockResolvedValue(undefined), + }), + } as any; +} + +function makeDispatcher( + collection: any, + handlers: HandlerServiceDocument[] = HANDLERS, + apiUrl = "http://api.test", +) { + const db = createMockDb(handlers); + const createQueueClient = vi.fn(); + return new HandlerDispatcher(collection, db, createQueueClient, 60_000, 30, apiUrl); +} + +describe("HandlerDispatcher — drain detection", () => { + let collection: ReturnType; + + beforeEach(() => { + collection = createMockCollection(); + }); + + function isDrained( + handlers: HandlerServiceDocument[], + handlerStatus: Record | undefined, + ): boolean { + const d = makeDispatcher(collection, handlers) as any; + const graph = d.buildGraph(handlers); + return d.isDagDrained(handlers, graph, handlerStatus); + } + + it("is drained when all handlers are done", () => { + expect( + isDrained(HANDLERS, { "pp-atif": { status: "done" }, "pp-taxonomy": { status: "done" } }), + ).toBe(true); + }); + + it("is NOT drained when the leaf is still pending", () => { + expect(isDrained(HANDLERS, { "pp-atif": { status: "done" } })).toBe(false); + }); + + it("is NOT drained when a handler is processing", () => { + expect( + isDrained(HANDLERS, { + "pp-atif": { status: "done" }, + "pp-taxonomy": { status: "processing" }, + }), + ).toBe(false); + }); + + it("is drained when a failed dependency blocks its descendant", () => { + // pp-atif failed → pp-taxonomy can never run (blocked) → terminal. + expect(isDrained(HANDLERS, { "pp-atif": { status: "failed" } })).toBe(true); + }); + + it("is drained when the leaf itself failed", () => { + expect( + isDrained(HANDLERS, { + "pp-atif": { status: "done" }, + "pp-taxonomy": { status: "failed" }, + }), + ).toBe(true); + }); + + it("is vacuously drained when there are no handlers", () => { + expect(isDrained([], undefined)).toBe(true); + }); +}); + +describe("HandlerDispatcher — maybeTriggerReports", () => { + let collection: ReturnType; + const fetchMock = vi.fn(); + + beforeEach(() => { + collection = createMockCollection(); + fetchMock.mockReset(); + vi.stubGlobal("fetch", fetchMock); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it("POSTs to /api/v1/reports/trigger once the DAG drains", async () => { + collection.findOne.mockResolvedValue({ + _id: "req-1", + run: { + _id: "run-1", + status: "done", + handlerStatus: { "pp-atif": { status: "done" }, "pp-taxonomy": { status: "done" } }, + }, + }); + collection.findOneAndUpdate.mockResolvedValue({ _id: "req-1" }); // claim succeeds + fetchMock.mockResolvedValue({ ok: true, status: 201, text: async () => "" }); + + const d = makeDispatcher(collection) as any; + await d.maybeTriggerReports("req-1", "run-1"); + + expect(collection.findOneAndUpdate).toHaveBeenCalledWith( + expect.objectContaining({ + _id: "req-1", + "run._id": "run-1", + "run.status": "done", + "run.reportsTriggeredAt": { $exists: false }, + }), + expect.objectContaining({ $set: expect.objectContaining({ "run.reportsTriggeredAt": expect.any(Date) }) }), + expect.objectContaining({ returnDocument: "after" }), + ); + expect(fetchMock).toHaveBeenCalledTimes(1); + const [url, init] = fetchMock.mock.calls[0]; + expect(url).toBe("http://api.test/api/v1/reports/trigger"); + expect(init.method).toBe("POST"); + expect(JSON.parse(init.body)).toEqual({ requestId: "req-1" }); + }); + + it("does not trigger when the DAG has not drained", async () => { + collection.findOne.mockResolvedValue({ + _id: "req-1", + run: { _id: "run-1", status: "done", handlerStatus: { "pp-atif": { status: "done" } } }, + }); + + const d = makeDispatcher(collection) as any; + await d.maybeTriggerReports("req-1", "run-1"); + + expect(collection.findOneAndUpdate).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("does not trigger when reports were already triggered", async () => { + collection.findOne.mockResolvedValue({ + _id: "req-1", + run: { _id: "run-1", status: "done", reportsTriggeredAt: new Date(), handlerStatus: {} }, + }); + + const d = makeDispatcher(collection) as any; + await d.maybeTriggerReports("req-1", "run-1"); + + expect(collection.findOneAndUpdate).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("does not trigger when the current attempt differs from the notified runId", async () => { + // A stale notify for run-1 arrives, but the request has since been retried + // into run-2 — the guard must not fire for the wrong attempt. + collection.findOne.mockResolvedValue({ + _id: "req-1", + run: { + _id: "run-2", + status: "done", + handlerStatus: { "pp-atif": { status: "done" }, "pp-taxonomy": { status: "done" } }, + }, + }); + + const d = makeDispatcher(collection) as any; + await d.maybeTriggerReports("req-1", "run-1"); + + expect(collection.findOneAndUpdate).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("does not POST twice when the guard claim is lost to a concurrent path", async () => { + collection.findOne.mockResolvedValue({ + _id: "req-1", + run: { + _id: "run-1", + status: "done", + handlerStatus: { "pp-atif": { status: "done" }, "pp-taxonomy": { status: "done" } }, + }, + }); + collection.findOneAndUpdate.mockResolvedValue(null); // another path claimed it first + + const d = makeDispatcher(collection) as any; + await d.maybeTriggerReports("req-1", "run-1"); + + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("rolls back the guard when the trigger POST fails", async () => { + collection.findOne.mockResolvedValue({ + _id: "req-1", + run: { + _id: "run-1", + status: "done", + handlerStatus: { "pp-atif": { status: "done" }, "pp-taxonomy": { status: "done" } }, + }, + }); + collection.findOneAndUpdate.mockResolvedValue({ _id: "req-1" }); + fetchMock.mockResolvedValue({ ok: false, status: 500, text: async () => "boom" }); + + const d = makeDispatcher(collection) as any; + d.reportRetryOptions = { maxRetries: 1, baseDelayMs: 1, isRetryable: () => true }; + await d.maybeTriggerReports("req-1", "run-1"); + + // Guard rolled back via $unset (scoped to the attempt) so the poll net retries. + expect(collection.updateOne).toHaveBeenCalledWith( + { _id: "req-1", "run._id": "run-1" }, + { $unset: { "run.reportsTriggeredAt": "" } }, + ); + }); + + it("ignores runs that are not done", async () => { + collection.findOne.mockResolvedValue({ _id: "req-1", run: { _id: "run-1", status: "processing" } }); + + const d = makeDispatcher(collection) as any; + await d.maybeTriggerReports("req-1", "run-1"); + + expect(collection.findOneAndUpdate).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/scheduler/src/handler-dispatcher.ts b/apps/scheduler/src/handler-dispatcher.ts index 09b461def..615a45e3d 100644 --- a/apps/scheduler/src/handler-dispatcher.ts +++ b/apps/scheduler/src/handler-dispatcher.ts @@ -4,7 +4,8 @@ import { Collection, Db } from "mongodb"; import { QueueClient } from "@azure/storage-queue"; import type { RequestDocument, HandlerServiceDocument, HandlerRunStatus } from "shared"; -import { DependencyGraph } from "shared"; +import { DependencyGraph, withRetry } from "shared"; +import type { RetryOptions } from "shared"; import type { NotifyHandler } from "./notify-routes.js"; /** @@ -24,12 +25,22 @@ export class HandlerDispatcher implements NotifyHandler { private dispatching = false; private queueClients = new Map(); + /** Retry policy for the report-trigger POST. The 30s poll net is the durable + * backstop, so in-call retries are modest. Overridable in tests. */ + private reportRetryOptions: RetryOptions = { + maxRetries: 4, + baseDelayMs: 250, + maxDelayMs: 2_000, + isRetryable: () => true, + }; + constructor( private readonly collection: Collection, private readonly db: Db, private readonly createQueueClient: (queueName: string) => QueueClient, private readonly pollIntervalMs: number = 30_000, private readonly batchSize: number = 30, + private readonly apiUrl: string = process.env.API_URL || "http://api:80", ) {} start(): void { @@ -54,14 +65,18 @@ export class HandlerDispatcher implements NotifyHandler { async onRunTerminal(requestId: string, runId: string): Promise { console.log(`[HandlerDispatcher] Notify: run-terminal ${requestId} (run=${runId})`); const handlers = await this.loadHandlers(); - if (handlers.length === 0) return; - const graph = this.buildGraph(handlers); - const roots = handlers.filter((h) => !h.dependsOn || h.dependsOn.length === 0); + if (handlers.length > 0) { + const graph = this.buildGraph(handlers); + const roots = handlers.filter((h) => !h.dependsOn || h.dependsOn.length === 0); - for (const handler of roots) { - await this.dispatchIfEligible(requestId, runId, handler, graph, handlers); + for (const handler of roots) { + await this.dispatchIfEligible(requestId, runId, handler, graph, handlers); + } } + + // A run with no handlers (or an already-drained DAG) triggers reports now. + await this.maybeTriggerReports(requestId, runId); } async onHandlerComplete( @@ -86,7 +101,9 @@ export class HandlerDispatcher implements NotifyHandler { ); if (status === "failed") { - // Don't dispatch downstream on failure + // Don't dispatch downstream on failure, but the failure may have drained + // the DAG (descendants are now permanently blocked) — check for reports. + await this.maybeTriggerReports(requestId, runId); return; } @@ -105,6 +122,9 @@ export class HandlerDispatcher implements NotifyHandler { for (const child of children) { await this.dispatchIfEligible(requestId, runId, child, graph, handlers); } + + // Completing this handler may have drained the DAG (e.g. it was the leaf). + await this.maybeTriggerReports(requestId, runId); } async registerHandler(doc: HandlerServiceDocument): Promise { @@ -134,6 +154,119 @@ export class HandlerDispatcher implements NotifyHandler { ); } + // ── Report trigger on DAG drain ───────────────────────────────────── + + /** + * A handler is "terminal" for a run when it can produce no further work: + * it has succeeded (`done`), failed (`failed`), or is permanently blocked + * because one of its transitive dependencies failed (so it can never run). + */ + private isHandlerTerminal( + handlerId: string, + graph: DependencyGraph, + handlerStatus: Record | undefined, + ): boolean { + const status = handlerStatus?.[handlerId]?.status; + if (status === "done" || status === "failed") return true; + + // Not yet dispatched/processed — terminal only if blocked by a failed + // ancestor (any transitive dependency that failed). + if (status === undefined) { + for (const ancestorId of graph.getAncestors(handlerId)) { + if (handlerStatus?.[ancestorId]?.status === "failed") return true; + } + } + + // "queued" or "processing" — still active. + return false; + } + + /** + * The DAG is drained for a run when every registered handler is terminal. + * Vacuously true when there are no handlers. + */ + private isDagDrained( + handlers: HandlerServiceDocument[], + graph: DependencyGraph, + handlerStatus: Record | undefined, + ): boolean { + return handlers.every((h) => + this.isHandlerTerminal(h._id, graph, handlerStatus), + ); + } + + /** + * If the run's handler DAG has drained and reports have not yet been + * triggered, atomically claim the exactly-once guard and POST to the API's + * report-trigger endpoint. Rolls the guard back on failure so the poll + * safety net retries. + * + * All reads/writes are scoped to the specific attempt (`run._id === runId`) + * so a stale notify or a concurrent retry can never trigger reports for, or + * roll back the guard of, a different attempt. + */ + private async maybeTriggerReports(requestId: string, runId: string): Promise { + const doc = await this.collection.findOne({ _id: requestId } as any); + const run = doc?.run; + if (!run || run._id !== runId || run.status !== "done") return; + if ((run as any).reportsTriggeredAt) return; + + const handlers = await this.loadHandlers(); + const graph = this.buildGraph(handlers); + const handlerStatus = (run as any).handlerStatus as + | Record + | undefined; + + if (!this.isDagDrained(handlers, graph, handlerStatus)) return; + + // Atomically claim the trigger so concurrent notify/poll paths fire once. + const claimed = await this.collection.findOneAndUpdate( + { + _id: requestId, + "run._id": runId, + "run.status": "done", + "run.reportsTriggeredAt": { $exists: false }, + } as any, + { $set: { "run.reportsTriggeredAt": new Date() } } as any, + { returnDocument: "after" }, + ); + if (!claimed) return; // Another path already claimed it. + + try { + await this.triggerReports(requestId); + console.log( + `[HandlerDispatcher] Triggered report generation for ${requestId} (DAG drained)`, + ); + } catch (err) { + // Roll back the guard so a later poll retries — scoped to this attempt so + // a concurrent retry's valid guard is never cleared. + await this.collection.updateOne( + { _id: requestId, "run._id": runId } as any, + { $unset: { "run.reportsTriggeredAt": "" } } as any, + ); + console.error( + `[HandlerDispatcher] Report trigger failed for ${requestId}, rolled back guard:`, + err, + ); + } + } + + /** POSTs to the API's report-trigger endpoint with retry on transient errors. */ + private async triggerReports(requestId: string): Promise { + const url = `${this.apiUrl}/api/v1/reports/trigger`; + await withRetry(async () => { + const res = await fetch(url, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ requestId }), + }); + if (!res.ok) { + const text = await res.text().catch(() => ""); + throw new Error(`POST ${url} -> ${res.status} ${text}`.trim()); + } + }, this.reportRetryOptions); + } + // ── Poll safety net ───────────────────────────────────────────────── private async pollDispatch(): Promise { @@ -141,33 +274,38 @@ export class HandlerDispatcher implements NotifyHandler { this.dispatching = true; try { const handlers = await this.loadHandlers(); - if (handlers.length === 0) return; - - const graph = this.buildGraph(handlers); - for (const handler of handlers) { - // Find runs that need this handler dispatched - for (let i = 0; i < this.batchSize; i++) { - const filter = this.buildDispatchFilter(handler, handlers, graph); - if (!filter) break; - - const claimed = await this.collection.findOneAndUpdate( - filter as any, - { - $set: { - [`run.handlerStatus.${handler._id}.status`]: "queued", - [`run.handlerStatus.${handler._id}.updatedAt`]: new Date(), - }, - } as any, - { sort: { updatedAt: -1 }, returnDocument: "after" }, - ); - - if (!claimed) break; - - await this.enqueueToHandler(handler, claimed._id, (claimed as any).run?._id); - console.log(`[HandlerDispatcher] Poll-dispatched ${handler._id} for ${claimed._id}`); + if (handlers.length > 0) { + const graph = this.buildGraph(handlers); + + for (const handler of handlers) { + // Find runs that need this handler dispatched + for (let i = 0; i < this.batchSize; i++) { + const filter = this.buildDispatchFilter(handler, handlers, graph); + if (!filter) break; + + const claimed = await this.collection.findOneAndUpdate( + filter as any, + { + $set: { + [`run.handlerStatus.${handler._id}.status`]: "queued", + [`run.handlerStatus.${handler._id}.updatedAt`]: new Date(), + }, + } as any, + { sort: { updatedAt: -1 }, returnDocument: "after" }, + ); + + if (!claimed) break; + + await this.enqueueToHandler(handler, claimed._id, (claimed as any).run?._id); + console.log(`[HandlerDispatcher] Poll-dispatched ${handler._id} for ${claimed._id}`); + } } } + + // Safety net: trigger reports for any done run whose DAG has drained but + // whose report trigger was missed (e.g. a dropped notify). + await this.pollTriggerReports(); } catch (err) { console.error("[HandlerDispatcher] Error during poll dispatch:", err); } finally { @@ -175,6 +313,27 @@ export class HandlerDispatcher implements NotifyHandler { } } + /** + * Scans for `done` runs whose reports have not yet been triggered and runs + * the drain check on each. Bounded by `batchSize` per poll. + */ + private async pollTriggerReports(): Promise { + const candidates = await this.collection + .find({ + "run.status": "done", + "run.reportsTriggeredAt": { $exists: false }, + deletedAt: { $exists: false }, + } as any) + .limit(this.batchSize) + .toArray(); + + for (const doc of candidates) { + const runId = (doc as any).run?._id as string | undefined; + if (!runId) continue; + await this.maybeTriggerReports(doc._id, runId); + } + } + // ── Dispatch logic ────────────────────────────────────────────────── private async dispatchIfEligible( diff --git a/apps/scheduler/src/index.ts b/apps/scheduler/src/index.ts index dce1509fe..71ba9382a 100644 --- a/apps/scheduler/src/index.ts +++ b/apps/scheduler/src/index.ts @@ -30,6 +30,7 @@ const POLL_INTERVAL_MS = parseInt( 10, ); const HEALTH_PORT = parseInt(process.env.PORT || "8080", 10); +const API_URL = process.env.API_URL || "http://api:80"; /** * Parse per-worker-type queue depth config from environment. @@ -142,6 +143,8 @@ async function main(): Promise { db, createQueueClient, ppPollIntervalMs, + 30, + API_URL, ); handlerDispatcher.start(); console.log("[Scheduler] Handler dispatcher (DAG) started"); diff --git a/apps/workers/report-generator/Dockerfile b/apps/workers/report-generator/Dockerfile index 62a5f2646..3cfd18150 100644 --- a/apps/workers/report-generator/Dockerfile +++ b/apps/workers/report-generator/Dockerfile @@ -15,7 +15,6 @@ COPY packages/shared/tsconfig.json ./packages/shared/ COPY packages/shared/src ./packages/shared/src/ COPY apps/workers/report-generator/tsconfig.json ./apps/workers/report-generator/ COPY apps/workers/report-generator/src ./apps/workers/report-generator/src/ -COPY apps/workers/report-generator/handler.yaml ./apps/workers/report-generator/ RUN pnpm --filter shared build && pnpm --filter report-generator build @@ -44,7 +43,6 @@ RUN pnpm install --frozen-lockfile --prod COPY --from=builder /app/packages/shared/dist ./packages/shared/dist/ COPY --from=builder /app/apps/workers/report-generator/dist ./apps/workers/report-generator/dist/ -COPY --from=builder /app/apps/workers/report-generator/handler.yaml ./apps/workers/report-generator/handler.yaml WORKDIR /app/apps/workers/report-generator diff --git a/apps/workers/report-generator/handler.yaml b/apps/workers/report-generator/handler.yaml deleted file mode 100644 index f7e14d83e..000000000 --- a/apps/workers/report-generator/handler.yaml +++ /dev/null @@ -1,12 +0,0 @@ -# Post-process handler registration metadata. -# Read by the generic register-handler script and POSTed to the -# scheduler's POST /handlers/register endpoint on deploy. -_id: pp-report -type: post-process-handler -version: 1 -queue: report-queue -selector: report -autoBackfill: false -dependsOn: - - pp-atif - - pp-taxonomy diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml index a2fbe32b5..0f9a0753e 100644 --- a/docker-compose.dev.yml +++ b/docker-compose.dev.yml @@ -204,10 +204,6 @@ services: build: target: dev - register-handler-report-generator: - build: - target: dev - post-processor: build: target: dev diff --git a/docker-compose.yml b/docker-compose.yml index 53cdc0da1..164946b0e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -366,6 +366,7 @@ services: SCHEDULER_QUEUE_DEPTH_CODER_ACP_COPILOT: "2" SCHEDULER_POLL_INTERVAL_MS: "2000" PORT: "8080" + API_URL: http://api:80 depends_on: mongodb: condition: service_healthy @@ -639,8 +640,6 @@ services: condition: service_healthy api: condition: service_started - register-handler-report-generator: - condition: service_completed_successfully taxonomy-handler: build: @@ -687,21 +686,6 @@ services: restart: "no" entrypoint: ["npx", "tsx", "packages/shared/src/scripts/register-handler.ts"] - register-handler-report-generator: - build: - context: . - dockerfile: apps/workers/report-generator/Dockerfile - profiles: [report] - environment: - <<: *common-env - HANDLER_YAML_PATH: apps/workers/report-generator/handler.yaml - SCHEDULER_URL: http://scheduler:8080 - depends_on: - scheduler: - condition: service_started - restart: "no" - entrypoint: ["npx", "tsx", "packages/shared/src/scripts/register-handler.ts"] - register-handler-post-processor: build: context: . diff --git a/docs/architecture/post-processing.md b/docs/architecture/post-processing.md index d16d6294f..a9fc61d42 100644 --- a/docs/architecture/post-processing.md +++ b/docs/architecture/post-processing.md @@ -34,7 +34,7 @@ Two paths trigger post-processing: - Updates `run.turns.$.atifUrl` in the request document 4. On success, stamps `run.handlerStatus["pp-atif"] = { status: "done", version: N }` (while legacy `run.postProcessorVersion` / `run.postProcessorStatus` may still be mirrored during the transition) -5. Triggers downstream taxonomy/report handlers once the scheduler sees the dependency graph is satisfied +5. Triggers the downstream taxonomy handler once the scheduler sees the dependency graph is satisfied. (Reports are **not** a DAG handler — see [Report Triggering](#report-triggering-on-dag-drain).) ## Taxonomy Generation @@ -120,7 +120,7 @@ processor.start(); The post-processor uses a version-based re-processing scheme: -- Each handler is registered independently in the `services` collection using a `post-process-handler` document keyed by handler ID (for example `pp-atif`, `pp-taxonomy`, `pp-report`) +- Each handler is registered independently in the `services` collection using a `post-process-handler` document keyed by handler ID (for example `pp-atif`, `pp-taxonomy`) - Each registration stores the handler `version`, queue name, selector, `autoBackfill` behavior, and `dependsOn` DAG edges - The scheduler compares each request's per-handler status/version state (for example `run.handlerStatus["pp-atif"]`) against the registered handler entry for that selector - Requests with missing or outdated handler state are re-dispatched for that specific handler once its dependencies are satisfied @@ -154,11 +154,61 @@ flowchart LR **Where it runs:** -- **Docker Compose:** one `register-handler-` init service per handler (`pp-atif`, `pp-taxonomy`, `pp-report`) runs the generic script via `tsx`, gated on the scheduler being up. The worker waits for its registration service to complete. -- **Kubernetes:** a `register-handler-post-processor` Job runs the compiled script (`node packages/shared/dist/scripts/register-handler.js`) on each deploy. Only `pp-atif` is registered in K8s today because it is the only post-process handler deployed to the cluster; `pp-taxonomy` and `pp-report` are registered in Compose only until the taxonomy worker is deployed to K8s and report generation moves onto the DAG. The scheduler exposes a `Service` (`scheduler.scoped.svc.cluster.local:8080`) so Jobs and workers can reach `/handlers/register` and the notify endpoints. +- **Docker Compose:** one `register-handler-` init service per handler (`pp-atif`, `pp-taxonomy`) runs the generic script via `tsx`, gated on the scheduler being up. The worker waits for its registration service to complete. +- **Kubernetes:** a `register-handler-post-processor` Job runs the compiled script (`node packages/shared/dist/scripts/register-handler.js`) on each deploy. Only `pp-atif` is registered in K8s today because it is the only post-process handler deployed to the cluster; `pp-taxonomy` is registered in Compose only until the taxonomy worker is deployed to K8s. The scheduler exposes a `Service` (`scheduler.scoped.svc.cluster.local:8080`) so Jobs and workers can reach `/handlers/register` and the notify endpoints. To **add or change a handler**, edit its `handler.yaml` (bump `version`, adjust `dependsOn`, etc.) — no code or migration changes are needed for registration. +## Report Triggering on DAG Drain + +Reports are intentionally **not** modeled as a DAG handler. The report-generator +worker is keyed by `reportId` and requires a `templateId`, whereas the DAG +dispatches a generic `{ type, requestId, runId }` message — so a report node +could never process a DAG message. Reports are also fundamentally different from +post-process handlers: they are parameterized (per `templateId`), N-per-run (one +per matching template), and trigger-gated (each template has its own +`ReportTrigger`). + +Instead, the scheduler watches for a run's handler DAG to **drain** and then +calls the existing `POST /api/v1/reports/trigger` endpoint, which evaluates every +active template's trigger and creates the properly-templated `ReportDocument`(s). + +```mermaid +flowchart LR + RT["run done"] --> DAG["scheduler dispatches DAG
(pp-atif → pp-taxonomy)"] + DAG -->|"all handlers terminal"| DR{DAG drained?} + DR -->|yes| TRIG["POST /api/v1/reports/trigger
{ requestId }"] + TRIG --> API["API evaluates each template trigger
→ ReportDocument + report-queue {reportId}"] + API --> RG["report-generator (unchanged)"] +``` + +**Drain definition.** A handler is _terminal_ when its status is `done` or +`failed`, **or** when its status is absent but a transitive dependency `failed` +(so it can never run — effectively blocked). The DAG is drained when every +registered handler is terminal. A run with **zero** registered handlers is +vacuously drained, so reports trigger immediately on run completion. + +**Trigger regardless of handler success.** A flaky taxonomy must not block report +generation (reports analyze the run/ATIF), so the scheduler triggers reports +whenever the DAG drains — not only when every handler succeeded. + +**Exactly-once, attempt-scoped.** Before POSTing, the scheduler atomically claims +a per-attempt guard (`run.reportsTriggeredAt`) via `findOneAndUpdate` filtered by +`{ _id: requestId, "run._id": runId, "run.status": "done", "run.reportsTriggeredAt": { $exists: false } }`. +Scoping by `run._id` ensures a stale notify or a concurrent retry can never fire +reports for — or roll back the guard of — a different attempt. If the POST fails, +the guard is rolled back (also `run._id`-scoped) so the 30s poll safety net +retries. + +**Where it fires.** `maybeTriggerReports(requestId, runId)` runs at the end of +`onRunTerminal` (handles zero-handler / already-drained runs), both branches of +`onHandlerComplete` (success **and** the failure early-return, since a failure can +drain the DAG by blocking descendants), and a `pollTriggerReports()` scan in the +scheduler's 30s poll loop (durable backstop for dropped notifications). + +The scheduler reaches the API via the `API_URL` env var (`http://api:80` in +Compose, `http://api.scoped.svc.cluster.local:80` in K8s). + ## Status Lifecycle ```mermaid @@ -190,6 +240,7 @@ stateDiagram-v2 | `TAXONOMY_MODEL` | `gpt-4.1` | Copilot SDK model used by the taxonomy handler | | `SESSION_TIMEOUT_MS` | `300000` | Timeout for report/taxonomy Copilot SDK sessions | | `SCHEDULER_URL` | _(unset)_ | Scheduler base URL — used by handlers to notify completion and by the register-handler script to reach `/handlers/register` | +| `API_URL` | `http://api:80` | API base URL the **scheduler** uses to call `POST /api/v1/reports/trigger` when a run's handler DAG drains | | `HANDLER_YAML_PATH` | _(unset)_ | Path to a handler's `handler.yaml`, read by the generic `register-handler` script | ## Infrastructure diff --git a/packages/db-migrations/src/migrations/018-migrate-services-to-handler-dag.ts b/packages/db-migrations/src/migrations/018-migrate-services-to-handler-dag.ts index b82b4335c..bcb3b3ade 100644 --- a/packages/db-migrations/src/migrations/018-migrate-services-to-handler-dag.ts +++ b/packages/db-migrations/src/migrations/018-migrate-services-to-handler-dag.ts @@ -7,8 +7,11 @@ import type { MigrationInterface } from "mongo-migrate-ts"; /** * Migration 018: Remove the legacy "post-processor" service entry. * - * Handler service registration (pp-atif, pp-taxonomy, pp-report) is now owned - * by each worker's register-version.ts script, run as a K8s Job on deploy. + * Handler service registration (pp-atif, pp-taxonomy) is now owned + * by each worker's handler.yaml + the generic register-handler script, + * which POSTs to the scheduler's POST /handlers/register endpoint on deploy. + * Reports are not a DAG handler — the scheduler triggers report generation + * (POST /api/v1/reports/trigger) once the DAG drains. * This migration only cleans up the old single-entry format. */ export class MigrateServicesToHandlerDag implements MigrationInterface { diff --git a/packages/db-migrations/src/migrations/019-add-handler-status-index.ts b/packages/db-migrations/src/migrations/019-add-handler-status-index.ts index ecdb0352a..577dc8901 100644 --- a/packages/db-migrations/src/migrations/019-add-handler-status-index.ts +++ b/packages/db-migrations/src/migrations/019-add-handler-status-index.ts @@ -21,14 +21,6 @@ const HANDLER_STATUS_INDEXES = [ updatedAt: -1 as const, }, }, - { - name: "idx_handler_dispatch_report", - key: { - "run.handlerStatus.pp-report.status": 1 as const, - "run.status": 1 as const, - updatedAt: -1 as const, - }, - }, ] as const; export class AddHandlerStatusIndex implements MigrationInterface { diff --git a/packages/shared/src/types/types.ts b/packages/shared/src/types/types.ts index ccd7d7805..1a176e9c1 100644 --- a/packages/shared/src/types/types.ts +++ b/packages/shared/src/types/types.ts @@ -279,8 +279,13 @@ export interface RunState { aiCallCount?: number; rawChatUrl?: string; rawChatFormat?: string; - /** Per-handler post-processing status. Keys are handler IDs (e.g. "pp-atif", "pp-taxonomy", "pp-report"). */ + /** Per-handler post-processing status. Keys are handler IDs (e.g. "pp-atif", "pp-taxonomy"). */ handlerStatus?: Record; + /** Set once the scheduler has triggered report generation for this run after + * the handler DAG drained (every handler reached a terminal state). Acts as + * an exactly-once guard so the scheduler POSTs /api/v1/reports/trigger at + * most once per run, even under notify/poll races. */ + reportsTriggeredAt?: Date; /** @deprecated Use handlerStatus["pp-atif"].version instead. Kept for migration compatibility. */ postProcessorVersion?: number; /** @deprecated Use handlerStatus["pp-atif"].status instead. Kept for migration compatibility. */ From c6cd9b25c44db1b132ff5e07ef521a64713549e8 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Tue, 9 Jun 2026 17:21:44 -0700 Subject: [PATCH 008/210] feat(taxonomy): add dev CLI, API-based ATIF fetch, and default to gpt-5.4 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Extract the Copilot SDK taxonomy-generation loop into a shared, side-effect-free generateTaxonomy() used by both the worker and a new developer CLI (src/cli.ts, `pnpm taxonomy`). The CLI runs generation against any local or integration run, streams session events, and writes the validated taxonomy to a file — making it easy to troubleshoot and A/B models without the full queue/scheduler pipeline. Switch get_atif_trajectory to fetch ATIF through the run-scoped API endpoint instead of reading blob storage directly, so the CLI needs only an API URL + token (no storage connection string). Change the default TAXONOMY_MODEL from gpt-4.1 to gpt-5.4. A/B testing nine models on a multi-iteration run containing a real defect (agent lost context in iteration 2) showed verdicts ranging 72-100: weaker models (incl. gpt-4.1) missed the critical failure entirely, while gpt-5.4 caught it at the lowest token cost of the models tested. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ENV_VARIABLES.md | 4 +- apps/workers/taxonomy/package.json | 1 + apps/workers/taxonomy/src/cli.ts | 206 ++++++++++++++++++ apps/workers/taxonomy/src/index.ts | 2 +- .../taxonomy/src/taxonomy-generator.ts | 195 +++++++++++++++++ .../taxonomy/src/taxonomy-queue-processor.ts | 170 +-------------- apps/workers/taxonomy/src/tools.ts | 30 ++- docker-compose.yml | 2 +- docs/architecture/post-processing.md | 37 +++- package.json | 1 + 10 files changed, 468 insertions(+), 180 deletions(-) create mode 100644 apps/workers/taxonomy/src/cli.ts create mode 100644 apps/workers/taxonomy/src/taxonomy-generator.ts diff --git a/ENV_VARIABLES.md b/ENV_VARIABLES.md index 5d62a193a..cd43d79bc 100644 --- a/ENV_VARIABLES.md +++ b/ENV_VARIABLES.md @@ -286,11 +286,13 @@ Git commit hash embedded in reporter metadata. Automatically set during CI/CD bu Azure Storage Queue name for taxonomy-generation jobs. The scheduler enqueues `{ type: "taxonomy", requestId, runId }` messages here after the `pp-atif` dependency completes, and the taxonomy worker polls this queue. ### TAXONOMY_MODEL -**Default:** `gpt-4.1` +**Default:** `gpt-5.4` **Type:** string The LLM model used by the taxonomy worker (via the Copilot SDK) to generate structured taxonomy JSON from run metadata and ATIF trajectories. +> **Model choice matters for taxonomy quality.** A/B testing across nine models on a multi-iteration run with a real defect (agent lost context in iteration 2) showed the verdict ranged from 72 to 100 depending on the model. `gpt-4.1` (the previous default) missed action items and, on harder runs, produced the thinnest output; weaker models rubber-stamped a buggy run with a perfect score. `gpt-5.4` was the best value: it correctly caught the critical defect while using the fewest tokens and lowest cost of the models tested. Stronger alternatives (e.g. `claude-opus-4-7`) yield richer evidence at higher token cost; avoid `gpt-5.3-codex` as a default (≈1M tokens / ~7 min per run). + ### SCOPE_MT_API_URL **Default:** `http://localhost:3001` (local), `http://api:80` (Docker) **Type:** URL string diff --git a/apps/workers/taxonomy/package.json b/apps/workers/taxonomy/package.json index aacbfc4f1..52cdd6b2f 100644 --- a/apps/workers/taxonomy/package.json +++ b/apps/workers/taxonomy/package.json @@ -7,6 +7,7 @@ "build": "tsc", "dev": "tsx watch src/index.ts", "start": "node dist/index.js", + "taxonomy": "tsx src/cli.ts", "lint": "eslint src/" }, "dependencies": { diff --git a/apps/workers/taxonomy/src/cli.ts b/apps/workers/taxonomy/src/cli.ts new file mode 100644 index 000000000..a5f51f600 --- /dev/null +++ b/apps/workers/taxonomy/src/cli.ts @@ -0,0 +1,206 @@ +#!/usr/bin/env npx tsx +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * Taxonomy post-processor developer CLI. + * + * Invokes the taxonomy generation loop directly against an existing requestId, + * streams the Copilot SDK session events live, and saves the validated taxonomy + * to a local JSON file. This is a developer/troubleshooting tool only — it never + * writes to Mongo (handlerStatus) or blob storage (taxonomy.json) and does not + * notify the scheduler. + * + * Usage: + * npx tsx src/cli.ts [options] + * pnpm taxonomy [options] + * + * Options: + * --run, -r Run id for the prompt/logging (default: active run from API). + * --model Override TAXONOMY_MODEL (e.g. a reasoning model). + * --timeout Override SESSION_TIMEOUT_MS (per-attempt session timeout). + * --output, -o Output file path (default: taxonomy-.json). + * --stdout Also print the taxonomy JSON to stdout. + * --quiet Suppress live session-event streaming on stderr. + * --help, -h Show this help. + */ +import "dotenv/config"; +import { writeFile } from "node:fs/promises"; +import { resolve } from "node:path"; +import { SessionEvent } from "@github/copilot-sdk"; +import { TokenManagerClient, type LogEvent, type RequestDocument } from "shared"; +import { generateTaxonomy } from "./taxonomy-generator.js"; + +interface CliArgs { + requestId: string; + runId?: string; + model?: string; + timeoutMs?: number; + output?: string; + stdout: boolean; + quiet: boolean; +} + +function printHelp(): void { + process.stderr.write( + [ + "Taxonomy post-processor developer CLI", + "", + "Usage: npx tsx src/cli.ts [options]", + "", + "Options:", + " --run, -r Run id for the prompt/logging (default: active run from API)", + " --model Override TAXONOMY_MODEL", + " --timeout Override SESSION_TIMEOUT_MS (per-attempt session timeout)", + " --output, -o Output file path (default: taxonomy-.json)", + " --stdout Also print the taxonomy JSON to stdout", + " --quiet Suppress live session-event streaming on stderr", + " --help, -h Show this help", + "", + ].join("\n"), + ); +} + +function parseArgs(argv: string[]): CliArgs | undefined { + const args: Partial & { stdout: boolean; quiet: boolean } = { stdout: false, quiet: false }; + const positionals: string[] = []; + + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i]; + switch (arg) { + case "--help": + case "-h": + printHelp(); + return undefined; + case "--run": + case "-r": + args.runId = argv[++i]; + break; + case "--model": + args.model = argv[++i]; + break; + case "--timeout": + args.timeoutMs = Number(argv[++i]); + break; + case "--output": + case "-o": + args.output = argv[++i]; + break; + case "--stdout": + args.stdout = true; + break; + case "--quiet": + args.quiet = true; + break; + default: + if (arg.startsWith("-")) { + throw new Error(`Unknown option: ${arg}`); + } + positionals.push(arg); + } + } + + const requestId = positionals[0]; + if (!requestId) { + throw new Error("Missing required argument"); + } + if (args.timeoutMs !== undefined && Number.isNaN(args.timeoutMs)) { + throw new Error("--timeout must be a number (milliseconds)"); + } + + return { ...args, requestId }; +} + +async function resolveRunId(apiBaseUrl: string, requestId: string, explicit?: string): Promise { + if (explicit) return explicit; + try { + const response = await fetch(`${apiBaseUrl}/api/v1/requests/${requestId}`); + if (response.ok) { + const request: RequestDocument = await response.json(); + if (request.run?._id) return request.run._id; + } + } catch { + // fall through to requestId fallback + } + return requestId; +} + +function summarizeEvent(event: SessionEvent): string | undefined { + switch (event.type) { + case "session.start": + return `session.start model=${event.data.selectedModel}`; + case "session.error": + return `session.error ${event.data.errorType}: ${event.data.message}`; + case "tool.execution_start": + return `tool.start ${event.data.toolName} ${JSON.stringify(event.data.arguments ?? {})}`; + case "tool.execution_complete": + return `tool.done ${event.data.success ? "ok" : "FAILED"}${event.data.error ? ` ${event.data.error.message}` : ""}`; + case "assistant.message": + return `assistant.message (${event.data.content.length} chars)`; + default: + return undefined; + } +} + +async function main(): Promise { + let parsed: CliArgs | undefined; + try { + parsed = parseArgs(process.argv.slice(2)); + } catch (error) { + process.stderr.write(`Error: ${error instanceof Error ? error.message : String(error)}\n\n`); + printHelp(); + process.exit(2); + } + if (!parsed) return; // help shown + + const apiBaseUrl = process.env.SCOPE_MT_API_URL || "http://localhost:3001"; + const taxonomyModel = parsed.model || process.env.TAXONOMY_MODEL || "gpt-5.4"; + const sessionTimeoutMs = parsed.timeoutMs ?? (Number(process.env.SESSION_TIMEOUT_MS) || 5 * 60 * 1000); + const outputPath = resolve(parsed.output ?? `taxonomy-${parsed.requestId}.json`); + + const githubToken = process.env.GITHUB_TOKEN + ? process.env.GITHUB_TOKEN + : await new TokenManagerClient(process.env.TOKEN_MANAGER_URL).acquireToken("copilot-sdk"); + + const runId = await resolveRunId(apiBaseUrl, parsed.requestId, parsed.runId); + + const log = (level: LogEvent["level"], msg: string, data?: Record): void => { + if (parsed.quiet) return; + const suffix = data && Object.keys(data).length > 0 ? ` ${JSON.stringify(data)}` : ""; + process.stderr.write(`[${level}] ${msg}${suffix}\n`); + }; + + process.stderr.write( + `Generating taxonomy: requestId=${parsed.requestId} runId=${runId} model=${taxonomyModel} timeout=${sessionTimeoutMs}ms\n`, + ); + + const onEvent = parsed.quiet + ? undefined + : (event: SessionEvent): void => { + const summary = summarizeEvent(event); + if (summary) process.stderr.write(` · ${summary}\n`); + }; + + const taxonomy = await generateTaxonomy({ + requestId: parsed.requestId, + runId, + apiBaseUrl, + taxonomyModel, + githubToken, + sessionTimeoutMs, + log, + onEvent, + }); + + const json = JSON.stringify(taxonomy, null, 2); + await writeFile(outputPath, `${json}\n`, "utf-8"); + process.stderr.write(`\nTaxonomy written to ${outputPath}\n`); + if (parsed.stdout) { + process.stdout.write(`${json}\n`); + } +} + +main().catch((error) => { + process.stderr.write(`\nTaxonomy generation failed: ${error instanceof Error ? error.message : String(error)}\n`); + process.exit(1); +}); diff --git a/apps/workers/taxonomy/src/index.ts b/apps/workers/taxonomy/src/index.ts index 2ee1a8118..b1a4f322b 100644 --- a/apps/workers/taxonomy/src/index.ts +++ b/apps/workers/taxonomy/src/index.ts @@ -16,7 +16,7 @@ const config: TaxonomyQueueProcessorConfig = { redisHost: process.env.REDIS_HOST || "localhost", redisPort: Number(process.env.REDIS_PORT) || 6379, redisPassword: process.env.REDIS_PASSWORD || "", - taxonomyModel: process.env.TAXONOMY_MODEL || "gpt-4.1", + taxonomyModel: process.env.TAXONOMY_MODEL || "gpt-5.4", apiBaseUrl: process.env.SCOPE_MT_API_URL || "http://localhost:3001", sessionTimeoutMs: Number(process.env.SESSION_TIMEOUT_MS) || 5 * 60 * 1000, schedulerUrl: process.env.SCHEDULER_URL, diff --git a/apps/workers/taxonomy/src/taxonomy-generator.ts b/apps/workers/taxonomy/src/taxonomy-generator.ts new file mode 100644 index 000000000..0df69d2c5 --- /dev/null +++ b/apps/workers/taxonomy/src/taxonomy-generator.ts @@ -0,0 +1,195 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { CopilotClient, SessionEvent } from "@github/copilot-sdk"; +import { + type LogEvent, + taxonomySchema, + type TaxonomyDocument, +} from "shared"; +import { TAXONOMY_SYSTEM_PROMPT } from "./prompt.js"; +import { createTaxonomyTools } from "./tools.js"; + +export const DEFAULT_SESSION_TIMEOUT_MS = 5 * 60 * 1000; +const DELTA_LOG_INTERVAL = 2_000; + +type TaxonomyLogFn = ( + level: LogEvent["level"], + msg: string, + data?: Record, +) => Promise | void; + +export interface GenerateTaxonomyParams { + requestId: string; + runId: string; + apiBaseUrl: string; + taxonomyModel: string; + githubToken: string; + sessionTimeoutMs?: number; + log: TaxonomyLogFn; + /** Optional raw session-event hook (used by the dev CLI to render live progress). */ + onEvent?: (event: SessionEvent) => void; +} + +/** + * Runs the Copilot SDK taxonomy generation loop and returns a schema-validated + * taxonomy document. This is side-effect-free with respect to Mongo and blob + * storage (it only reads run data and ATIF trajectories through the API); + * persistence is the caller's responsibility. + */ +export async function generateTaxonomy(params: GenerateTaxonomyParams): Promise { + const { requestId, runId, apiBaseUrl, taxonomyModel, githubToken, log, onEvent } = params; + const client = new CopilotClient({ githubToken }); + const tools = createTaxonomyTools(apiBaseUrl, requestId); + const timeoutMs = params.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS; + + let streamedResponse = ""; + let latestMessage = ""; + let lastLoggedCharCount = 0; + const toolNames = new Map(); + + try { + const session = await client.createSession({ + model: taxonomyModel, + streaming: true, + tools, + systemMessage: { mode: "replace", content: TAXONOMY_SYSTEM_PROMPT }, + }); + + session.on((event: SessionEvent) => { + onEvent?.(event); + switch (event.type) { + case "session.start": + void log("info", "Copilot session started", { + sessionId: event.data.sessionId, + model: event.data.selectedModel, + }); + break; + case "session.error": + void log("error", `Session error: ${event.data.message}`, { errorType: event.data.errorType }); + break; + case "tool.execution_start": + toolNames.set(event.data.toolCallId, event.data.toolName); + void log("info", `Tool call: ${event.data.toolName}`, { + toolCallId: event.data.toolCallId, + arguments: event.data.arguments as Record | undefined, + }); + break; + case "tool.execution_complete": { + const toolName = toolNames.get(event.data.toolCallId) ?? "unknown"; + toolNames.delete(event.data.toolCallId); + void log("info", `Tool result: ${toolName} (${event.data.success ? "success" : "failed"})`, { + toolCallId: event.data.toolCallId, + error: event.data.error?.message, + }); + break; + } + case "assistant.message_delta": + streamedResponse += event.data.deltaContent; + if (streamedResponse.length - lastLoggedCharCount >= DELTA_LOG_INTERVAL) { + lastLoggedCharCount = streamedResponse.length; + void log("info", `Generating taxonomy… (${streamedResponse.length} chars so far)`); + } + break; + case "assistant.message": + latestMessage = event.data.content; + break; + } + }); + + let attempts = 0; + const maxAttempts = 3; + let prompt = [ + `Generate taxonomy JSON for request ${requestId} and run ${runId}.`, + "Use get_run_data first, then inspect ATIF trajectories that materially affect the classification.", + "Return only raw JSON that satisfies the taxonomy schema.", + ].join(" "); + let lastJson: string | undefined; + + while (attempts < maxAttempts) { + attempts += 1; + streamedResponse = ""; + latestMessage = ""; + lastLoggedCharCount = 0; + + await log("info", `Sending taxonomy prompt to Copilot SDK (attempt ${attempts}/${maxAttempts})`, { + requestId, + runId, + timeoutMs, + }); + + const response = await session.sendAndWait({ prompt }, timeoutMs); + const responseText = response?.data.content?.trim() || latestMessage.trim() || streamedResponse.trim(); + + if (!responseText) { + throw new Error("Copilot SDK returned an empty taxonomy response"); + } + + const jsonText = extractJson(responseText); + lastJson = jsonText; + + let parsedJson: unknown; + try { + parsedJson = JSON.parse(jsonText) as unknown; + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + if (attempts >= maxAttempts) { + throw new Error(`Taxonomy response was not valid JSON after ${maxAttempts} attempts: ${errorMessage}`); + } + + prompt = [ + "Your previous response was not valid JSON.", + `JSON parse error: ${errorMessage}.`, + "Return the full taxonomy document again as raw JSON only, with no markdown fences or commentary.", + "Replace the entire response with corrected JSON.", + ].join(" "); + continue; + } + + const validation = taxonomySchema.safeParse(parsedJson); + if (validation.success) { + return validation.data; + } + + const validationErrors = formatValidationErrors(validation.error.issues); + await log("warn", `Taxonomy validation failed on attempt ${attempts}`, { + issues: validationErrors, + }); + + if (attempts >= maxAttempts) { + throw new Error( + `Taxonomy schema validation failed after ${maxAttempts} attempts: ${validationErrors.join(" | ")}`, + ); + } + + prompt = [ + "Your previous taxonomy JSON did not satisfy the schema.", + "Correct the document and return the entire replacement JSON object.", + "Do not include markdown fences or commentary.", + `Validation errors: ${validationErrors.join("; ")}`, + lastJson ? `Previous JSON: ${lastJson}` : "", + ].filter(Boolean).join(" "); + } + + throw new Error("Taxonomy generation ended without a valid document"); + } finally { + await client.stop().catch(() => undefined); + } +} + +function extractJson(responseText: string): string { + const trimmed = responseText.trim(); + if (!trimmed.startsWith("```")) { + return trimmed; + } + + const fenceMatch = trimmed.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i); + return fenceMatch?.[1]?.trim() ?? trimmed; +} + +function formatValidationErrors(issues: Array<{ path: PropertyKey[]; message: string }>): string[] { + return issues.map((issue) => { + const path = issue.path.length > 0 ? issue.path.map((segment) => String(segment)).join(".") : ""; + return `${path}: ${issue.message}`; + }); +} diff --git a/apps/workers/taxonomy/src/taxonomy-queue-processor.ts b/apps/workers/taxonomy/src/taxonomy-queue-processor.ts index 29fb3b61a..d3c7495d3 100644 --- a/apps/workers/taxonomy/src/taxonomy-queue-processor.ts +++ b/apps/workers/taxonomy/src/taxonomy-queue-processor.ts @@ -2,26 +2,22 @@ // Licensed under the MIT License. import { DequeuedMessageItem } from "@azure/storage-queue"; -import { CopilotClient, SessionEvent } from "@github/copilot-sdk"; import { BaseQueueProcessor, BlobStorage, type BaseQueueProcessorConfig, type LogEvent, type RequestDocument, - taxonomySchema, TokenManagerClient, type TaxonomyDocument, type VisibilityHeartbeat, withRetry, } from "shared"; -import { TAXONOMY_SYSTEM_PROMPT } from "./prompt.js"; -import { createTaxonomyTools } from "./tools.js"; +import { generateTaxonomy } from "./taxonomy-generator.js"; const HANDLER_ID = "pp-taxonomy"; const HANDLER_VERSION = 1; const DEFAULT_SESSION_TIMEOUT_MS = 5 * 60 * 1000; -const DELTA_LOG_INTERVAL = 2_000; interface TaxonomyQueueMessage { type: "taxonomy"; @@ -156,143 +152,17 @@ export class TaxonomyQueueProcessor extends BaseQueueProcessor log: (level: LogEvent["level"], msg: string, data?: Record) => Promise, ): Promise { const githubToken = await this.tokenClient.acquireToken("copilot-sdk"); - const client = new CopilotClient({ githubToken }); - const tools = createTaxonomyTools(this.taxonomyConfig.apiBaseUrl, requestId, this.blobStorage); - const timeoutMs = this.taxonomyConfig.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS; - - let streamedResponse = ""; - let latestMessage = ""; - let lastLoggedCharCount = 0; - const toolNames = new Map(); - - try { - await log("info", "Acquired Copilot SDK token"); - - const session = await client.createSession({ - model: this.taxonomyConfig.taxonomyModel, - streaming: true, - tools, - systemMessage: { mode: "replace", content: TAXONOMY_SYSTEM_PROMPT }, - }); - - session.on((event: SessionEvent) => { - switch (event.type) { - case "session.start": - void log("info", "Copilot session started", { - sessionId: event.data.sessionId, - model: event.data.selectedModel, - }); - break; - case "session.error": - void log("error", `Session error: ${event.data.message}`, { errorType: event.data.errorType }); - break; - case "tool.execution_start": - toolNames.set(event.data.toolCallId, event.data.toolName); - void log("info", `Tool call: ${event.data.toolName}`, { - toolCallId: event.data.toolCallId, - arguments: event.data.arguments as Record | undefined, - }); - break; - case "tool.execution_complete": { - const toolName = toolNames.get(event.data.toolCallId) ?? "unknown"; - toolNames.delete(event.data.toolCallId); - void log("info", `Tool result: ${toolName} (${event.data.success ? "success" : "failed"})`, { - toolCallId: event.data.toolCallId, - error: event.data.error?.message, - }); - break; - } - case "assistant.message_delta": - streamedResponse += event.data.deltaContent; - if (streamedResponse.length - lastLoggedCharCount >= DELTA_LOG_INTERVAL) { - lastLoggedCharCount = streamedResponse.length; - void log("info", `Generating taxonomy… (${streamedResponse.length} chars so far)`); - } - break; - case "assistant.message": - latestMessage = event.data.content; - break; - } - }); - - let attempts = 0; - const maxAttempts = 3; - let prompt = [ - `Generate taxonomy JSON for request ${requestId} and run ${runId}.`, - "Use get_run_data first, then inspect ATIF trajectories that materially affect the classification.", - "Return only raw JSON that satisfies the taxonomy schema.", - ].join(" "); - let lastJson: string | undefined; - - while (attempts < maxAttempts) { - attempts += 1; - streamedResponse = ""; - latestMessage = ""; - lastLoggedCharCount = 0; - - await log("info", `Sending taxonomy prompt to Copilot SDK (attempt ${attempts}/${maxAttempts})`, { - requestId, - runId, - timeoutMs, - }); - - const response = await session.sendAndWait({ prompt }, timeoutMs); - const responseText = response?.data.content?.trim() || latestMessage.trim() || streamedResponse.trim(); - - if (!responseText) { - throw new Error("Copilot SDK returned an empty taxonomy response"); - } - - const jsonText = extractJson(responseText); - lastJson = jsonText; - - let parsedJson: unknown; - try { - parsedJson = JSON.parse(jsonText) as unknown; - } catch (error) { - const errorMessage = error instanceof Error ? error.message : String(error); - if (attempts >= maxAttempts) { - throw new Error(`Taxonomy response was not valid JSON after ${maxAttempts} attempts: ${errorMessage}`); - } - - prompt = [ - "Your previous response was not valid JSON.", - `JSON parse error: ${errorMessage}.`, - "Return the full taxonomy document again as raw JSON only, with no markdown fences or commentary.", - "Replace the entire response with corrected JSON.", - ].join(" "); - continue; - } - - const validation = taxonomySchema.safeParse(parsedJson); - if (validation.success) { - return validation.data; - } - - const validationErrors = formatValidationErrors(validation.error.issues); - await log("warn", `Taxonomy validation failed on attempt ${attempts}`, { - issues: validationErrors, - }); - - if (attempts >= maxAttempts) { - throw new Error( - `Taxonomy schema validation failed after ${maxAttempts} attempts: ${validationErrors.join(" | ")}`, - ); - } - - prompt = [ - "Your previous taxonomy JSON did not satisfy the schema.", - "Correct the document and return the entire replacement JSON object.", - "Do not include markdown fences or commentary.", - `Validation errors: ${validationErrors.join("; ")}`, - lastJson ? `Previous JSON: ${lastJson}` : "", - ].filter(Boolean).join(" "); - } - - throw new Error("Taxonomy generation ended without a valid document"); - } finally { - await client.stop().catch(() => undefined); - } + await log("info", "Acquired Copilot SDK token"); + + return generateTaxonomy({ + requestId, + runId, + apiBaseUrl: this.taxonomyConfig.apiBaseUrl, + taxonomyModel: this.taxonomyConfig.taxonomyModel, + githubToken, + sessionTimeoutMs: this.taxonomyConfig.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS, + log, + }); } private async notifyHandlerComplete( @@ -319,19 +189,3 @@ export class TaxonomyQueueProcessor extends BaseQueueProcessor } } -function extractJson(responseText: string): string { - const trimmed = responseText.trim(); - if (!trimmed.startsWith("```")) { - return trimmed; - } - - const fenceMatch = trimmed.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i); - return fenceMatch?.[1]?.trim() ?? trimmed; -} - -function formatValidationErrors(issues: Array<{ path: PropertyKey[]; message: string }>): string[] { - return issues.map((issue) => { - const path = issue.path.length > 0 ? issue.path.map((segment) => String(segment)).join(".") : ""; - return `${path}: ${issue.message}`; - }); -} diff --git a/apps/workers/taxonomy/src/tools.ts b/apps/workers/taxonomy/src/tools.ts index 9c92b5b18..ea4eced32 100644 --- a/apps/workers/taxonomy/src/tools.ts +++ b/apps/workers/taxonomy/src/tools.ts @@ -2,22 +2,12 @@ // Licensed under the MIT License. import { defineTool } from "@github/copilot-sdk"; -import { BlobStorage, type ConversationTurn, type RequestDocument } from "shared"; +import { type ConversationTurn, type RequestDocument } from "shared"; interface GetAtifTrajectoryArgs { iteration?: number; } -function resolveSnapshotsBlobName(blobUrl: string): string { - const url = new URL(blobUrl); - const containerPrefix = "/snapshots/"; - const containerIndex = url.pathname.indexOf(containerPrefix); - if (containerIndex === -1) { - throw new Error(`Blob URL does not contain the snapshots container: ${blobUrl}`); - } - return decodeURIComponent(url.pathname.substring(containerIndex + containerPrefix.length)); -} - function selectTurnWithAtif(turns: ConversationTurn[] | undefined, requestedIteration?: number): ConversationTurn | undefined { if (!turns?.length) return undefined; @@ -33,7 +23,6 @@ function selectTurnWithAtif(turns: ConversationTurn[] | undefined, requestedIter export function createTaxonomyTools( apiBaseUrl: string, requestId: string, - blobStorage: BlobStorage, ) { const getRunData = defineTool("get_run_data", { description: @@ -138,12 +127,21 @@ export function createTaxonomyTools( }; } - const blobName = resolveSnapshotsBlobName(selectedTurn.atifUrl); - const buffer = await blobStorage.downloadBlobToBuffer(blobName); - const trajectory: unknown = JSON.parse(buffer.toString("utf-8")); + const runId = request.run?._id; + const iteration = selectedTurn.iteration; + const atifUrl = runId + ? `${apiBaseUrl}/api/v1/requests/${requestId}/runs/${runId}/atif?iteration=${iteration}` + : `${apiBaseUrl}/api/v1/requests/${requestId}/atif?iteration=${iteration}`; + + const atifResponse = await fetch(atifUrl); + if (!atifResponse.ok) { + return { error: `Failed to fetch ATIF trajectory: ${atifResponse.status} ${atifResponse.statusText}` }; + } + + const trajectory: unknown = await atifResponse.json(); return { - iteration: selectedTurn.iteration, + iteration, trajectory, }; } catch (err) { diff --git a/docker-compose.yml b/docker-compose.yml index 164946b0e..0124b6f71 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -649,7 +649,7 @@ services: environment: <<: *common-env AZURE_STORAGE_QUEUE_TAXONOMY: pp-taxonomy-queue - TAXONOMY_MODEL: ${TAXONOMY_MODEL:-gpt-4.1} + TAXONOMY_MODEL: ${TAXONOMY_MODEL:-gpt-5.4} SCOPE_MT_API_URL: http://api:80 SCHEDULER_URL: http://scheduler:8080 GITHUB_TOKEN: ${GITHUB_TOKEN:-} diff --git a/docs/architecture/post-processing.md b/docs/architecture/post-processing.md index a9fc61d42..dadda0544 100644 --- a/docs/architecture/post-processing.md +++ b/docs/architecture/post-processing.md @@ -38,7 +38,7 @@ Two paths trigger post-processing: ## Taxonomy Generation -The taxonomy handler (`apps/workers/taxonomy/`) consumes messages from the dedicated `pp-taxonomy-queue` and produces a structured JSON artifact for a completed run. It uses the GitHub Copilot SDK with a tool-backed session to fetch run metadata from the API and ATIF trajectories from blob storage, then validates the generated JSON against the shared taxonomy Zod schema. +The taxonomy handler (`apps/workers/taxonomy/`) consumes messages from the dedicated `pp-taxonomy-queue` and produces a structured JSON artifact for a completed run. It uses the GitHub Copilot SDK with a tool-backed session to fetch run metadata and ATIF trajectories from the API, then validates the generated JSON against the shared taxonomy Zod schema. ### Flow @@ -46,7 +46,7 @@ The taxonomy handler (`apps/workers/taxonomy/`) consumes messages from the dedic 2. Worker fetches the request document from MongoDB and marks `run.handlerStatus["pp-taxonomy"].status = "processing"` 3. Copilot SDK session calls: - `get_run_data` to fetch the request + active run from the API - - `get_atif_trajectory` to fetch per-iteration ATIF JSON from blob storage + - `get_atif_trajectory` to fetch per-iteration ATIF JSON from the API (`GET /api/v1/requests/:id/runs/:runId/atif?iteration=N`) 4. The worker validates the assistant response with `taxonomySchema.safeParse()` 5. If validation fails, the worker feeds the schema errors back into the same session and retries up to 3 total attempts 6. On success, the worker uploads `taxonomy.json` to `{requestId}/runs/{runId}/taxonomy.json` @@ -77,6 +77,37 @@ The completed run stores the taxonomy blob URL on `run.taxonomyUrl`. The `iteration` query parameter is mandatory only for the ATIF endpoints. ATIF files are also included in archive exports as `iteration-{N}.atif.trajectory.json`. +### Local troubleshooting: taxonomy CLI + +The Copilot SDK generation loop lives in `apps/workers/taxonomy/src/taxonomy-generator.ts` (`generateTaxonomy()`), shared by both the queue processor and a standalone developer CLI (`src/cli.ts`). The CLI invokes generation directly against an existing `requestId`, streams the session events live, and saves the validated taxonomy to a local file — **it never writes to MongoDB, blob storage, or the scheduler** (read-only). It is a developer tool and is intentionally not part of the Scope CLI. + +Because both taxonomy tools (`get_run_data` and `get_atif_trajectory`) read through the API, the CLI needs only an API URL and a Copilot token — no storage connection string. This lets it run against any environment (local or a remote deployment such as integration) given a reachable API. + +```bash +# Local stack (use your worktree's host-mapped API port): +SCOPE_MT_API_URL=http://localhost:3001 \ +GITHUB_TOKEN=$(gh auth token) \ +pnpm taxonomy [--run ] [--model ] [--timeout ] [-o out.json] [--stdout] [--quiet] + +# Integration (read-only against the deployed API): +SCOPE_MT_API_URL=https://msscope-int.azurewebsites.net \ +GITHUB_TOKEN=$(gh auth token) \ +pnpm taxonomy -o taxonomy-int.json +``` + +The root `pnpm taxonomy` script proxies to `pnpm --filter taxonomy-handler taxonomy` (i.e. `tsx src/cli.ts`). + +| Option | Description | +| --- | --- | +| `--run, -r ` | Run id used in the prompt/logging (default: active run resolved from the API) | +| `--model ` | Override `TAXONOMY_MODEL` (e.g. A/B a reasoning model vs the `gpt-5.4` default) | +| `--timeout ` | Override `SESSION_TIMEOUT_MS` (per-attempt session timeout) | +| `--output, -o ` | Output file path (default: `taxonomy-.json` in the cwd) | +| `--stdout` | Also print the taxonomy JSON to stdout | +| `--quiet` | Suppress live session-event streaming on stderr | + +Live progress (tool calls, errors, deltas) is written to stderr so the saved JSON file stays clean. The CLI exits non-zero on failure (empty response, JSON/schema validation failure after 3 attempts, timeout, or model rate limit) and surfaces the underlying error message — making it well suited to diagnosing the oversized-`get_atif_trajectory` paging loop and Copilot model rate limits. + ## Handler Interface The post-processor uses a registry pattern for extensibility: @@ -237,7 +268,7 @@ stateDiagram-v2 | `BATCH_SIZE` | `1` | Messages to process per poll (worker-side) | | `POLL_INTERVAL_MS` | `5000` | Worker queue polling interval | | `SCOPE_MT_API_URL` / `API_BASE_URL` | `http://localhost:3001` | API URL used by report/taxonomy Copilot tools | -| `TAXONOMY_MODEL` | `gpt-4.1` | Copilot SDK model used by the taxonomy handler | +| `TAXONOMY_MODEL` | `gpt-5.4` | Copilot SDK model used by the taxonomy handler | | `SESSION_TIMEOUT_MS` | `300000` | Timeout for report/taxonomy Copilot SDK sessions | | `SCHEDULER_URL` | _(unset)_ | Scheduler base URL — used by handlers to notify completion and by the register-handler script to reach `/handlers/register` | | `API_URL` | `http://api:80` | API base URL the **scheduler** uses to call `POST /api/v1/reports/trigger` when a run's handler DAG drains | diff --git a/package.json b/package.json index 62ce2760d..2905d5efc 100644 --- a/package.json +++ b/package.json @@ -17,6 +17,7 @@ "dev:coder-acp-claude-code": "pnpm --filter coder-acp-claude-code dev", "dev:coder-acp-copilot": "pnpm --filter coder-acp-copilot dev", "dev:report-generator": "pnpm --filter report-generator dev", + "taxonomy": "pnpm --filter taxonomy-handler taxonomy", "docker:up": "scripts/worktree-env.sh && scripts/dev-compose.sh up --build", "docker:up:claude-code": "scripts/worktree-env.sh && scripts/dev-compose.sh --env-file .env --env-file apps/workers/coder-acp-claude-code/versions.env --profile claude-code --profile report up --build", "docker:up:copilot": "scripts/worktree-env.sh && scripts/dev-compose.sh --env-file .env --env-file apps/workers/coder-acp-copilot/versions.env --profile copilot --profile report up --build", From 07127ae483af9d6c1d48d6f34f69cef4d02fcb33 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Wed, 24 Jun 2026 14:34:24 -0700 Subject: [PATCH 009/210] chore: remove taxonomy changes (split to #1053) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- AGENTS.md | 2 - ENV_VARIABLES.md | 28 -- .../openapi-snapshot.test.ts.snap | 63 ----- apps/api/src/archive-har.test.ts | 41 --- apps/api/src/archive-har.ts | 29 +- apps/api/src/index.ts | 2 - apps/api/src/routes/requests/taxonomy.test.ts | 107 -------- apps/api/src/routes/requests/taxonomy.ts | 30 --- apps/portal/src/components/TaxonomyTab.tsx | 248 ------------------ apps/portal/src/lib/api.ts | 10 - apps/portal/src/pages/RunDetail.tsx | 10 - apps/portal/src/types.ts | 1 - apps/scheduler/src/handler-dispatcher.test.ts | 22 +- apps/scheduler/src/notify-routes.test.ts | 8 +- apps/workers/taxonomy/Dockerfile | 50 ---- apps/workers/taxonomy/handler.yaml | 11 - apps/workers/taxonomy/package.json | 24 -- apps/workers/taxonomy/src/cli.ts | 206 --------------- apps/workers/taxonomy/src/index.ts | 30 --- apps/workers/taxonomy/src/prompt.ts | 88 ------- .../taxonomy/src/taxonomy-generator.ts | 195 -------------- .../taxonomy/src/taxonomy-queue-processor.ts | 191 -------------- apps/workers/taxonomy/src/tools.ts | 154 ----------- apps/workers/taxonomy/tsconfig.json | 8 - docker-compose.dev.yml | 20 -- docker-compose.yml | 46 ---- docs/architecture/db-migrations.md | 2 +- docs/architecture/overview.md | 1 - docs/architecture/post-processing.md | 89 ++----- package.json | 5 +- .../018-migrate-services-to-handler-dag.ts | 2 +- .../019-add-handler-status-index.ts | 8 - packages/shared/src/index.ts | 1 - packages/shared/src/schemas/index.ts | 1 - packages/shared/src/schemas/request.ts | 1 - packages/shared/src/schemas/taxonomy.test.ts | 180 ------------- packages/shared/src/schemas/taxonomy.ts | 104 -------- .../src/scripts/register-handler.test.ts | 6 +- packages/shared/src/types/types.ts | 4 +- pnpm-lock.yaml | 25 -- 40 files changed, 41 insertions(+), 2012 deletions(-) delete mode 100644 apps/api/src/routes/requests/taxonomy.test.ts delete mode 100644 apps/api/src/routes/requests/taxonomy.ts delete mode 100644 apps/portal/src/components/TaxonomyTab.tsx delete mode 100644 apps/workers/taxonomy/Dockerfile delete mode 100644 apps/workers/taxonomy/handler.yaml delete mode 100644 apps/workers/taxonomy/package.json delete mode 100644 apps/workers/taxonomy/src/cli.ts delete mode 100644 apps/workers/taxonomy/src/index.ts delete mode 100644 apps/workers/taxonomy/src/prompt.ts delete mode 100644 apps/workers/taxonomy/src/taxonomy-generator.ts delete mode 100644 apps/workers/taxonomy/src/taxonomy-queue-processor.ts delete mode 100644 apps/workers/taxonomy/src/tools.ts delete mode 100644 apps/workers/taxonomy/tsconfig.json delete mode 100644 packages/shared/src/schemas/taxonomy.test.ts delete mode 100644 packages/shared/src/schemas/taxonomy.ts diff --git a/AGENTS.md b/AGENTS.md index 419fb8e6a..de77cbeba 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,7 +19,6 @@ apps/ coder-acp-copilot/ # GitHub Copilot worker (ACP SDK) coder-acp-claude-code/ # Claude Code worker (ACP SDK) report-generator/ # Post-run report generation - taxonomy/ # Post-run taxonomy generation model-scanners/ # Feature detection for Copilot and Anthropic models version-checkers/ # Poll for new agent/tool releases key-updaters/ # GitHub auth cookie management for VS Code Web @@ -54,7 +53,6 @@ Each worker implements the same queue-processor interface but adapts a different | `coder-acp-copilot` | GitHub Copilot | ACP SDK v0.14.1 | | `coder-acp-claude-code` | Claude Code | ACP SDK v0.13.1 | | `report-generator` | — | Copilot SDK | -| `taxonomy` | — | Copilot SDK | Workers consume tasks from Azure Storage Queues (named `queue-`) and write results to MongoDB and Blob Storage. Each has its own Dockerfile and docker-compose profile. diff --git a/ENV_VARIABLES.md b/ENV_VARIABLES.md index cd43d79bc..e56ea082e 100644 --- a/ENV_VARIABLES.md +++ b/ENV_VARIABLES.md @@ -277,34 +277,6 @@ Timeout for the Copilot SDK session used by the report-generator worker. If the Git commit hash embedded in reporter metadata. Automatically set during CI/CD builds. Used to track which version of the report-generator produced a given report. -## Taxonomy Handler Configuration - -### AZURE_STORAGE_QUEUE_TAXONOMY -**Default:** `pp-taxonomy-queue` -**Type:** string - -Azure Storage Queue name for taxonomy-generation jobs. The scheduler enqueues `{ type: "taxonomy", requestId, runId }` messages here after the `pp-atif` dependency completes, and the taxonomy worker polls this queue. - -### TAXONOMY_MODEL -**Default:** `gpt-5.4` -**Type:** string - -The LLM model used by the taxonomy worker (via the Copilot SDK) to generate structured taxonomy JSON from run metadata and ATIF trajectories. - -> **Model choice matters for taxonomy quality.** A/B testing across nine models on a multi-iteration run with a real defect (agent lost context in iteration 2) showed the verdict ranged from 72 to 100 depending on the model. `gpt-4.1` (the previous default) missed action items and, on harder runs, produced the thinnest output; weaker models rubber-stamped a buggy run with a perfect score. `gpt-5.4` was the best value: it correctly caught the critical defect while using the fewest tokens and lowest cost of the models tested. Stronger alternatives (e.g. `claude-opus-4-7`) yield richer evidence at higher token cost; avoid `gpt-5.3-codex` as a default (≈1M tokens / ~7 min per run). - -### SCOPE_MT_API_URL -**Default:** `http://localhost:3001` (local), `http://api:80` (Docker) -**Type:** URL string - -Base URL of the Scope API. The taxonomy worker calls this to fetch the request document and active run state through its Copilot tools. - -### SESSION_TIMEOUT_MS -**Default:** `300000` (5 minutes) -**Type:** integer (milliseconds) - -Timeout for the Copilot SDK session used by the taxonomy worker. If the model does not finish generating a valid taxonomy JSON document within this window, the worker marks `run.handlerStatus.pp-taxonomy` as failed. - ## Scheduler Configuration ### SCHEDULER_POLL_INTERVAL_MS diff --git a/apps/api/src/__snapshots__/openapi-snapshot.test.ts.snap b/apps/api/src/__snapshots__/openapi-snapshot.test.ts.snap index 16ee7fc6d..7912955e3 100644 --- a/apps/api/src/__snapshots__/openapi-snapshot.test.ts.snap +++ b/apps/api/src/__snapshots__/openapi-snapshot.test.ts.snap @@ -2313,9 +2313,6 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` ], "type": "string", }, - "taxonomyUrl": { - "type": "string", - }, "tokenUsage": { "$ref": "#/components/schemas/TokenUsage", }, @@ -7984,40 +7981,6 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` ], }, }, - "/api/v1/requests/{id}/runs/{runId}/taxonomy": { - "get": { - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "string", - }, - }, - { - "in": "path", - "name": "runId", - "required": true, - "schema": { - "type": "string", - }, - }, - ], - "responses": { - "200": { - "description": "Taxonomy v1 JSON document (scorecard, behavior analysis, action list)", - }, - "404": { - "description": "Not found — taxonomy not yet generated", - }, - }, - "summary": "Download taxonomy JSON for a specific attempt", - "tags": [ - "Requests", - ], - }, - }, "/api/v1/requests/{id}/runs/{runId}/tool-calls": { "get": { "parameters": [ @@ -8120,32 +8083,6 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` ], }, }, - "/api/v1/requests/{id}/taxonomy": { - "get": { - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "string", - }, - }, - ], - "responses": { - "200": { - "description": "Taxonomy v1 JSON document (scorecard, behavior analysis, action list)", - }, - "404": { - "description": "Not found — taxonomy not yet generated", - }, - }, - "summary": "Download taxonomy JSON for the run", - "tags": [ - "Requests", - ], - }, - }, "/api/v1/requests/{id}/tool-calls": { "get": { "parameters": [ diff --git a/apps/api/src/archive-har.test.ts b/apps/api/src/archive-har.test.ts index 51d5e36f2..f83d846ac 100644 --- a/apps/api/src/archive-har.test.ts +++ b/apps/api/src/archive-har.test.ts @@ -99,17 +99,6 @@ describe("rewriteHarUrlsForArchive", () => { expect(result.run!.turns![1].toolCallsUrl).toBe("iteration-2.tool-calls.jsonl"); expect(result.run!.turns![2].toolCallsUrl).toBeUndefined(); }); - - it("rewrites run.taxonomyUrl to taxonomy.json", () => { - const resource = { - run: { - taxonomyUrl: "https://storage.blob.core.windows.net/snapshots/abc123/runs/attempt-1/taxonomy.json", - turns: [], - }, - }; - const result = rewriteHarUrlsForArchive(resource); - expect(result.run!.taxonomyUrl).toBe("taxonomy.json"); - }); }); // --- blobNameFromSnapshotsUrl --- @@ -855,34 +844,4 @@ describe("packRunIntoTar", () => { expect(yaml).toContain("iteration-1.chat-result.json"); expect(yaml).not.toContain("blob.core.windows.net"); }); - - it("bundles run-level taxonomy.json and rewrites taxonomyUrl", async () => { - const { pack } = await import("tar-stream"); - const p = pack(); - const taxonomyData = Buffer.from('{"topics":["agent"]}'); - const container = makeMockBlobContainer({ - "run-010/runs/attempt-1/taxonomy.json": { body: taxonomyData, length: taxonomyData.length }, - }); - - const run: ArchivableRun = { - _id: "run-010", - run: { - taxonomyUrl: "https://storage.blob.core.windows.net/snapshots/run-010/runs/attempt-1/taxonomy.json", - turns: [], - }, - }; - - const entriesPromise = collectPackEntries(p); - await packRunIntoTar(p, run, container, "run-010", () => true); - p.finalize(); - - const entries = await entriesPromise; - const names = entries.map(e => e.name); - expect(names).toContain("run-010/taxonomy.json"); - expect(entries.find(e => e.name === "run-010/taxonomy.json")!.data).toEqual(taxonomyData); - - const yaml = entries.find(e => e.name === "run-010/run.yaml")!.data.toString(); - expect(yaml).toContain("taxonomy.json"); - expect(yaml).not.toContain("blob.core.windows.net"); - }); }); diff --git a/apps/api/src/archive-har.ts b/apps/api/src/archive-har.ts index 86cfeb1ee..21f922179 100644 --- a/apps/api/src/archive-har.ts +++ b/apps/api/src/archive-har.ts @@ -41,12 +41,11 @@ export function blobNameFromLogsUrl(url: string): string | null { /** * Deep-clone a run resource and rewrite `harUrl`, `rawChatUrl`, - * `taxonomyUrl`, `chatResultUrl`, and `toolCallsUrl` fields to relative archive paths. + * `chatResultUrl`, and `toolCallsUrl` fields to relative archive paths. * * - `run.harUrl` → `"run.har"` * - Per-turn `harUrl` → `"iteration-{N}.har"` * - `run.rawChatUrl` → `"run.chat-export.json"` - * - `run.taxonomyUrl` → `"taxonomy.json"` * - Per-turn `rawChatUrl` → `"iteration-{N}.chat-export.json"` * - Per-turn `chatResultUrl` → `"iteration-{N}.chat-result.json"` * - Per-turn `toolCallsUrl` → `"iteration-{N}.tool-calls.jsonl"` @@ -55,7 +54,6 @@ export function rewriteHarUrlsForArchive; [key: string]: unknown; }; @@ -68,9 +66,6 @@ export function rewriteHarUrlsForArchive ({ - checkMigrations: vi.fn().mockResolvedValue({ ready: true, applied: ["001", "002"], pending: [] }), -})); - -vi.hoisted(() => { - process.env.STORAGE_CONNECTION_STRING = "DefaultEndpointsProtocol=https;AccountName=mockaccount;AccountKey=bW9jaw==;EndpointSuffix=core.windows.net"; -}); - -vi.mock("../../llm.js", () => ({ isLlmAvailable: vi.fn().mockReturnValue(false) })); -vi.mock("../../prompt-feature-llm.js", () => ({ isLlmAvailable: vi.fn().mockReturnValue(false) })); -vi.mock("../../task-prompt-llm.js", () => ({ isTaskPromptLlmAvailable: vi.fn().mockReturnValue(false) })); - -const { mockDownload, mockGetProperties, mockGetBlockBlobClient, mockGetBlobClient, mockGetContainerClient } = vi.hoisted(() => { - const mockDownload = vi.fn(); - const mockGetProperties = vi.fn(); - const mockGetBlockBlobClient = vi.fn().mockReturnValue({ download: mockDownload, getProperties: mockGetProperties }); - const mockGetBlobClient = vi.fn().mockReturnValue({ download: mockDownload, getProperties: mockGetProperties }); - const mockGetContainerClient = vi.fn().mockReturnValue({ getBlockBlobClient: mockGetBlockBlobClient, getBlobClient: mockGetBlobClient }); - return { mockDownload, mockGetProperties, mockGetBlockBlobClient, mockGetBlobClient, mockGetContainerClient }; -}); - -vi.mock("@azure/storage-blob", async (importOriginal) => { - const original = await importOriginal(); - return { - ...original, - BlobServiceClient: { fromConnectionString: vi.fn().mockReturnValue({ getContainerClient: mockGetContainerClient }) }, - }; -}); - -describe("taxonomy endpoints", () => { - let mocks: ReturnType; - - beforeAll(() => { - mocks = createAllMockDependencies(); - _injectTestDependencies(mocks); - }); - - beforeEach(() => { - vi.clearAllMocks(); - mocks = createAllMockDependencies(); - _injectTestDependencies(mocks); - rewireBlobMocks({ mockDownload, mockGetProperties, mockGetBlockBlobClient, mockGetBlobClient, mockGetContainerClient }); - mockDownload.mockResolvedValue({ readableStreamBody: readableFrom('{"status":"ok"}'), contentLength: 15 }); - mockGetProperties.mockResolvedValue({ contentLength: 15 }); - }); - - describe.each(VARIANTS)("$label", (variant) => { - const taxonomyUrl = (id: string) => variant.url(id) + "taxonomy"; - - it("returns 404 when request not found", async () => { - (mocks.collection.findOne as ReturnType).mockResolvedValue(null); - const res = await supertest(app).get(taxonomyUrl("missing")); - expect(res.status).toBe(404); - expect(res.body).toMatchObject({ error: "Request not found" }); - }); - - it("returns 404 when taxonomyUrl is not set", async () => { - variant.mockRequest(mocks, "req-1", { _id: "run-1", attemptNumber: 1, status: "done" }); - const res = await supertest(app).get(taxonomyUrl("req-1")); - expect(res.status).toBe(404); - expect(res.body).toMatchObject({ error: "Taxonomy not yet generated for this run" }); - }); - - it("returns taxonomy JSON when taxonomyUrl is set", async () => { - variant.mockRequest(mocks, "req-1", { - _id: "run-1", - attemptNumber: 1, - status: "done", - taxonomyUrl: blobUrl("req-1/taxonomy.json"), - }); - - const res = await supertest(app).get(taxonomyUrl("req-1")).buffer(true).parse(rawParser); - expect(res.status).toBe(200); - expect(res.headers["content-type"]).toMatch("application/json"); - expect(res.headers["content-disposition"]).toContain("req-1-taxonomy.json"); - expect(mockGetBlockBlobClient).toHaveBeenCalledWith("req-1/taxonomy.json"); - }); - }); - - it("works with per-run variant", async () => { - RUN_LEVEL.mockRequest(mocks, "req-1", { - _id: "run-1", - attemptNumber: 1, - status: "done", - taxonomyUrl: blobUrl("req-1/runs/run-1/taxonomy.json"), - }); - - const res = await supertest(app).get(RUN_LEVEL.url("req-1") + "taxonomy").buffer(true).parse(rawParser); - expect(res.status).toBe(200); - expect(res.headers["content-disposition"]).toContain("req-1-taxonomy.json"); - expect(mockGetBlockBlobClient).toHaveBeenCalledWith("req-1/runs/run-1/taxonomy.json"); - }); -}); diff --git a/apps/api/src/routes/requests/taxonomy.ts b/apps/api/src/routes/requests/taxonomy.ts deleted file mode 100644 index e74d303f6..000000000 --- a/apps/api/src/routes/requests/taxonomy.ts +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { RouteContext } from "../../route-context.js"; -import { downloadBlobToResponse } from "./blob-helpers.js"; -import { registerArtifactRoutes } from "./artifact-route.js"; - -export function registerRequestsTaxonomyRoutes(ctx: RouteContext): void { - registerArtifactRoutes(ctx, { - path: "taxonomy", - summary: "Download taxonomy JSON for the run", - perRunSummary: "Download taxonomy JSON for a specific attempt", - responseDescription: "Taxonomy v1 JSON document (scorecard, behavior analysis, action list)", - errorResponses: { 404: { description: "Not found — taxonomy not yet generated" } }, - blobNotFoundMessage: "Taxonomy file not found — the blob may have been deleted or is no longer available", - handler: async (ctx, _req, res, targetRun, id) => { - const taxonomyUrl = targetRun.taxonomyUrl; - if (!taxonomyUrl) { - res.status(404).json({ error: "Taxonomy not yet generated for this run" }); - return; - } - - await downloadBlobToResponse(ctx, res, taxonomyUrl, { - contentType: "application/json", - filename: `${id}-taxonomy.json`, - label: "Taxonomy", - }); - }, - }); -} diff --git a/apps/portal/src/components/TaxonomyTab.tsx b/apps/portal/src/components/TaxonomyTab.tsx deleted file mode 100644 index e97c8c8c4..000000000 --- a/apps/portal/src/components/TaxonomyTab.tsx +++ /dev/null @@ -1,248 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { useQuery } from "@tanstack/react-query"; -import { api } from "@/lib/api"; -import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; -import { Badge } from "@/components/ui/badge"; -import { Button } from "@/components/ui/button"; -import { Loader2, Download, ChevronDown, ChevronRight } from "lucide-react"; -import { useState } from "react"; - -interface TaxonomyDimension { - name: string; - score: number; - maxScore: number; - justification: string; -} - -interface BehaviorPattern { - id: string; - category: string; - observation: string; - evidence: string[]; - impact: "positive" | "negative" | "neutral"; -} - -interface ActionItem { - id: string; - priority: "high" | "medium" | "low"; - title: string; - description: string; - category: string; -} - -interface TaxonomyData { - meta?: { - schemaVersion?: string; - generatedAt?: string; - requestId?: string; - runId?: string; - model?: string; - }; - scorecard?: { - overall?: number; - dimensions?: TaxonomyDimension[]; - }; - behaviorAnalysis?: { - patterns?: BehaviorPattern[]; - }; - actionList?: { - items?: ActionItem[]; - }; -} - -function ScoreBar({ score, maxScore }: { score: number; maxScore: number }) { - const pct = Math.round((score / maxScore) * 100); - const color = pct >= 80 ? "bg-green-500" : pct >= 50 ? "bg-yellow-500" : "bg-red-500"; - return ( -
-
-
-
- {score}/{maxScore} -
- ); -} - -function ImpactBadge({ impact }: { impact: string }) { - const variant = impact === "positive" ? "default" : impact === "negative" ? "destructive" : "secondary"; - return {impact}; -} - -function PriorityBadge({ priority }: { priority: string }) { - const colors: Record = { - high: "bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300", - medium: "bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300", - low: "bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300", - }; - return {priority}; -} - -function CollapsibleSection({ title, defaultOpen = true, children }: { title: string; defaultOpen?: boolean; children: React.ReactNode }) { - const [open, setOpen] = useState(defaultOpen); - return ( -
- - {open &&
{children}
} -
- ); -} - -export function TaxonomyTab({ runId, attemptRunId }: { runId: string; attemptRunId?: string }) { - const url = attemptRunId ? api.runTaxonomyUrl(runId, attemptRunId) : api.taxonomyUrl(runId); - - const { data: taxonomy, isLoading, error } = useQuery({ - queryKey: ["run-taxonomy", runId, attemptRunId], - queryFn: async () => { - const res = await fetch(url); - if (!res.ok) { - if (res.status === 404) return null; - throw new Error(`Failed to fetch taxonomy: ${res.statusText}`); - } - return res.json(); - }, - }); - - if (isLoading) { - return ( -
- - Loading taxonomy… -
- ); - } - - if (error) { - return ( -
-

Failed to load taxonomy: {(error as Error).message}

-
- ); - } - - if (!taxonomy) { - return ( -
-

Taxonomy not yet generated for this run.

-

It will appear here once post-processing completes.

-
- ); - } - - const { meta, scorecard, behaviorAnalysis, actionList } = taxonomy; - - return ( -
- {/* Header with download */} -
-
-

Run Taxonomy

- {meta?.generatedAt && ( -

- Generated {new Date(meta.generatedAt).toLocaleString()} - {meta.model && <> · Model: {meta.model}} -

- )} -
- -
- - {/* Scorecard */} - {scorecard && ( - - - - Scorecard - {scorecard.overall !== undefined && ( - {scorecard.overall}% - )} - - - - {scorecard.dimensions?.map((dim) => ( -
-
- {dim.name} -
- -

{dim.justification}

-
- ))} -
-
- )} - - {/* Behavior Analysis */} - {behaviorAnalysis?.patterns && behaviorAnalysis.patterns.length > 0 && ( - - - - Behavior Analysis ({behaviorAnalysis.patterns.length}) - - - - -
- {behaviorAnalysis.patterns.map((pattern) => ( -
-
- {pattern.category} - -
-

{pattern.observation}

- {pattern.evidence.length > 0 && ( -
    - {pattern.evidence.map((e, i) =>
  • {e}
  • )} -
- )} -
- ))} -
-
-
-
- )} - - {/* Action List */} - {actionList?.items && actionList.items.length > 0 && ( - - - - Action Items ({actionList.items.length}) - - - - -
- {actionList.items.map((item) => ( -
- -
-

{item.title}

-

{item.description}

- {item.category} -
-
- ))} -
-
-
-
- )} - - {/* Raw JSON fallback — collapsed by default */} - -
-          {JSON.stringify(taxonomy, null, 2)}
-        
-
-
- ); -} diff --git a/apps/portal/src/lib/api.ts b/apps/portal/src/lib/api.ts index 144b41c73..ea16aeabb 100644 --- a/apps/portal/src/lib/api.ts +++ b/apps/portal/src/lib/api.ts @@ -217,16 +217,6 @@ export const api = { return `${BASE}/requests/${id}/atif${qs}`; }, - /** Get taxonomy JSON URL for a request (latest run) */ - taxonomyUrl: (id: string): string => { - return `${BASE}/requests/${id}/taxonomy`; - }, - - /** Get taxonomy JSON URL for a specific attempt */ - runTaxonomyUrl: (requestId: string, runId: string): string => { - return `${BASE}/requests/${requestId}/runs/${runId}/taxonomy`; - }, - /** Download a batch archive of multiple runs as a single .tar.gz */ batchArchive: async (ids: string[]): Promise => { const resp = await fetch(`${BASE}/requests/archive`, { diff --git a/apps/portal/src/pages/RunDetail.tsx b/apps/portal/src/pages/RunDetail.tsx index 789e74743..ee42b2467 100644 --- a/apps/portal/src/pages/RunDetail.tsx +++ b/apps/portal/src/pages/RunDetail.tsx @@ -24,7 +24,6 @@ import { CriteriaGraphView } from "@/components/CriteriaGraphView"; import { HarNetworkViewer } from "@/components/HarNetworkViewer"; import { ConversationView } from "@/components/ConversationView"; import { VideoPlayer } from "@/components/VideoPlayer"; -import { TaxonomyTab } from "@/components/TaxonomyTab"; import { useLogStream } from "@/hooks/use-log-stream"; import { useAllTurnsToolCalls } from "@/hooks/useHarExtraction"; import { MarkdownRenderer } from "@/components/MarkdownRenderer"; @@ -326,7 +325,6 @@ export function RunDetail() { } const hasHarData = !!(activeRun?.harUrl || activeRun?.turns?.some(t => t.harUrl)); - const hasTaxonomy = !!activeRun?.taxonomyUrl; const hasVideoData = !!(activeRun?.videoUrls?.length || activeRun?.setupVideoUrls?.length || activeRun?.turns?.some(t => t.videoUrls?.length)); const videoCount = (activeRun?.setupVideoUrls?.length ?? 0) + (activeRun?.videoUrls?.length ?? 0) @@ -654,7 +652,6 @@ export function RunDetail() { )} {hasHarData && Network} {hasHarData && Tool Calls} - {hasTaxonomy && Taxonomy} {hasVideoData && } Logs @@ -687,13 +684,6 @@ export function RunDetail() { )} - {/* Taxonomy tab — structured scorecard + behavior analysis + action items */} - {hasTaxonomy && ( - - - - )} - {/* Video tab — session recording player */} {hasVideoData && ( diff --git a/apps/portal/src/types.ts b/apps/portal/src/types.ts index 019f77a9f..7b7e4c0f2 100644 --- a/apps/portal/src/types.ts +++ b/apps/portal/src/types.ts @@ -112,7 +112,6 @@ export interface RunState { resumedAt?: string; postProcessorVersion?: number; postProcessorStatus?: "queued" | "processing" | "done" | "failed"; - taxonomyUrl?: string; } export interface Run { diff --git a/apps/scheduler/src/handler-dispatcher.test.ts b/apps/scheduler/src/handler-dispatcher.test.ts index 080b2b4a7..67264d02c 100644 --- a/apps/scheduler/src/handler-dispatcher.test.ts +++ b/apps/scheduler/src/handler-dispatcher.test.ts @@ -16,11 +16,11 @@ const HANDLERS: HandlerServiceDocument[] = [ dependsOn: [], }, { - _id: "pp-taxonomy", + _id: "pp-example", type: "post-process-handler", version: 1, - queue: "pp-taxonomy-queue", - selector: "taxonomy", + queue: "pp-example-queue", + selector: "example", autoBackfill: false, dependsOn: ["pp-atif"], }, @@ -72,7 +72,7 @@ describe("HandlerDispatcher — drain detection", () => { it("is drained when all handlers are done", () => { expect( - isDrained(HANDLERS, { "pp-atif": { status: "done" }, "pp-taxonomy": { status: "done" } }), + isDrained(HANDLERS, { "pp-atif": { status: "done" }, "pp-example": { status: "done" } }), ).toBe(true); }); @@ -84,13 +84,13 @@ describe("HandlerDispatcher — drain detection", () => { expect( isDrained(HANDLERS, { "pp-atif": { status: "done" }, - "pp-taxonomy": { status: "processing" }, + "pp-example": { status: "processing" }, }), ).toBe(false); }); it("is drained when a failed dependency blocks its descendant", () => { - // pp-atif failed → pp-taxonomy can never run (blocked) → terminal. + // pp-atif failed → pp-example can never run (blocked) → terminal. expect(isDrained(HANDLERS, { "pp-atif": { status: "failed" } })).toBe(true); }); @@ -98,7 +98,7 @@ describe("HandlerDispatcher — drain detection", () => { expect( isDrained(HANDLERS, { "pp-atif": { status: "done" }, - "pp-taxonomy": { status: "failed" }, + "pp-example": { status: "failed" }, }), ).toBe(true); }); @@ -128,7 +128,7 @@ describe("HandlerDispatcher — maybeTriggerReports", () => { run: { _id: "run-1", status: "done", - handlerStatus: { "pp-atif": { status: "done" }, "pp-taxonomy": { status: "done" } }, + handlerStatus: { "pp-atif": { status: "done" }, "pp-example": { status: "done" } }, }, }); collection.findOneAndUpdate.mockResolvedValue({ _id: "req-1" }); // claim succeeds @@ -188,7 +188,7 @@ describe("HandlerDispatcher — maybeTriggerReports", () => { run: { _id: "run-2", status: "done", - handlerStatus: { "pp-atif": { status: "done" }, "pp-taxonomy": { status: "done" } }, + handlerStatus: { "pp-atif": { status: "done" }, "pp-example": { status: "done" } }, }, }); @@ -205,7 +205,7 @@ describe("HandlerDispatcher — maybeTriggerReports", () => { run: { _id: "run-1", status: "done", - handlerStatus: { "pp-atif": { status: "done" }, "pp-taxonomy": { status: "done" } }, + handlerStatus: { "pp-atif": { status: "done" }, "pp-example": { status: "done" } }, }, }); collection.findOneAndUpdate.mockResolvedValue(null); // another path claimed it first @@ -222,7 +222,7 @@ describe("HandlerDispatcher — maybeTriggerReports", () => { run: { _id: "run-1", status: "done", - handlerStatus: { "pp-atif": { status: "done" }, "pp-taxonomy": { status: "done" } }, + handlerStatus: { "pp-atif": { status: "done" }, "pp-example": { status: "done" } }, }, }); collection.findOneAndUpdate.mockResolvedValue({ _id: "req-1" }); diff --git a/apps/scheduler/src/notify-routes.test.ts b/apps/scheduler/src/notify-routes.test.ts index 00968ba29..797256018 100644 --- a/apps/scheduler/src/notify-routes.test.ts +++ b/apps/scheduler/src/notify-routes.test.ts @@ -162,11 +162,11 @@ describe("createHttpServer", () => { servers.push(server); const doc = { - _id: "pp-taxonomy", + _id: "pp-example", type: "post-process-handler", version: 1, - queue: "pp-taxonomy-queue", - selector: "taxonomy", + queue: "pp-example-queue", + selector: "example", autoBackfill: false, dependsOn: ["pp-atif"], }; @@ -178,7 +178,7 @@ describe("createHttpServer", () => { }); expect(response.status).toBe(200); - expect(await response.json()).toEqual({ ok: true, handlerId: "pp-taxonomy" }); + expect(await response.json()).toEqual({ ok: true, handlerId: "pp-example" }); expect(handler.registerHandler).toHaveBeenCalledWith(doc); }); diff --git a/apps/workers/taxonomy/Dockerfile b/apps/workers/taxonomy/Dockerfile deleted file mode 100644 index b6be8f2ad..000000000 --- a/apps/workers/taxonomy/Dockerfile +++ /dev/null @@ -1,50 +0,0 @@ -FROM node:22.22.0-slim AS builder - -RUN corepack enable && corepack prepare pnpm@10.29.1 --activate - -WORKDIR /app - -COPY package.json pnpm-workspace.yaml pnpm-lock.yaml ./ -COPY tsconfig.base.json ./ -COPY packages/shared/package.json ./packages/shared/ -COPY apps/workers/taxonomy/package.json ./apps/workers/taxonomy/ - -RUN pnpm install --frozen-lockfile - -COPY packages/shared/tsconfig.json ./packages/shared/ -COPY packages/shared/src ./packages/shared/src/ -COPY apps/workers/taxonomy/tsconfig.json ./apps/workers/taxonomy/ -COPY apps/workers/taxonomy/src ./apps/workers/taxonomy/src/ -COPY apps/workers/taxonomy/handler.yaml ./apps/workers/taxonomy/ - -RUN pnpm --filter shared build && pnpm --filter taxonomy-handler build - -# --- Dev stage: hot reload with tsx watch --- -FROM builder AS dev -ENV NODE_ENV=development -ENV SERVICE_DIR=workers/taxonomy -COPY scripts/dev-entrypoint.sh /app/scripts/dev-entrypoint.sh -EXPOSE 80 -ENV PORT=80 -CMD ["/app/scripts/dev-entrypoint.sh"] - -# --- Production stage --- -FROM node:22.22.0-slim - -RUN corepack enable && corepack prepare pnpm@10.29.1 --activate - -WORKDIR /app - -COPY package.json pnpm-workspace.yaml pnpm-lock.yaml ./ -COPY packages/shared/package.json ./packages/shared/ -COPY apps/workers/taxonomy/package.json ./apps/workers/taxonomy/ - -RUN pnpm install --frozen-lockfile --prod - -COPY --from=builder /app/packages/shared/dist ./packages/shared/dist/ -COPY --from=builder /app/apps/workers/taxonomy/dist ./apps/workers/taxonomy/dist/ -COPY --from=builder /app/apps/workers/taxonomy/handler.yaml ./apps/workers/taxonomy/handler.yaml - -WORKDIR /app/apps/workers/taxonomy - -CMD ["node", "dist/index.js"] diff --git a/apps/workers/taxonomy/handler.yaml b/apps/workers/taxonomy/handler.yaml deleted file mode 100644 index b479f905e..000000000 --- a/apps/workers/taxonomy/handler.yaml +++ /dev/null @@ -1,11 +0,0 @@ -# Post-process handler registration metadata. -# Read by the generic register-handler script and POSTed to the -# scheduler's POST /handlers/register endpoint on deploy. -_id: pp-taxonomy -type: post-process-handler -version: 1 -queue: pp-taxonomy-queue -selector: taxonomy -autoBackfill: false -dependsOn: - - pp-atif diff --git a/apps/workers/taxonomy/package.json b/apps/workers/taxonomy/package.json deleted file mode 100644 index 52cdd6b2f..000000000 --- a/apps/workers/taxonomy/package.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "name": "taxonomy-handler", - "version": "1.0.0", - "type": "module", - "main": "dist/index.js", - "scripts": { - "build": "tsc", - "dev": "tsx watch src/index.ts", - "start": "node dist/index.js", - "taxonomy": "tsx src/cli.ts", - "lint": "eslint src/" - }, - "dependencies": { - "shared": "workspace:*", - "@azure/storage-queue": "^12.25.0", - "@github/copilot-sdk": "^0.1.17", - "dotenv": "^16.4.5" - }, - "devDependencies": { - "@types/node": "^22.7.0", - "tsx": "^4.19.0", - "typescript": "^5.6.2" - } -} diff --git a/apps/workers/taxonomy/src/cli.ts b/apps/workers/taxonomy/src/cli.ts deleted file mode 100644 index a5f51f600..000000000 --- a/apps/workers/taxonomy/src/cli.ts +++ /dev/null @@ -1,206 +0,0 @@ -#!/usr/bin/env npx tsx -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * Taxonomy post-processor developer CLI. - * - * Invokes the taxonomy generation loop directly against an existing requestId, - * streams the Copilot SDK session events live, and saves the validated taxonomy - * to a local JSON file. This is a developer/troubleshooting tool only — it never - * writes to Mongo (handlerStatus) or blob storage (taxonomy.json) and does not - * notify the scheduler. - * - * Usage: - * npx tsx src/cli.ts [options] - * pnpm taxonomy [options] - * - * Options: - * --run, -r Run id for the prompt/logging (default: active run from API). - * --model Override TAXONOMY_MODEL (e.g. a reasoning model). - * --timeout Override SESSION_TIMEOUT_MS (per-attempt session timeout). - * --output, -o Output file path (default: taxonomy-.json). - * --stdout Also print the taxonomy JSON to stdout. - * --quiet Suppress live session-event streaming on stderr. - * --help, -h Show this help. - */ -import "dotenv/config"; -import { writeFile } from "node:fs/promises"; -import { resolve } from "node:path"; -import { SessionEvent } from "@github/copilot-sdk"; -import { TokenManagerClient, type LogEvent, type RequestDocument } from "shared"; -import { generateTaxonomy } from "./taxonomy-generator.js"; - -interface CliArgs { - requestId: string; - runId?: string; - model?: string; - timeoutMs?: number; - output?: string; - stdout: boolean; - quiet: boolean; -} - -function printHelp(): void { - process.stderr.write( - [ - "Taxonomy post-processor developer CLI", - "", - "Usage: npx tsx src/cli.ts [options]", - "", - "Options:", - " --run, -r Run id for the prompt/logging (default: active run from API)", - " --model Override TAXONOMY_MODEL", - " --timeout Override SESSION_TIMEOUT_MS (per-attempt session timeout)", - " --output, -o Output file path (default: taxonomy-.json)", - " --stdout Also print the taxonomy JSON to stdout", - " --quiet Suppress live session-event streaming on stderr", - " --help, -h Show this help", - "", - ].join("\n"), - ); -} - -function parseArgs(argv: string[]): CliArgs | undefined { - const args: Partial & { stdout: boolean; quiet: boolean } = { stdout: false, quiet: false }; - const positionals: string[] = []; - - for (let i = 0; i < argv.length; i += 1) { - const arg = argv[i]; - switch (arg) { - case "--help": - case "-h": - printHelp(); - return undefined; - case "--run": - case "-r": - args.runId = argv[++i]; - break; - case "--model": - args.model = argv[++i]; - break; - case "--timeout": - args.timeoutMs = Number(argv[++i]); - break; - case "--output": - case "-o": - args.output = argv[++i]; - break; - case "--stdout": - args.stdout = true; - break; - case "--quiet": - args.quiet = true; - break; - default: - if (arg.startsWith("-")) { - throw new Error(`Unknown option: ${arg}`); - } - positionals.push(arg); - } - } - - const requestId = positionals[0]; - if (!requestId) { - throw new Error("Missing required argument"); - } - if (args.timeoutMs !== undefined && Number.isNaN(args.timeoutMs)) { - throw new Error("--timeout must be a number (milliseconds)"); - } - - return { ...args, requestId }; -} - -async function resolveRunId(apiBaseUrl: string, requestId: string, explicit?: string): Promise { - if (explicit) return explicit; - try { - const response = await fetch(`${apiBaseUrl}/api/v1/requests/${requestId}`); - if (response.ok) { - const request: RequestDocument = await response.json(); - if (request.run?._id) return request.run._id; - } - } catch { - // fall through to requestId fallback - } - return requestId; -} - -function summarizeEvent(event: SessionEvent): string | undefined { - switch (event.type) { - case "session.start": - return `session.start model=${event.data.selectedModel}`; - case "session.error": - return `session.error ${event.data.errorType}: ${event.data.message}`; - case "tool.execution_start": - return `tool.start ${event.data.toolName} ${JSON.stringify(event.data.arguments ?? {})}`; - case "tool.execution_complete": - return `tool.done ${event.data.success ? "ok" : "FAILED"}${event.data.error ? ` ${event.data.error.message}` : ""}`; - case "assistant.message": - return `assistant.message (${event.data.content.length} chars)`; - default: - return undefined; - } -} - -async function main(): Promise { - let parsed: CliArgs | undefined; - try { - parsed = parseArgs(process.argv.slice(2)); - } catch (error) { - process.stderr.write(`Error: ${error instanceof Error ? error.message : String(error)}\n\n`); - printHelp(); - process.exit(2); - } - if (!parsed) return; // help shown - - const apiBaseUrl = process.env.SCOPE_MT_API_URL || "http://localhost:3001"; - const taxonomyModel = parsed.model || process.env.TAXONOMY_MODEL || "gpt-5.4"; - const sessionTimeoutMs = parsed.timeoutMs ?? (Number(process.env.SESSION_TIMEOUT_MS) || 5 * 60 * 1000); - const outputPath = resolve(parsed.output ?? `taxonomy-${parsed.requestId}.json`); - - const githubToken = process.env.GITHUB_TOKEN - ? process.env.GITHUB_TOKEN - : await new TokenManagerClient(process.env.TOKEN_MANAGER_URL).acquireToken("copilot-sdk"); - - const runId = await resolveRunId(apiBaseUrl, parsed.requestId, parsed.runId); - - const log = (level: LogEvent["level"], msg: string, data?: Record): void => { - if (parsed.quiet) return; - const suffix = data && Object.keys(data).length > 0 ? ` ${JSON.stringify(data)}` : ""; - process.stderr.write(`[${level}] ${msg}${suffix}\n`); - }; - - process.stderr.write( - `Generating taxonomy: requestId=${parsed.requestId} runId=${runId} model=${taxonomyModel} timeout=${sessionTimeoutMs}ms\n`, - ); - - const onEvent = parsed.quiet - ? undefined - : (event: SessionEvent): void => { - const summary = summarizeEvent(event); - if (summary) process.stderr.write(` · ${summary}\n`); - }; - - const taxonomy = await generateTaxonomy({ - requestId: parsed.requestId, - runId, - apiBaseUrl, - taxonomyModel, - githubToken, - sessionTimeoutMs, - log, - onEvent, - }); - - const json = JSON.stringify(taxonomy, null, 2); - await writeFile(outputPath, `${json}\n`, "utf-8"); - process.stderr.write(`\nTaxonomy written to ${outputPath}\n`); - if (parsed.stdout) { - process.stdout.write(`${json}\n`); - } -} - -main().catch((error) => { - process.stderr.write(`\nTaxonomy generation failed: ${error instanceof Error ? error.message : String(error)}\n`); - process.exit(1); -}); diff --git a/apps/workers/taxonomy/src/index.ts b/apps/workers/taxonomy/src/index.ts deleted file mode 100644 index b1a4f322b..000000000 --- a/apps/workers/taxonomy/src/index.ts +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import "dotenv/config"; -import { TaxonomyQueueProcessor, type TaxonomyQueueProcessorConfig } from "./taxonomy-queue-processor.js"; - -const config: TaxonomyQueueProcessorConfig = { - mongoUri: process.env.MONGO_CONNECTION_STRING || process.env.AZURE_COSMOS_CONNECTION_STRING || "mongodb://localhost:27017", - mongoDatabase: process.env.MONGO_DATABASE || "requests-db", - mongoCollection: "requests", - storageAccountName: process.env.AZURE_STORAGE_ACCOUNT_NAME || "devstoreaccount1", - storageConnectionString: process.env.STORAGE_CONNECTION_STRING || process.env.AZURE_STORAGE_CONNECTION_STRING || undefined, - queueName: process.env.AZURE_STORAGE_QUEUE_TAXONOMY || "pp-taxonomy-queue", - batchSize: Number(process.env.BATCH_SIZE) || 1, - pollIntervalMs: Number(process.env.POLL_INTERVAL_MS) || 5000, - redisHost: process.env.REDIS_HOST || "localhost", - redisPort: Number(process.env.REDIS_PORT) || 6379, - redisPassword: process.env.REDIS_PASSWORD || "", - taxonomyModel: process.env.TAXONOMY_MODEL || "gpt-5.4", - apiBaseUrl: process.env.SCOPE_MT_API_URL || "http://localhost:3001", - sessionTimeoutMs: Number(process.env.SESSION_TIMEOUT_MS) || 5 * 60 * 1000, - schedulerUrl: process.env.SCHEDULER_URL, - tokenManagerUrl: process.env.TOKEN_MANAGER_URL, -}; - -const processor = new TaxonomyQueueProcessor(config); -processor.start().catch((err) => { - console.error("[taxonomy-handler] Fatal error:", err); - process.exit(1); -}); diff --git a/apps/workers/taxonomy/src/prompt.ts b/apps/workers/taxonomy/src/prompt.ts deleted file mode 100644 index 47ea28e4d..000000000 --- a/apps/workers/taxonomy/src/prompt.ts +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -export const TAXONOMY_SYSTEM_PROMPT = `You generate benchmark taxonomy documents for completed Scope runs. - -Your job is to inspect the run metadata and ATIF trajectories, then return a taxonomy JSON document that conforms exactly to the taxonomy Zod schema enforced by the worker. - -Required JSON shape: -{ - "meta": { - "generatedAt": "ISO-8601 datetime with offset", - "schemaVersion": "string", - "runId": "string", - "requestId": "string" - }, - "scorecard": { - "summary": "string", - "profileResults": [ - { - "profileId": "string", - "select": "best|median|worst", - "taskOutcome": "success|partial|failure", - "overallScore": 0-100, - "dimensions": [ - { - "name": "string", - "score": 0-100, - "rationale": "string", - "evidence": ["string"] - } - ] - } - ], - "crossProfileInsights": ["string"] - }, - "behaviorAnalysis": { - "patterns": [ - { - "id": "string", - "category": "strength|weakness|inconsistency|regression", - "title": "string", - "description": "string", - "frequency": 0-1, - "impact": "critical|high|medium|low", - "evidence": [ - { - "runId": "string", - "iteration": 0-or-greater integer, - "excerpt": "string" - } - ] - } - ], - "agentPersonality": { - "communicationStyle": "string", - "problemSolvingApproach": "string", - "errorRecoveryBehavior": "string" - } - }, - "actionList": { - "fix": [actionItem], - "improve": [actionItem], - "investigate": [actionItem] - } -} - -Each actionItem must include: -- id -- title -- priority: critical|high|medium|low -- description -- ownership: agent-team|platform-team|prompt-engineer|scenario-author -- relatedPatterns: string[] -- suggestedApproach - -Output rules: -- Return raw JSON only. -- Do not wrap the JSON in markdown fences. -- Do not include commentary before or after the JSON. -- Every field must be valid for the schema. -- Preserve the 3-layer structure: scorecard, behaviorAnalysis, actionList. -- If a value is unknown, use the schema-compatible empty/null/default value rather than inventing facts. - -Use the available tools to gather evidence before answering: -- get_run_data for the request, scenario, run, turns, and criteria outcomes. -- get_atif_trajectory for ATIF evidence from individual iterations. - -Ground every classification in the actual run evidence. Prefer precise, stable labels over verbose prose. If validation feedback is provided later in the conversation, correct the JSON and return a full replacement document.`; diff --git a/apps/workers/taxonomy/src/taxonomy-generator.ts b/apps/workers/taxonomy/src/taxonomy-generator.ts deleted file mode 100644 index 0df69d2c5..000000000 --- a/apps/workers/taxonomy/src/taxonomy-generator.ts +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { CopilotClient, SessionEvent } from "@github/copilot-sdk"; -import { - type LogEvent, - taxonomySchema, - type TaxonomyDocument, -} from "shared"; -import { TAXONOMY_SYSTEM_PROMPT } from "./prompt.js"; -import { createTaxonomyTools } from "./tools.js"; - -export const DEFAULT_SESSION_TIMEOUT_MS = 5 * 60 * 1000; -const DELTA_LOG_INTERVAL = 2_000; - -type TaxonomyLogFn = ( - level: LogEvent["level"], - msg: string, - data?: Record, -) => Promise | void; - -export interface GenerateTaxonomyParams { - requestId: string; - runId: string; - apiBaseUrl: string; - taxonomyModel: string; - githubToken: string; - sessionTimeoutMs?: number; - log: TaxonomyLogFn; - /** Optional raw session-event hook (used by the dev CLI to render live progress). */ - onEvent?: (event: SessionEvent) => void; -} - -/** - * Runs the Copilot SDK taxonomy generation loop and returns a schema-validated - * taxonomy document. This is side-effect-free with respect to Mongo and blob - * storage (it only reads run data and ATIF trajectories through the API); - * persistence is the caller's responsibility. - */ -export async function generateTaxonomy(params: GenerateTaxonomyParams): Promise { - const { requestId, runId, apiBaseUrl, taxonomyModel, githubToken, log, onEvent } = params; - const client = new CopilotClient({ githubToken }); - const tools = createTaxonomyTools(apiBaseUrl, requestId); - const timeoutMs = params.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS; - - let streamedResponse = ""; - let latestMessage = ""; - let lastLoggedCharCount = 0; - const toolNames = new Map(); - - try { - const session = await client.createSession({ - model: taxonomyModel, - streaming: true, - tools, - systemMessage: { mode: "replace", content: TAXONOMY_SYSTEM_PROMPT }, - }); - - session.on((event: SessionEvent) => { - onEvent?.(event); - switch (event.type) { - case "session.start": - void log("info", "Copilot session started", { - sessionId: event.data.sessionId, - model: event.data.selectedModel, - }); - break; - case "session.error": - void log("error", `Session error: ${event.data.message}`, { errorType: event.data.errorType }); - break; - case "tool.execution_start": - toolNames.set(event.data.toolCallId, event.data.toolName); - void log("info", `Tool call: ${event.data.toolName}`, { - toolCallId: event.data.toolCallId, - arguments: event.data.arguments as Record | undefined, - }); - break; - case "tool.execution_complete": { - const toolName = toolNames.get(event.data.toolCallId) ?? "unknown"; - toolNames.delete(event.data.toolCallId); - void log("info", `Tool result: ${toolName} (${event.data.success ? "success" : "failed"})`, { - toolCallId: event.data.toolCallId, - error: event.data.error?.message, - }); - break; - } - case "assistant.message_delta": - streamedResponse += event.data.deltaContent; - if (streamedResponse.length - lastLoggedCharCount >= DELTA_LOG_INTERVAL) { - lastLoggedCharCount = streamedResponse.length; - void log("info", `Generating taxonomy… (${streamedResponse.length} chars so far)`); - } - break; - case "assistant.message": - latestMessage = event.data.content; - break; - } - }); - - let attempts = 0; - const maxAttempts = 3; - let prompt = [ - `Generate taxonomy JSON for request ${requestId} and run ${runId}.`, - "Use get_run_data first, then inspect ATIF trajectories that materially affect the classification.", - "Return only raw JSON that satisfies the taxonomy schema.", - ].join(" "); - let lastJson: string | undefined; - - while (attempts < maxAttempts) { - attempts += 1; - streamedResponse = ""; - latestMessage = ""; - lastLoggedCharCount = 0; - - await log("info", `Sending taxonomy prompt to Copilot SDK (attempt ${attempts}/${maxAttempts})`, { - requestId, - runId, - timeoutMs, - }); - - const response = await session.sendAndWait({ prompt }, timeoutMs); - const responseText = response?.data.content?.trim() || latestMessage.trim() || streamedResponse.trim(); - - if (!responseText) { - throw new Error("Copilot SDK returned an empty taxonomy response"); - } - - const jsonText = extractJson(responseText); - lastJson = jsonText; - - let parsedJson: unknown; - try { - parsedJson = JSON.parse(jsonText) as unknown; - } catch (error) { - const errorMessage = error instanceof Error ? error.message : String(error); - if (attempts >= maxAttempts) { - throw new Error(`Taxonomy response was not valid JSON after ${maxAttempts} attempts: ${errorMessage}`); - } - - prompt = [ - "Your previous response was not valid JSON.", - `JSON parse error: ${errorMessage}.`, - "Return the full taxonomy document again as raw JSON only, with no markdown fences or commentary.", - "Replace the entire response with corrected JSON.", - ].join(" "); - continue; - } - - const validation = taxonomySchema.safeParse(parsedJson); - if (validation.success) { - return validation.data; - } - - const validationErrors = formatValidationErrors(validation.error.issues); - await log("warn", `Taxonomy validation failed on attempt ${attempts}`, { - issues: validationErrors, - }); - - if (attempts >= maxAttempts) { - throw new Error( - `Taxonomy schema validation failed after ${maxAttempts} attempts: ${validationErrors.join(" | ")}`, - ); - } - - prompt = [ - "Your previous taxonomy JSON did not satisfy the schema.", - "Correct the document and return the entire replacement JSON object.", - "Do not include markdown fences or commentary.", - `Validation errors: ${validationErrors.join("; ")}`, - lastJson ? `Previous JSON: ${lastJson}` : "", - ].filter(Boolean).join(" "); - } - - throw new Error("Taxonomy generation ended without a valid document"); - } finally { - await client.stop().catch(() => undefined); - } -} - -function extractJson(responseText: string): string { - const trimmed = responseText.trim(); - if (!trimmed.startsWith("```")) { - return trimmed; - } - - const fenceMatch = trimmed.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i); - return fenceMatch?.[1]?.trim() ?? trimmed; -} - -function formatValidationErrors(issues: Array<{ path: PropertyKey[]; message: string }>): string[] { - return issues.map((issue) => { - const path = issue.path.length > 0 ? issue.path.map((segment) => String(segment)).join(".") : ""; - return `${path}: ${issue.message}`; - }); -} diff --git a/apps/workers/taxonomy/src/taxonomy-queue-processor.ts b/apps/workers/taxonomy/src/taxonomy-queue-processor.ts deleted file mode 100644 index d3c7495d3..000000000 --- a/apps/workers/taxonomy/src/taxonomy-queue-processor.ts +++ /dev/null @@ -1,191 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { DequeuedMessageItem } from "@azure/storage-queue"; -import { - BaseQueueProcessor, - BlobStorage, - type BaseQueueProcessorConfig, - type LogEvent, - type RequestDocument, - TokenManagerClient, - type TaxonomyDocument, - type VisibilityHeartbeat, - withRetry, -} from "shared"; -import { generateTaxonomy } from "./taxonomy-generator.js"; - -const HANDLER_ID = "pp-taxonomy"; -const HANDLER_VERSION = 1; -const DEFAULT_SESSION_TIMEOUT_MS = 5 * 60 * 1000; - -interface TaxonomyQueueMessage { - type: "taxonomy"; - requestId: string; - runId?: string; -} - -export interface TaxonomyQueueProcessorConfig extends BaseQueueProcessorConfig { - taxonomyModel: string; - apiBaseUrl: string; - sessionTimeoutMs?: number; - schedulerUrl?: string; - tokenManagerUrl?: string; -} - -export class TaxonomyQueueProcessor extends BaseQueueProcessor { - private taxonomyConfig: TaxonomyQueueProcessorConfig; - private tokenClient: TokenManagerClient; - private blobStorage: BlobStorage; - - constructor(config: TaxonomyQueueProcessorConfig) { - super(config, "taxonomy-handler"); - this.taxonomyConfig = config; - this.tokenClient = new TokenManagerClient(config.tokenManagerUrl); - this.blobStorage = new BlobStorage({ - storageAccountName: config.storageAccountName, - storageConnectionString: config.storageConnectionString, - }); - } - - protected override async handleRequest( - doc: RequestDocument, - message: DequeuedMessageItem, - heartbeat: VisibilityHeartbeat, - log: (level: LogEvent["level"], msg: string, data?: Record) => Promise, - payload?: Record, - ): Promise { - const queueMessage = payload as TaxonomyQueueMessage | undefined; - const requestId = doc._id; - const activeRunId = doc.run?._id; - const runId = queueMessage?.runId ?? activeRunId ?? requestId; - - if (!queueMessage || queueMessage.type !== "taxonomy") { - await log("warn", "Discarding message with unsupported taxonomy payload", { payload }); - await this.safeDeleteMessage(message.messageId, heartbeat.stop()); - return; - } - - if (queueMessage.runId && activeRunId && queueMessage.runId !== activeRunId) { - await log("warn", "Discarding stale taxonomy message for superseded run", { - requestId, - queuedRunId: queueMessage.runId, - activeRunId, - }); - await this.safeDeleteMessage(message.messageId, heartbeat.stop()); - return; - } - - if (!doc.run) { - throw new Error(`Request ${requestId} has no active run to classify`); - } - - await withRetry(() => this.collection.updateOne( - { _id: requestId } as never, - { - $set: { - [`run.handlerStatus.${HANDLER_ID}.status`]: "processing", - [`run.handlerStatus.${HANDLER_ID}.version`]: HANDLER_VERSION, - [`run.handlerStatus.${HANDLER_ID}.updatedAt`]: new Date(), - [`run.handlerStatus.${HANDLER_ID}.error`]: null, - }, - } as never, - )); - - await log("info", "Starting taxonomy generation", { requestId, runId, model: this.taxonomyConfig.taxonomyModel }); - - try { - const taxonomy = await this.generateTaxonomy(requestId, runId, log); - const blobName = `${requestId}/runs/${runId}/taxonomy.json`; - const taxonomyUrl = await this.blobStorage.uploadJson(blobName, taxonomy); - - await withRetry(() => this.collection.updateOne( - { _id: requestId } as never, - { - $set: { - [`run.taxonomyUrl`]: taxonomyUrl, - [`run.handlerStatus.${HANDLER_ID}.status`]: "done", - [`run.handlerStatus.${HANDLER_ID}.version`]: HANDLER_VERSION, - [`run.handlerStatus.${HANDLER_ID}.updatedAt`]: new Date(), - }, - $unset: { - [`run.handlerStatus.${HANDLER_ID}.error`]: "", - }, - } as never, - )); - - await log("info", "Taxonomy generation completed", { - requestId, - runId, - blobName, - taxonomyUrl, - }); - - await this.notifyHandlerComplete(requestId, runId, "done"); - } catch (error) { - const errorMessage = error instanceof Error ? error.message : String(error); - - await withRetry(() => this.collection.updateOne( - { _id: requestId } as never, - { - $set: { - [`run.handlerStatus.${HANDLER_ID}.status`]: "failed", - [`run.handlerStatus.${HANDLER_ID}.version`]: HANDLER_VERSION, - [`run.handlerStatus.${HANDLER_ID}.updatedAt`]: new Date(), - [`run.handlerStatus.${HANDLER_ID}.error`]: errorMessage, - }, - } as never, - )); - - await log("error", `Taxonomy generation failed: ${errorMessage}`, { requestId, runId }); - await this.notifyHandlerComplete(requestId, runId, "failed"); - throw error; - } - - const finalPopReceipt = heartbeat.stop(); - await this.safeDeleteMessage(message.messageId, finalPopReceipt); - } - - private async generateTaxonomy( - requestId: string, - runId: string, - log: (level: LogEvent["level"], msg: string, data?: Record) => Promise, - ): Promise { - const githubToken = await this.tokenClient.acquireToken("copilot-sdk"); - await log("info", "Acquired Copilot SDK token"); - - return generateTaxonomy({ - requestId, - runId, - apiBaseUrl: this.taxonomyConfig.apiBaseUrl, - taxonomyModel: this.taxonomyConfig.taxonomyModel, - githubToken, - sessionTimeoutMs: this.taxonomyConfig.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS, - log, - }); - } - - private async notifyHandlerComplete( - requestId: string, - runId: string, - status: "done" | "failed", - ): Promise { - const schedulerUrl = this.taxonomyConfig.schedulerUrl; - if (!schedulerUrl) return; - - try { - const response = await fetch(`${schedulerUrl}/notify/handler-complete`, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ requestId, runId, handlerId: HANDLER_ID, status }), - }); - - if (!response.ok) { - console.warn(`[taxonomy-handler] Scheduler notify failed: ${response.status}`); - } - } catch (error) { - console.warn(`[taxonomy-handler] Scheduler notify error for ${requestId}/${runId}:`, error); - } - } -} - diff --git a/apps/workers/taxonomy/src/tools.ts b/apps/workers/taxonomy/src/tools.ts deleted file mode 100644 index ea4eced32..000000000 --- a/apps/workers/taxonomy/src/tools.ts +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { defineTool } from "@github/copilot-sdk"; -import { type ConversationTurn, type RequestDocument } from "shared"; - -interface GetAtifTrajectoryArgs { - iteration?: number; -} - -function selectTurnWithAtif(turns: ConversationTurn[] | undefined, requestedIteration?: number): ConversationTurn | undefined { - if (!turns?.length) return undefined; - - if (requestedIteration !== undefined) { - return turns.find((turn) => turn.iteration === requestedIteration && typeof turn.atifUrl === "string"); - } - - return [...turns] - .filter((turn) => typeof turn.atifUrl === "string") - .sort((a, b) => b.iteration - a.iteration)[0]; -} - -export function createTaxonomyTools( - apiBaseUrl: string, - requestId: string, -) { - const getRunData = defineTool("get_run_data", { - description: - "Fetch the full request document plus the active run state, including scenario, persona, turns, criteria results, and handler status.", - parameters: { - type: "object", - properties: {}, - }, - handler: async () => { - try { - const response = await fetch(`${apiBaseUrl}/api/v1/requests/${requestId}`); - if (!response.ok) { - return { error: `Failed to fetch request: ${response.status} ${response.statusText}` }; - } - - const request: RequestDocument = await response.json(); - const run = request.run; - - return { - request: { - id: request._id, - workerType: request.workerType, - model: request.model, - reasoningEffort: request.reasoningEffort, - maxIterations: request.maxIterations, - createdAt: request.createdAt, - updatedAt: request.updatedAt, - persona: request.persona, - personaInstructions: request.personaInstructions, - mcpServers: request.mcpServers, - skillRevisions: request.skillRevisions, - extensions: request.extensions, - priority: request.priority, - scenario: request.scenario, - }, - run: run ? { - id: run._id, - attemptNumber: run.attemptNumber, - status: run.status, - outcome: run.outcome, - result: run.result, - error: run.error, - startedAt: run.startedAt, - finishedAt: run.finishedAt, - updatedAt: run.updatedAt, - aiCallCount: run.aiCallCount, - tokenUsage: run.tokenUsage, - handlerStatus: run.handlerStatus, - turns: run.turns?.map((turn) => ({ - iteration: turn.iteration, - passed: turn.passed, - timestamp: turn.timestamp, - startedAt: turn.startedAt, - durationMs: turn.durationMs, - judgeFeedback: turn.judgeFeedback, - codingAgentResponse: turn.codingAgentResponse, - aiCallCount: turn.aiCallCount, - tokenUsage: turn.tokenUsage, - snapshotUrl: turn.snapshotUrl, - rawChatUrl: turn.rawChatUrl, - rawChatFormat: turn.rawChatFormat, - toolCallsUrl: turn.toolCallsUrl, - toolCallCount: turn.toolCallCount, - atifUrl: turn.atifUrl, - criteriaResults: turn.criteriaResults, - })) ?? [], - } : null, - }; - } catch (err) { - return { error: `Failed to fetch run data: ${err}` }; - } - }, - }); - - const getAtifTrajectory = defineTool("get_atif_trajectory", { - description: - "Fetch an ATIF trajectory JSON document for a specific iteration, or the latest available iteration when omitted.", - parameters: { - type: "object", - properties: { - iteration: { - type: "number", - description: "Optional 1-based iteration number. If omitted, the latest available ATIF trajectory is returned.", - }, - }, - }, - handler: async (args: GetAtifTrajectoryArgs) => { - try { - const response = await fetch(`${apiBaseUrl}/api/v1/requests/${requestId}`); - if (!response.ok) { - return { error: `Failed to fetch request: ${response.status} ${response.statusText}` }; - } - - const request: RequestDocument = await response.json(); - const selectedTurn = selectTurnWithAtif(request.run?.turns, args.iteration); - - if (!selectedTurn?.atifUrl) { - return { - error: args.iteration !== undefined - ? `No ATIF trajectory available for iteration ${args.iteration}` - : "No ATIF trajectory is available for this run", - }; - } - - const runId = request.run?._id; - const iteration = selectedTurn.iteration; - const atifUrl = runId - ? `${apiBaseUrl}/api/v1/requests/${requestId}/runs/${runId}/atif?iteration=${iteration}` - : `${apiBaseUrl}/api/v1/requests/${requestId}/atif?iteration=${iteration}`; - - const atifResponse = await fetch(atifUrl); - if (!atifResponse.ok) { - return { error: `Failed to fetch ATIF trajectory: ${atifResponse.status} ${atifResponse.statusText}` }; - } - - const trajectory: unknown = await atifResponse.json(); - - return { - iteration, - trajectory, - }; - } catch (err) { - return { error: `Failed to fetch ATIF trajectory: ${err}` }; - } - }, - }); - - return [getRunData, getAtifTrajectory]; -} diff --git a/apps/workers/taxonomy/tsconfig.json b/apps/workers/taxonomy/tsconfig.json deleted file mode 100644 index bf012ecbb..000000000 --- a/apps/workers/taxonomy/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../../tsconfig.base.json", - "compilerOptions": { - "outDir": "./dist", - "rootDir": "./src" - }, - "include": ["src/**/*"] -} diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml index 0f9a0753e..daa4d9c9f 100644 --- a/docker-compose.dev.yml +++ b/docker-compose.dev.yml @@ -180,30 +180,10 @@ services: - action: rebuild path: ./pnpm-lock.yaml - taxonomy-handler: - build: - target: dev - develop: - watch: - - action: sync - path: ./apps/workers/taxonomy/src - target: /app/apps/workers/taxonomy/src - - action: sync - path: ./packages/shared/src - target: /app/packages/shared/src - - action: rebuild - path: ./apps/workers/taxonomy/package.json - - action: rebuild - path: ./pnpm-lock.yaml - register-handler-post-processor: build: target: dev - register-handler-taxonomy: - build: - target: dev - post-processor: build: target: dev diff --git a/docker-compose.yml b/docker-compose.yml index 0124b6f71..3ab31dced 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -9,7 +9,6 @@ # docker compose --profile vscode-web up # + VS Code Web worker # docker compose --profile claude-code --profile copilot up # multiple workers # docker compose --profile report up # + Report Generator worker -# docker compose --profile taxonomy up # + Taxonomy handler worker # docker compose up mongodb redis azurite # infra only (run app services natively) # # Host-native debugging: @@ -641,51 +640,6 @@ services: api: condition: service_started - taxonomy-handler: - build: - context: . - dockerfile: apps/workers/taxonomy/Dockerfile - profiles: [taxonomy, all] - environment: - <<: *common-env - AZURE_STORAGE_QUEUE_TAXONOMY: pp-taxonomy-queue - TAXONOMY_MODEL: ${TAXONOMY_MODEL:-gpt-5.4} - SCOPE_MT_API_URL: http://api:80 - SCHEDULER_URL: http://scheduler:8080 - GITHUB_TOKEN: ${GITHUB_TOKEN:-} - TOKEN_MANAGER_URL: http://token-manager:80 - GIT_COMMIT: ${GIT_COMMIT:-development} - SESSION_TIMEOUT_MS: ${SESSION_TIMEOUT_MS:-300000} - depends_on: - mongodb: - condition: service_healthy - required: false - redis: - condition: service_healthy - azurite: - condition: service_healthy - api: - condition: service_started - scheduler: - condition: service_started - register-handler-taxonomy: - condition: service_completed_successfully - - register-handler-taxonomy: - build: - context: . - dockerfile: apps/workers/taxonomy/Dockerfile - profiles: [taxonomy, all] - environment: - <<: *common-env - HANDLER_YAML_PATH: apps/workers/taxonomy/handler.yaml - SCHEDULER_URL: http://scheduler:8080 - depends_on: - scheduler: - condition: service_started - restart: "no" - entrypoint: ["npx", "tsx", "packages/shared/src/scripts/register-handler.ts"] - register-handler-post-processor: build: context: . diff --git a/docs/architecture/db-migrations.md b/docs/architecture/db-migrations.md index fbe5b1cd4..f69880a10 100644 --- a/docs/architecture/db-migrations.md +++ b/docs/architecture/db-migrations.md @@ -103,7 +103,7 @@ When you run a command: | `008-backfill-ai-call-count` | Downloads HARs from blob storage to count AI completion calls per turn | | `009-add-requests-filter-indexes` | Adds indexes on `taskPromptId`, `status`, `outcome`, `workerType`, `deletedAt` for server-side filtering/grouping | | `018-migrate-services-to-handler-dag` | Replaces the legacy single `post-processor` service row with per-handler service registrations and dependencies | -| `019-add-handler-status-index` | Adds handler-specific dispatch indexes for `pp-atif`, `pp-taxonomy`, and `pp-report` polling | +| `019-add-handler-status-index` | Adds a handler-specific dispatch index for `pp-atif` polling | | `020-backfill-handler-status` | Backfills `run.handlerStatus.pp-atif` from deprecated `run.postProcessorStatus` / `run.postProcessorVersion` fields | ## CI/CD diff --git a/docs/architecture/overview.md b/docs/architecture/overview.md index 7550c5703..cb0aa299c 100644 --- a/docs/architecture/overview.md +++ b/docs/architecture/overview.md @@ -80,7 +80,6 @@ flowchart TB | `workers/coder-acp-claude-code` | Claude Code agent via Agent Client Protocol (ACP) | | `workers/coder-acp-copilot` | GitHub Copilot agent via Agent Client Protocol (ACP) | | `workers/report-generator` | Copilot SDK worker that generates post-run markdown reports | -| `workers/taxonomy` | Copilot SDK worker that generates validated post-run taxonomy JSON | | `gateway` | AI Gateway — shared Rust TLS-intercepting proxy with plugin architecture (HAR capture, future: token refresh, rate limiting) | ## Data Flow diff --git a/docs/architecture/post-processing.md b/docs/architecture/post-processing.md index dadda0544..097dc4b28 100644 --- a/docs/architecture/post-processing.md +++ b/docs/architecture/post-processing.md @@ -34,23 +34,7 @@ Two paths trigger post-processing: - Updates `run.turns.$.atifUrl` in the request document 4. On success, stamps `run.handlerStatus["pp-atif"] = { status: "done", version: N }` (while legacy `run.postProcessorVersion` / `run.postProcessorStatus` may still be mirrored during the transition) -5. Triggers the downstream taxonomy handler once the scheduler sees the dependency graph is satisfied. (Reports are **not** a DAG handler — see [Report Triggering](#report-triggering-on-dag-drain).) - -## Taxonomy Generation - -The taxonomy handler (`apps/workers/taxonomy/`) consumes messages from the dedicated `pp-taxonomy-queue` and produces a structured JSON artifact for a completed run. It uses the GitHub Copilot SDK with a tool-backed session to fetch run metadata and ATIF trajectories from the API, then validates the generated JSON against the shared taxonomy Zod schema. - -### Flow - -1. Queue message arrives: `{ type: "taxonomy", requestId, runId }` -2. Worker fetches the request document from MongoDB and marks `run.handlerStatus["pp-taxonomy"].status = "processing"` -3. Copilot SDK session calls: - - `get_run_data` to fetch the request + active run from the API - - `get_atif_trajectory` to fetch per-iteration ATIF JSON from the API (`GET /api/v1/requests/:id/runs/:runId/atif?iteration=N`) -4. The worker validates the assistant response with `taxonomySchema.safeParse()` -5. If validation fails, the worker feeds the schema errors back into the same session and retries up to 3 total attempts -6. On success, the worker uploads `taxonomy.json` to `{requestId}/runs/{runId}/taxonomy.json` -7. The worker stamps `run.handlerStatus["pp-taxonomy"] = { status: "done", version: 1 }` and calls `POST /notify/handler-complete` +5. Triggers any downstream handlers once the scheduler sees the dependency graph is satisfied. (Reports are **not** a DAG handler — see [Report Triggering](#report-triggering-on-dag-drain).) ### Blob Storage Layout @@ -61,52 +45,16 @@ The taxonomy handler (`apps/workers/taxonomy/`) consumes messages from the dedic atif.trajectory.json iteration-2/ atif.trajectory.json - taxonomy.json ``` -The completed run stores the taxonomy blob URL on `run.taxonomyUrl`. - ### API Endpoints | Endpoint | Description | | --- | --- | | `GET /api/v1/requests/:id/atif?iteration=N` | Download ATIF for the latest run | | `GET /api/v1/requests/:id/runs/:runId/atif?iteration=N` | Download ATIF for a specific run | -| `GET /api/v1/requests/:id/taxonomy` | Download taxonomy JSON for the latest run | -| `GET /api/v1/requests/:id/runs/:runId/taxonomy` | Download taxonomy JSON for a specific run | - -The `iteration` query parameter is mandatory only for the ATIF endpoints. ATIF files are also included in archive exports as `iteration-{N}.atif.trajectory.json`. - -### Local troubleshooting: taxonomy CLI - -The Copilot SDK generation loop lives in `apps/workers/taxonomy/src/taxonomy-generator.ts` (`generateTaxonomy()`), shared by both the queue processor and a standalone developer CLI (`src/cli.ts`). The CLI invokes generation directly against an existing `requestId`, streams the session events live, and saves the validated taxonomy to a local file — **it never writes to MongoDB, blob storage, or the scheduler** (read-only). It is a developer tool and is intentionally not part of the Scope CLI. - -Because both taxonomy tools (`get_run_data` and `get_atif_trajectory`) read through the API, the CLI needs only an API URL and a Copilot token — no storage connection string. This lets it run against any environment (local or a remote deployment such as integration) given a reachable API. - -```bash -# Local stack (use your worktree's host-mapped API port): -SCOPE_MT_API_URL=http://localhost:3001 \ -GITHUB_TOKEN=$(gh auth token) \ -pnpm taxonomy [--run ] [--model ] [--timeout ] [-o out.json] [--stdout] [--quiet] - -# Integration (read-only against the deployed API): -SCOPE_MT_API_URL=https://msscope-int.azurewebsites.net \ -GITHUB_TOKEN=$(gh auth token) \ -pnpm taxonomy -o taxonomy-int.json -``` - -The root `pnpm taxonomy` script proxies to `pnpm --filter taxonomy-handler taxonomy` (i.e. `tsx src/cli.ts`). - -| Option | Description | -| --- | --- | -| `--run, -r ` | Run id used in the prompt/logging (default: active run resolved from the API) | -| `--model ` | Override `TAXONOMY_MODEL` (e.g. A/B a reasoning model vs the `gpt-5.4` default) | -| `--timeout ` | Override `SESSION_TIMEOUT_MS` (per-attempt session timeout) | -| `--output, -o ` | Output file path (default: `taxonomy-.json` in the cwd) | -| `--stdout` | Also print the taxonomy JSON to stdout | -| `--quiet` | Suppress live session-event streaming on stderr | -Live progress (tool calls, errors, deltas) is written to stderr so the saved JSON file stays clean. The CLI exits non-zero on failure (empty response, JSON/schema validation failure after 3 attempts, timeout, or model rate limit) and surfaces the underlying error message — making it well suited to diagnosing the oversized-`get_atif_trajectory` paging loop and Copilot model rate limits. +The `iteration` query parameter is mandatory for the ATIF endpoints. ATIF files are also included in archive exports as `iteration-{N}.atif.trajectory.json`. ## Handler Interface @@ -151,7 +99,7 @@ processor.start(); The post-processor uses a version-based re-processing scheme: -- Each handler is registered independently in the `services` collection using a `post-process-handler` document keyed by handler ID (for example `pp-atif`, `pp-taxonomy`) +- Each handler is registered independently in the `services` collection using a `post-process-handler` document keyed by handler ID (for example `pp-atif`) - Each registration stores the handler `version`, queue name, selector, `autoBackfill` behavior, and `dependsOn` DAG edges - The scheduler compares each request's per-handler status/version state (for example `run.handlerStatus["pp-atif"]`) against the registered handler entry for that selector - Requests with missing or outdated handler state are re-dispatched for that specific handler once its dependencies are satisfied @@ -160,18 +108,17 @@ This allows deploying handler improvements and having them automatically applied ## Handler Registration -Each post-process handler declares its DAG metadata in a `handler.yaml` file colocated with the worker (e.g. `apps/workers/taxonomy/handler.yaml`). This mirrors the coding-agent `agent.yaml` registration pattern. +Each post-process handler declares its DAG metadata in a `handler.yaml` file colocated with the worker (e.g. `apps/workers/post-processor/handler.yaml`). This mirrors the coding-agent `agent.yaml` registration pattern. ```yaml -# apps/workers/taxonomy/handler.yaml -_id: pp-taxonomy +# apps/workers/post-processor/handler.yaml +_id: pp-atif type: post-process-handler version: 1 -queue: pp-taxonomy-queue -selector: taxonomy -autoBackfill: false -dependsOn: - - pp-atif +queue: post-processor-queue +selector: atif +autoBackfill: true +dependsOn: [] ``` On deploy, a generic registration script — `packages/shared/src/scripts/register-handler.ts` — reads the `handler.yaml` pointed to by `HANDLER_YAML_PATH`, waits for the scheduler's `/health`, and POSTs the parsed document to `${SCHEDULER_URL}/handlers/register` (with retry). The scheduler validates the document, runs a cycle check against the existing topology, and upserts it into the `services` collection via `HandlerDispatcher.registerHandler`. **Workers never write to the `services` collection directly** — the scheduler is the sole owner. @@ -185,8 +132,8 @@ flowchart LR **Where it runs:** -- **Docker Compose:** one `register-handler-` init service per handler (`pp-atif`, `pp-taxonomy`) runs the generic script via `tsx`, gated on the scheduler being up. The worker waits for its registration service to complete. -- **Kubernetes:** a `register-handler-post-processor` Job runs the compiled script (`node packages/shared/dist/scripts/register-handler.js`) on each deploy. Only `pp-atif` is registered in K8s today because it is the only post-process handler deployed to the cluster; `pp-taxonomy` is registered in Compose only until the taxonomy worker is deployed to K8s. The scheduler exposes a `Service` (`scheduler.scoped.svc.cluster.local:8080`) so Jobs and workers can reach `/handlers/register` and the notify endpoints. +- **Docker Compose:** one `register-handler-` init service per handler (e.g. `pp-atif`) runs the generic script via `tsx`, gated on the scheduler being up. The worker waits for its registration service to complete. +- **Kubernetes:** a `register-handler-post-processor` Job runs the compiled script (`node packages/shared/dist/scripts/register-handler.js`) on each deploy. Only `pp-atif` is registered in K8s today because it is the only post-process handler deployed to the cluster. The scheduler exposes a `Service` (`scheduler.scoped.svc.cluster.local:8080`) so Jobs and workers can reach `/handlers/register` and the notify endpoints. To **add or change a handler**, edit its `handler.yaml` (bump `version`, adjust `dependsOn`, etc.) — no code or migration changes are needed for registration. @@ -206,7 +153,7 @@ active template's trigger and creates the properly-templated `ReportDocument`(s) ```mermaid flowchart LR - RT["run done"] --> DAG["scheduler dispatches DAG
(pp-atif → pp-taxonomy)"] + RT["run done"] --> DAG["scheduler dispatches DAG
(pp-atif → …)"] DAG -->|"all handlers terminal"| DR{DAG drained?} DR -->|yes| TRIG["POST /api/v1/reports/trigger
{ requestId }"] TRIG --> API["API evaluates each template trigger
→ ReportDocument + report-queue {reportId}"] @@ -219,7 +166,7 @@ flowchart LR registered handler is terminal. A run with **zero** registered handlers is vacuously drained, so reports trigger immediately on run completion. -**Trigger regardless of handler success.** A flaky taxonomy must not block report +**Trigger regardless of handler success.** A flaky handler must not block report generation (reports analyze the run/ATIF), so the scheduler triggers reports whenever the DAG drains — not only when every handler succeeded. @@ -263,20 +210,18 @@ stateDiagram-v2 | Environment Variable | Default | Description | | --- | --- | --- | | `AZURE_STORAGE_QUEUE_POSTPROCESSOR` | `post-processor-queue` | Queue name for ATIF post-processor messages | -| `AZURE_STORAGE_QUEUE_TAXONOMY` | `pp-taxonomy-queue` | Queue name for taxonomy-generation jobs | | `SCHEDULER_PP_POLL_INTERVAL_MS` | `30000` | Scheduler backfill polling interval | | `BATCH_SIZE` | `1` | Messages to process per poll (worker-side) | | `POLL_INTERVAL_MS` | `5000` | Worker queue polling interval | -| `SCOPE_MT_API_URL` / `API_BASE_URL` | `http://localhost:3001` | API URL used by report/taxonomy Copilot tools | -| `TAXONOMY_MODEL` | `gpt-5.4` | Copilot SDK model used by the taxonomy handler | -| `SESSION_TIMEOUT_MS` | `300000` | Timeout for report/taxonomy Copilot SDK sessions | +| `SCOPE_MT_API_URL` / `API_BASE_URL` | `http://localhost:3001` | API URL used by report Copilot tools | +| `SESSION_TIMEOUT_MS` | `300000` | Timeout for report Copilot SDK sessions | | `SCHEDULER_URL` | _(unset)_ | Scheduler base URL — used by handlers to notify completion and by the register-handler script to reach `/handlers/register` | | `API_URL` | `http://api:80` | API base URL the **scheduler** uses to call `POST /api/v1/reports/trigger` when a run's handler DAG drains | | `HANDLER_YAML_PATH` | _(unset)_ | Path to a handler's `handler.yaml`, read by the generic `register-handler` script | ## Infrastructure -- **Queues:** Azure Storage Queues (`post-processor-queue` for ATIF, `pp-taxonomy-queue` for taxonomy, `report-queue` for reports) +- **Queues:** Azure Storage Queues (`post-processor-queue` for ATIF, `report-queue` for reports) - **Blob Storage:** `snapshots` container (shared with HAR, tool-calls, and other artifacts) - **Database:** MongoDB `requests` collection (`run.handlerStatus` map keyed by handler ID, with deprecated `run.postProcessorStatus` / `run.postProcessorVersion` compatibility fields during migration) - **KEDA:** ScaledObject scales the worker to zero when queue is empty diff --git a/package.json b/package.json index 2905d5efc..46b946a51 100644 --- a/package.json +++ b/package.json @@ -17,7 +17,6 @@ "dev:coder-acp-claude-code": "pnpm --filter coder-acp-claude-code dev", "dev:coder-acp-copilot": "pnpm --filter coder-acp-copilot dev", "dev:report-generator": "pnpm --filter report-generator dev", - "taxonomy": "pnpm --filter taxonomy-handler taxonomy", "docker:up": "scripts/worktree-env.sh && scripts/dev-compose.sh up --build", "docker:up:claude-code": "scripts/worktree-env.sh && scripts/dev-compose.sh --env-file .env --env-file apps/workers/coder-acp-claude-code/versions.env --profile claude-code --profile report up --build", "docker:up:copilot": "scripts/worktree-env.sh && scripts/dev-compose.sh --env-file .env --env-file apps/workers/coder-acp-copilot/versions.env --profile copilot --profile report up --build", @@ -26,9 +25,9 @@ "docker:up:portal": "scripts/worktree-env.sh && scripts/dev-compose.sh --profile portal up --build", "docker:dev": "scripts/worktree-env.sh && COMPOSE_EXPERIMENTAL_WATCH_POLL=1 scripts/dev-compose.sh -f docker-compose.yml -f docker-compose.dev.yml up --build --watch", "docker:dev:claude-code": "scripts/worktree-env.sh && GIT_BRANCH=$(git rev-parse --abbrev-ref HEAD) COMPOSE_EXPERIMENTAL_WATCH_POLL=1 scripts/dev-compose.sh --env-file .env --env-file apps/workers/coder-acp-claude-code/versions.env -f docker-compose.yml -f docker-compose.dev.yml --profile claude-code --profile report --profile post-processor --profile portal up --build --watch", - "docker:dev:copilot": "scripts/worktree-env.sh && GIT_BRANCH=$(git rev-parse --abbrev-ref HEAD) COMPOSE_EXPERIMENTAL_WATCH_POLL=1 scripts/dev-compose.sh --env-file .env --env-file apps/workers/coder-acp-copilot/versions.env -f docker-compose.yml -f docker-compose.dev.yml --profile copilot --profile report --profile post-processor --profile taxonomy --profile portal up --build --watch", + "docker:dev:copilot": "scripts/worktree-env.sh && GIT_BRANCH=$(git rev-parse --abbrev-ref HEAD) COMPOSE_EXPERIMENTAL_WATCH_POLL=1 scripts/dev-compose.sh --env-file .env --env-file apps/workers/coder-acp-copilot/versions.env -f docker-compose.yml -f docker-compose.dev.yml --profile copilot --profile report --profile post-processor --profile portal up --build --watch", "docker:dev:portal": "scripts/worktree-env.sh && GIT_BRANCH=$(git rev-parse --abbrev-ref HEAD) COMPOSE_EXPERIMENTAL_WATCH_POLL=1 scripts/dev-compose.sh -f docker-compose.yml -f docker-compose.dev.yml --profile portal up --build --watch", - "docker:dev:all": "scripts/worktree-env.sh && GIT_BRANCH=$(git rev-parse --abbrev-ref HEAD) COMPOSE_EXPERIMENTAL_WATCH_POLL=1 scripts/dev-compose.sh --env-file .env --env-file apps/workers/coder-acp-copilot/versions.env --env-file apps/workers/coder-acp-claude-code/versions.env -f docker-compose.yml -f docker-compose.dev.yml --profile claude-code --profile copilot --profile report --profile post-processor --profile taxonomy --profile portal up --build --watch", + "docker:dev:all": "scripts/worktree-env.sh && GIT_BRANCH=$(git rev-parse --abbrev-ref HEAD) COMPOSE_EXPERIMENTAL_WATCH_POLL=1 scripts/dev-compose.sh --env-file .env --env-file apps/workers/coder-acp-copilot/versions.env --env-file apps/workers/coder-acp-claude-code/versions.env -f docker-compose.yml -f docker-compose.dev.yml --profile claude-code --profile copilot --profile report --profile post-processor --profile portal up --build --watch", "docker:dev:build": "scripts/worktree-env.sh && GIT_BRANCH=$(git rev-parse --abbrev-ref HEAD) scripts/dev-compose.sh --env-file .env --env-file apps/workers/coder-acp-copilot/versions.env --env-file apps/workers/coder-acp-claude-code/versions.env -f docker-compose.yml -f docker-compose.dev.yml --profile claude-code --profile copilot --profile report --profile portal build", "docker:down": "scripts/worktree-env.sh && scripts/dev-compose.sh --env-file .env --env-file apps/workers/coder-acp-copilot/versions.env --env-file apps/workers/coder-acp-claude-code/versions.env --profile claude-code --profile copilot --profile report --profile portal down --volumes", "docker:build": "scripts/worktree-env.sh && scripts/dev-compose.sh --env-file .env --env-file apps/workers/coder-acp-copilot/versions.env --env-file apps/workers/coder-acp-claude-code/versions.env --profile claude-code --profile copilot --profile report build", diff --git a/packages/db-migrations/src/migrations/018-migrate-services-to-handler-dag.ts b/packages/db-migrations/src/migrations/018-migrate-services-to-handler-dag.ts index bcb3b3ade..6d2aa2c94 100644 --- a/packages/db-migrations/src/migrations/018-migrate-services-to-handler-dag.ts +++ b/packages/db-migrations/src/migrations/018-migrate-services-to-handler-dag.ts @@ -7,7 +7,7 @@ import type { MigrationInterface } from "mongo-migrate-ts"; /** * Migration 018: Remove the legacy "post-processor" service entry. * - * Handler service registration (pp-atif, pp-taxonomy) is now owned + * Handler service registration (e.g. pp-atif) is now owned * by each worker's handler.yaml + the generic register-handler script, * which POSTs to the scheduler's POST /handlers/register endpoint on deploy. * Reports are not a DAG handler — the scheduler triggers report generation diff --git a/packages/db-migrations/src/migrations/019-add-handler-status-index.ts b/packages/db-migrations/src/migrations/019-add-handler-status-index.ts index 577dc8901..ee6e35f95 100644 --- a/packages/db-migrations/src/migrations/019-add-handler-status-index.ts +++ b/packages/db-migrations/src/migrations/019-add-handler-status-index.ts @@ -13,14 +13,6 @@ const HANDLER_STATUS_INDEXES = [ updatedAt: -1 as const, }, }, - { - name: "idx_handler_dispatch_taxonomy", - key: { - "run.handlerStatus.pp-taxonomy.status": 1 as const, - "run.status": 1 as const, - updatedAt: -1 as const, - }, - }, ] as const; export class AddHandlerStatusIndex implements MigrationInterface { diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index e2af74303..392a9cde2 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -21,5 +21,4 @@ export * from "./devproxy/index.js"; export * from "./har/index.js"; export * from "./utils/index.js"; export * from "./schemas/index.js"; -export * from "./schemas/taxonomy.js"; export * from "./cursor.js"; diff --git a/packages/shared/src/schemas/index.ts b/packages/shared/src/schemas/index.ts index 06332d90d..b64fcee87 100644 --- a/packages/shared/src/schemas/index.ts +++ b/packages/shared/src/schemas/index.ts @@ -19,4 +19,3 @@ export * from "./token.js"; export * from "./account.js"; export * from "./feature-flag.js"; export * from "./profile.js"; -export * from "./taxonomy.js"; diff --git a/packages/shared/src/schemas/request.ts b/packages/shared/src/schemas/request.ts index ea6f3d4da..bdcf6cc88 100644 --- a/packages/shared/src/schemas/request.ts +++ b/packages/shared/src/schemas/request.ts @@ -173,7 +173,6 @@ export const RunStateSchema = z podName: z.string().optional(), }).optional(), harUrl: z.string().optional(), - taxonomyUrl: z.string().optional(), videoUrls: z.array(z.string()).optional(), setupVideoUrls: z.array(z.string()).optional(), tokenUsage: TokenUsageSchema.optional(), diff --git a/packages/shared/src/schemas/taxonomy.test.ts b/packages/shared/src/schemas/taxonomy.test.ts deleted file mode 100644 index 320f89ceb..000000000 --- a/packages/shared/src/schemas/taxonomy.test.ts +++ /dev/null @@ -1,180 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { describe, expect, it } from "vitest"; -import { taxonomySchema } from "./taxonomy.js"; - -describe("taxonomySchema", () => { - const validFixture = { - meta: { - generatedAt: "2025-02-01T12:00:00Z", - schemaVersion: "1.0.0", - runId: "run-123", - requestId: "req-456", - }, - scorecard: { - summary: "The agent usually succeeds but struggles with recovery quality.", - profileResults: [ - { - profileId: "profile-best", - select: "best", - taskOutcome: "success", - overallScore: 92, - dimensions: [ - { - name: "Correctness", - score: 95, - rationale: "Implemented the requested behavior fully.", - evidence: ["All acceptance criteria passed", "No regressions observed"], - }, - ], - }, - ], - crossProfileInsights: [ - "The agent communicates clearly across profiles.", - "Stress conditions reduce recovery quality.", - ], - }, - behaviorAnalysis: { - patterns: [ - { - id: "pattern-1", - category: "strength", - title: "Consistent planning", - description: "The agent outlines a clear plan before making changes.", - frequency: 0.75, - impact: "high", - evidence: [ - { - runId: "run-123", - iteration: 1, - excerpt: "Plan: inspect the failing endpoint, then patch the handler.", - }, - ], - }, - ], - agentPersonality: { - communicationStyle: "Concise and structured", - problemSolvingApproach: "Hypothesis-driven debugging", - errorRecoveryBehavior: "Retries with targeted fixes after inspecting evidence", - }, - }, - actionList: { - fix: [ - { - id: "action-1", - title: "Stabilize recovery prompts", - priority: "critical", - description: "Reduce failures when the first attempt is rejected.", - ownership: "prompt-engineer", - relatedPatterns: ["pattern-1"], - suggestedApproach: "Add explicit fallback guidance for failed first passes.", - }, - ], - improve: [ - { - id: "action-2", - title: "Expand planning examples", - priority: "medium", - description: "Reinforce successful planning behavior.", - ownership: "agent-team", - relatedPatterns: ["pattern-1"], - suggestedApproach: "Fine-tune on traces with strong upfront decomposition.", - }, - ], - investigate: [ - { - id: "action-3", - title: "Review profile variance", - priority: "low", - description: "Understand why profile-specific regressions appear sporadically.", - ownership: "scenario-author", - relatedPatterns: ["pattern-1"], - suggestedApproach: "Compare scenario wording against affected profile runs.", - }, - ], - }, - }; - - it("accepts a valid taxonomy fixture", () => { - const result = taxonomySchema.safeParse(validFixture); - expect(result.success).toBe(true); - }); - - it("rejects fixtures missing required fields with precise paths", () => { - const invalidFixture = { - ...validFixture, - scorecard: { - ...validFixture.scorecard, - profileResults: [ - { - ...validFixture.scorecard.profileResults[0], - dimensions: [ - { - name: "Correctness", - score: 95, - evidence: ["All acceptance criteria passed"], - }, - ], - }, - ], - }, - behaviorAnalysis: { - ...validFixture.behaviorAnalysis, - agentPersonality: { - communicationStyle: "Concise and structured", - errorRecoveryBehavior: "Retries with targeted fixes after inspecting evidence", - }, - }, - }; - - const result = taxonomySchema.safeParse(invalidFixture); - expect(result.success).toBe(false); - if (result.success) { - throw new Error("Expected invalid taxonomy fixture to fail parsing"); - } - - const issuePaths = result.error.issues.map((issue) => issue.path); - expect(issuePaths).toContainEqual([ - "scorecard", - "profileResults", - 0, - "dimensions", - 0, - "rationale", - ]); - expect(issuePaths).toContainEqual([ - "behaviorAnalysis", - "agentPersonality", - "problemSolvingApproach", - ]); - }); - - it("enforces enum values", () => { - const invalidFixture = { - ...validFixture, - actionList: { - ...validFixture.actionList, - fix: [ - { - ...validFixture.actionList.fix[0], - priority: "urgent", - }, - ], - }, - }; - - const result = taxonomySchema.safeParse(invalidFixture); - expect(result.success).toBe(false); - if (result.success) { - throw new Error("Expected invalid enum fixture to fail parsing"); - } - - expect(result.error.issues.map((issue) => issue.path)).toContainEqual([ - "actionList", - "fix", - 0, - "priority", - ]); - }); -}); diff --git a/packages/shared/src/schemas/taxonomy.ts b/packages/shared/src/schemas/taxonomy.ts deleted file mode 100644 index a837d4f91..000000000 --- a/packages/shared/src/schemas/taxonomy.ts +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { z } from "zod"; - -const scoreSchema = z.number().min(0).max(100); -const frequencySchema = z.number().min(0).max(1); - -/** Taxonomy document metadata. */ -export const taxonomyMetaSchema = z.object({ - generatedAt: z.string().datetime({ offset: true }), - schemaVersion: z.string().min(1), - runId: z.string().min(1), - requestId: z.string().min(1), -}); - -/** Scorecard dimension result for a single profile. */ -export const scorecardDimensionSchema = z.object({ - name: z.string().min(1), - score: scoreSchema, - rationale: z.string().min(1), - evidence: z.array(z.string().min(1)), -}); - -/** Scorecard result for a specific profile slice. */ -export const profileResultSchema = z.object({ - profileId: z.string().min(1), - select: z.enum(["best", "median", "worst"]), - taskOutcome: z.enum(["success", "partial", "failure"]), - overallScore: scoreSchema, - dimensions: z.array(scorecardDimensionSchema), -}); - -/** Top-level scorecard section summarizing profile results. */ -export const scorecardSchema = z.object({ - summary: z.string().min(1), - profileResults: z.array(profileResultSchema), - crossProfileInsights: z.array(z.string().min(1)), -}); - -/** Evidence excerpt supporting an observed behavior pattern. */ -export const behaviorEvidenceSchema = z.object({ - runId: z.string().min(1), - iteration: z.number().int().min(0), - excerpt: z.string().min(1), -}); - -/** Cross-run behavioral pattern identified by the taxonomy analysis. */ -export const behaviorPatternSchema = z.object({ - id: z.string().min(1), - category: z.enum(["strength", "weakness", "inconsistency", "regression"]), - title: z.string().min(1), - description: z.string().min(1), - frequency: frequencySchema, - impact: z.enum(["critical", "high", "medium", "low"]), - evidence: z.array(behaviorEvidenceSchema), -}); - -/** Qualitative description of the agent's personality traits. */ -export const agentPersonalitySchema = z.object({ - communicationStyle: z.string().min(1), - problemSolvingApproach: z.string().min(1), - errorRecoveryBehavior: z.string().min(1), -}); - -/** Behavior analysis section describing patterns and personality. */ -export const behaviorAnalysisSchema = z.object({ - patterns: z.array(behaviorPatternSchema), - agentPersonality: agentPersonalitySchema, -}); - -/** Action item emitted by the taxonomy analysis. */ -export const actionItemSchema = z.object({ - id: z.string().min(1), - title: z.string().min(1), - priority: z.enum(["critical", "high", "medium", "low"]), - description: z.string().min(1), - ownership: z.enum([ - "agent-team", - "platform-team", - "prompt-engineer", - "scenario-author", - ]), - relatedPatterns: z.array(z.string().min(1)), - suggestedApproach: z.string().min(1), -}); - -/** Prioritized action lists grouped by remediation intent. */ -export const actionListSchema = z.object({ - fix: z.array(actionItemSchema), - improve: z.array(actionItemSchema), - investigate: z.array(actionItemSchema), -}); - -/** Complete taxonomy document produced by the taxonomy post-processor. */ -export const taxonomySchema = z.object({ - meta: taxonomyMetaSchema, - scorecard: scorecardSchema, - behaviorAnalysis: behaviorAnalysisSchema, - actionList: actionListSchema, -}); - -/** Inferred TypeScript type for the taxonomy document. */ -export type TaxonomyDocument = z.infer; diff --git a/packages/shared/src/scripts/register-handler.test.ts b/packages/shared/src/scripts/register-handler.test.ts index 0c3858b58..162916404 100644 --- a/packages/shared/src/scripts/register-handler.test.ts +++ b/packages/shared/src/scripts/register-handler.test.ts @@ -6,11 +6,11 @@ import { parseHandlerDocument } from "./register-handler.js"; describe("parseHandlerDocument", () => { const valid = { - _id: "pp-taxonomy", + _id: "pp-example", type: "post-process-handler", version: 1, - queue: "pp-taxonomy-queue", - selector: "taxonomy", + queue: "pp-example-queue", + selector: "example", autoBackfill: false, dependsOn: ["pp-atif"], }; diff --git a/packages/shared/src/types/types.ts b/packages/shared/src/types/types.ts index 1a176e9c1..374d5b2ca 100644 --- a/packages/shared/src/types/types.ts +++ b/packages/shared/src/types/types.ts @@ -272,14 +272,13 @@ export interface RunState { podName?: string; }; harUrl?: string; - taxonomyUrl?: string; videoUrls?: string[]; setupVideoUrls?: string[]; tokenUsage?: TokenUsage; aiCallCount?: number; rawChatUrl?: string; rawChatFormat?: string; - /** Per-handler post-processing status. Keys are handler IDs (e.g. "pp-atif", "pp-taxonomy"). */ + /** Per-handler post-processing status. Keys are handler IDs (e.g. "pp-atif"). */ handlerStatus?: Record; /** Set once the scheduler has triggered report generation for this run after * the handler DAG drained (every handler reached a terminal state). Acts as @@ -329,7 +328,6 @@ export const RUN_STATE_FIELD_NAMES = [ "lastHeartbeatAt", "worker", "harUrl", - "taxonomyUrl", "videoUrls", "setupVideoUrls", "tokenUsage", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a7903fc00..339c191ba 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -705,31 +705,6 @@ importers: specifier: ^5.6.2 version: 5.9.3 - apps/workers/taxonomy: - dependencies: - '@azure/storage-queue': - specifier: ^12.25.0 - version: 12.29.0 - '@github/copilot-sdk': - specifier: ^0.1.17 - version: 0.1.23 - dotenv: - specifier: ^16.4.5 - version: 16.6.1 - shared: - specifier: workspace:* - version: link:../../../packages/shared - devDependencies: - '@types/node': - specifier: ^22.7.0 - version: 22.19.10 - tsx: - specifier: ^4.19.0 - version: 4.21.0 - typescript: - specifier: ^5.6.2 - version: 5.9.3 - packages/copilot-driver-ext: devDependencies: '@types/node': From 1fb829c008fadb5fa02f4662d4be328d0a930083 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Sun, 28 Jun 2026 19:16:42 -0700 Subject: [PATCH 010/210] feat(observations): observation criteria + pp-taxonomy handler, CLI, config, docs Add kind:gate|observation discriminator + hard-coded taxonomyElementId to criteria; record-only per-iteration boolean observations evaluated post-run by the pp-taxonomy handler (reuses judge via JudgeClient, dependsOn pp-atif) and stored as turn.observationResults. Request-level opt-in via observations[]. CLI, migration 021, deploy wiring, config seeds, and docs included. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ENV_VARIABLES.md | 8 +- README.md | 1 + .../openapi-snapshot.test.ts.snap | 93 ++++++++++++++++ apps/api/src/endpoints.test.ts | 28 +++++ apps/api/src/routes/criteria.ts | 16 ++- apps/api/src/routes/requests/index.ts | 51 ++++++++- .../__snapshots__/cli-commands.test.ts.snap | 5 + apps/cli/src/commands/criteria.ts | 36 ++++++- apps/cli/src/commands/run.ts | 7 +- apps/cli/src/run-get-action.ts | 45 +++++++- apps/cli/src/utils/yaml-mappers.ts | 9 +- apps/judge/src/index.ts | 27 ++++- .../post-processor/handler.taxonomy.yaml | 17 +++ .../src/handlers/taxonomy-handler.test.ts | 80 ++++++++++++++ .../src/handlers/taxonomy-handler.ts | 90 ++++++++++++++++ apps/workers/post-processor/src/index.ts | 2 + .../criteria/auth_configured_correctly.yaml | 8 ++ .../dependency_added_then_removed.yaml | 9 ++ config/criteria/idiomatic_api_usage.yaml | 8 ++ docker-compose.dev.yml | 4 + docker-compose.yml | 19 ++++ docs/architecture/app-design.md | 7 +- docs/architecture/criteria-provider.md | 4 + docs/architecture/overview.md | 1 + docs/architecture/post-processing.md | 21 +++- .../migrations/021-backfill-criteria-kind.ts | 47 ++++++++ .../db-migrations/src/required-migrations.ts | 1 + .../src/criteria/criteria-provider-api.ts | 4 + .../src/criteria/criteria-provider-fs.ts | 13 +++ .../src/criteria/criteria-store.test.ts | 59 +++++++++++ .../shared/src/criteria/criteria-store.ts | 100 +++++++++++++++++- packages/shared/src/criteria/index.ts | 1 + .../src/criteria/observation-taxonomy.ts | 43 ++++++++ packages/shared/src/judge/judge-client.ts | 4 + packages/shared/src/schemas/criteria.ts | 12 ++- packages/shared/src/schemas/request.ts | 3 + packages/shared/src/schemas/schemas.test.ts | 27 +++++ packages/shared/src/storage/blob-storage.ts | 23 ++++ packages/shared/src/types/types.ts | 54 ++++++++++ 39 files changed, 964 insertions(+), 23 deletions(-) create mode 100644 apps/workers/post-processor/handler.taxonomy.yaml create mode 100644 apps/workers/post-processor/src/handlers/taxonomy-handler.test.ts create mode 100644 apps/workers/post-processor/src/handlers/taxonomy-handler.ts create mode 100644 config/criteria/auth_configured_correctly.yaml create mode 100644 config/criteria/dependency_added_then_removed.yaml create mode 100644 config/criteria/idiomatic_api_usage.yaml create mode 100644 packages/db-migrations/src/migrations/021-backfill-criteria-kind.ts create mode 100644 packages/shared/src/criteria/observation-taxonomy.ts diff --git a/ENV_VARIABLES.md b/ENV_VARIABLES.md index ec5d268e1..3001c4b16 100644 --- a/ENV_VARIABLES.md +++ b/ENV_VARIABLES.md @@ -341,7 +341,13 @@ How often the post-processor dispatcher polls for completed runs needing post-pr **Default:** `post-processor-queue` **Type:** string -Azure Storage Queue name used by both the scheduler (to enqueue post-processing work) and the post-processor worker (to dequeue). Must match between the two services. +Azure Storage Queue name used by both the scheduler (to enqueue post-processing work) and the post-processor worker (to dequeue). Must match between the two services. The `pp-taxonomy` observation handler shares this queue. + +### JUDGE_URL +**Default:** falls back to `JUDGE_SERVICE_URL`, then `http://localhost:3002` +**Type:** URL string + +Base URL of the judge service used by the `pp-taxonomy` post-process handler to evaluate observation criteria per iteration (snapshot + ATIF trajectory → boolean + evidence). The handler reuses the shared `JudgeClient`, so `JUDGE_CLIENT_TIMEOUT` / `JUDGE_CLIENT_RETRIES` apply. In Docker/K8s the worker reads `JUDGE_SERVICE_URL` from `worker-config`; no extra var needed. See issue #1156 and [docs/architecture/post-processing.md](docs/architecture/post-processing.md). ### SCHEDULER_URL **Default:** (not set) diff --git a/README.md b/README.md index 38c22b8dd..e8df7301b 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,7 @@ | **coder-acp-copilot** | GitHub Copilot agent worker (ACP SDK) | | **coder-acp-claude-code** | Claude Code agent worker (ACP SDK) | | **report-generator** | Post-run evaluation report generator (Copilot SDK) | +| **post-processor** | DAG post-run handlers: `pp-atif` (ATIF trajectory) + `pp-taxonomy` (boolean observations via judge) | | **model-scanners** | Feature detection for Copilot and Anthropic models | | **version-checkers** | Poll for new releases of agents/tools (`acp-copilot`, `claude-code`, `vscode-electron`) | diff --git a/apps/api/src/__snapshots__/openapi-snapshot.test.ts.snap b/apps/api/src/__snapshots__/openapi-snapshot.test.ts.snap index d99d079de..3d5d038c9 100644 --- a/apps/api/src/__snapshots__/openapi-snapshot.test.ts.snap +++ b/apps/api/src/__snapshots__/openapi-snapshot.test.ts.snap @@ -512,6 +512,12 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "judgeFeedback": { "type": "string", }, + "observationResults": { + "items": { + "$ref": "#/components/schemas/CriterionResult", + }, + "type": "array", + }, "passed": { "type": "boolean", }, @@ -653,9 +659,25 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "pattern": "^[a-z][a-z0-9_]*$", "type": "string", }, + "kind": { + "default": "gate", + "enum": [ + "gate", + "observation", + ], + "type": "string", + }, "prompt": { "type": "string", }, + "taxonomyElementId": { + "enum": [ + "dimension:idiomatic-use", + "dimension:dependency-currency", + "dimension:configuration-correctness", + ], + "type": "string", + }, }, "required": [ "id", @@ -873,6 +895,12 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "model": { "type": "string", }, + "observations": { + "items": { + "type": "string", + }, + "type": "array", + }, "persona": { "$ref": "#/components/schemas/Persona", }, @@ -1020,9 +1048,24 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "id": { "type": "string", }, + "kind": { + "enum": [ + "gate", + "observation", + ], + "type": "string", + }, "prompt": { "type": "string", }, + "taxonomyElementId": { + "enum": [ + "dimension:idiomatic-use", + "dimension:dependency-currency", + "dimension:configuration-correctness", + ], + "type": "string", + }, }, "required": [ "id", @@ -1068,9 +1111,24 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "id": { "type": "string", }, + "kind": { + "enum": [ + "gate", + "observation", + ], + "type": "string", + }, "prompt": { "type": "string", }, + "taxonomyElementId": { + "enum": [ + "dimension:idiomatic-use", + "dimension:dependency-currency", + "dimension:configuration-correctness", + ], + "type": "string", + }, "updatedAt": { "format": "date-time", "type": [ @@ -2430,6 +2488,12 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "model": { "type": "string", }, + "observations": { + "items": { + "type": "string", + }, + "type": "array", + }, "persona": { "$ref": "#/components/schemas/Persona", }, @@ -3087,9 +3151,24 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` }, "type": "array", }, + "kind": { + "enum": [ + "gate", + "observation", + ], + "type": "string", + }, "prompt": { "type": "string", }, + "taxonomyElementId": { + "enum": [ + "dimension:idiomatic-use", + "dimension:dependency-currency", + "dimension:configuration-correctness", + ], + "type": "string", + }, }, "type": "object", }, @@ -4132,6 +4211,20 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "type": "string", }, }, + { + "description": "Filter by criterion kind", + "in": "query", + "name": "kind", + "required": false, + "schema": { + "description": "Filter by criterion kind", + "enum": [ + "gate", + "observation", + ], + "type": "string", + }, + }, ], "responses": { "200": { diff --git a/apps/api/src/endpoints.test.ts b/apps/api/src/endpoints.test.ts index 0cabc44eb..34a89df39 100644 --- a/apps/api/src/endpoints.test.ts +++ b/apps/api/src/endpoints.test.ts @@ -192,6 +192,34 @@ describe("API Endpoints", () => { expect(res.status).toBe(400); }); + + it("creates an observation criterion with a taxonomy element", async () => { + (mocks.criteriaCollection.findOne as any).mockResolvedValue(null); + + const res = await request(app) + .post("/api/v1/criteria") + .send({ + id: "obs_crit", + prompt: "Did the agent use current deps?", + dependsOn: [], + kind: "observation", + taxonomyElementId: "dimension:dependency-currency", + }); + + expect(res.status).toBe(201); + expect(res.body).toHaveProperty("kind", "observation"); + expect(res.body).toHaveProperty("taxonomyElementId", "dimension:dependency-currency"); + }); + + it("rejects an unknown taxonomyElementId", async () => { + (mocks.criteriaCollection.findOne as any).mockResolvedValue(null); + + const res = await request(app) + .post("/api/v1/criteria") + .send({ id: "bad_tax", prompt: "x", dependsOn: [], kind: "observation", taxonomyElementId: "dimension:nope" }); + + expect(res.status).toBe(400); + }); }); describe("POST /api/v1/criteria/seed", () => { diff --git a/apps/api/src/routes/criteria.ts b/apps/api/src/routes/criteria.ts index 3d1279a9f..40aee5d0c 100644 --- a/apps/api/src/routes/criteria.ts +++ b/apps/api/src/routes/criteria.ts @@ -210,11 +210,13 @@ apiRoute(ctx.app, ctx.registry, { q: z.string().optional(), ids: z.string().optional().describe("Comma-separated criterion IDs to include"), ancestors: z.enum(["true", "false"]).optional().describe("When true and ids is set, also include dependency ancestors"), + kind: z.enum(["gate", "observation"]).optional().describe("Filter by criterion kind"), }), response: z.array(CriteriaResponseSchema), handler: async (req, res) => { const q = req.query.q; const idsParam = req.query.ids; + const kind = req.query.kind; // `q` (regex search) and `ids` (exact set + optional ancestor resolution) // are mutually exclusive: applying the regex filter first would silently @@ -231,6 +233,12 @@ apiRoute(ctx.app, ctx.registry, { { prompt: { $regex: q, $options: "i" } }, ]; } + // kind:"gate" includes legacy rows where kind is absent (backfilled to gate). + if (kind === "gate") { + filter.$and = [{ $or: [{ kind: "gate" }, { kind: { $exists: false } }] }]; + } else if (kind === "observation") { + filter.kind = "observation"; + } let criteria = await ctx.criteriaCollection.find(filter).toArray(); criteria.sort((a, b) => a.id.localeCompare(b.id)); @@ -419,9 +427,9 @@ apiRoute(ctx.app, ctx.registry, { 409: { description: "Criterion already exists" }, }, handler: async (req, res) => { - const { id, prompt, dependsOn = [], gates } = req.body; + const { id, prompt, dependsOn = [], gates, kind, taxonomyElementId } = req.body; try { - const doc = await getCriteriaStore().create({ id, prompt, dependsOn, gates }); + const doc = await getCriteriaStore().create({ id, prompt, dependsOn, gates, kind, taxonomyElementId }); res.status(201).json(doc); } catch (err) { if (!sendStoreError(res, err)) throw err; @@ -444,9 +452,9 @@ apiRoute(ctx.app, ctx.registry, { }, handler: async (req, res) => { const { id } = req.params; - const { prompt, dependsOn, gates } = req.body; + const { prompt, dependsOn, gates, kind, taxonomyElementId } = req.body; try { - const updated = await getCriteriaStore().update(id, { prompt, dependsOn, gates }); + const updated = await getCriteriaStore().update(id, { prompt, dependsOn, gates, kind, taxonomyElementId }); res.json(updated); } catch (err) { if (!sendStoreError(res, err)) throw err; diff --git a/apps/api/src/routes/requests/index.ts b/apps/api/src/routes/requests/index.ts index b6fcd4b1d..143735329 100644 --- a/apps/api/src/routes/requests/index.ts +++ b/apps/api/src/routes/requests/index.ts @@ -95,6 +95,9 @@ async function validateGatesForSubmit( if (!doc) { return `Gate '${gc.gate}' references unknown criterion '${cid}'.`; } + if ((doc.kind ?? "gate") !== "gate") { + return `Criterion '${cid}' is an observation and cannot be used as a gate criterion.`; + } if (!isCriterionCompatibleWithGate(doc.gates as GateId[] | undefined, gc.gate)) { return `Criterion '${cid}' is not compatible with the '${gc.gate}' gate.`; } @@ -122,7 +125,32 @@ async function validateGatesForSubmit( } /** - * Materialize free-text gate prompts into typed prompt entities (docs/design/ + * Validate the submit payload's observation-criteria ids: each must be an + * active kind:"observation" criterion. Gate ids are rejected. Empty/absent is + * valid (no observations evaluated). See issue #1156. + */ +async function validateObservationsForSubmit( + ctx: RouteContext, + observations: string[], +): Promise { + if (observations.length === 0) return null; + const ids = [...new Set(observations)]; + const docs = await ctx.criteriaCollection + .find({ id: { $in: ids }, deletedAt: { $exists: false } }) + .toArray(); + const byId = new Map(docs.map((c) => [c.id, c])); + for (const id of ids) { + const doc = byId.get(id); + if (!doc) return `Observation references unknown criterion '${id}'.`; + if ((doc.kind ?? "gate") !== "observation") { + return `Criterion '${id}' is a gate and cannot be used as an observation.`; + } + } + return null; +} + +/** + * Resolve free-text gate prompts into typed prompt entities before validation (see * gates.md §4.3/§4.4). For every non-Select gate that supplies `promptText`, the * text is content-addressed via `taskPromptStore.findOrCreate(text, gate)` — * idempotent and parallel to how the request task prompt is materialized — and @@ -168,7 +196,7 @@ apiRoute(ctx.app, ctx.registry, { response: z.union([RequestResponseSchema, z.array(RequestResponseSchema)]), successStatus: 201, handler: async (req, res) => { - const { scenario: scenarioObj, persona: personaObj, maxIterations, personaInstructions, count = 1, promptFeatureExtractionId, model: requestedModel, reasoningEffort: requestedReasoningEffort, mcpServers: mcpServerSlugs, skills: skillSlugs, extensions: extensionIds, agentVersion: requestedAgentVersion, profileId: requestedProfileSpec, profileVariations, priority: requestedPriority, gates: requestedGates, codebase: codebaseSpec, codebaseRevisionId: requestedCodebaseRevisionId } = req.body; + const { scenario: scenarioObj, persona: personaObj, maxIterations, personaInstructions, count = 1, promptFeatureExtractionId, model: requestedModel, reasoningEffort: requestedReasoningEffort, mcpServers: mcpServerSlugs, skills: skillSlugs, extensions: extensionIds, agentVersion: requestedAgentVersion, profileId: requestedProfileSpec, profileVariations, priority: requestedPriority, gates: requestedGates, observations: requestedObservations, codebase: codebaseSpec, codebaseRevisionId: requestedCodebaseRevisionId } = req.body; let worker = req.query.worker as string | undefined; // Resolve the optional per-run codebase selection into a concrete revision id. @@ -677,6 +705,17 @@ apiRoute(ctx.app, ctx.registry, { } } + // Validate the optional observation-criteria selection (issue #1156). + const observationsProvided = Array.isArray(requestedObservations) && requestedObservations.length > 0; + const resolvedObservations: string[] = observationsProvided ? (requestedObservations as string[]) : []; + if (observationsProvided) { + const obsError = await validateObservationsForSubmit(ctx, resolvedObservations); + if (obsError) { + res.status(400).json({ error: obsError }); + return; + } + } + // Validate count if provided if (typeof count !== "number" || count < 1 || count > 10) { res.status(400).json({ error: "count must be a number between 1 and 10" }); @@ -887,6 +926,12 @@ apiRoute(ctx.app, ctx.registry, { ) : undefined; + // Persisted observation-criteria selection (issue #1156); deduped, evaluated + // by the pp-taxonomy post-processor. Absent/empty = no observations evaluated. + const persistedObservations: string[] | undefined = observationsProvided + ? [...new Set(resolvedObservations)] + : undefined; + // Generate a submission ID to group all runs from this request const submissionId = uuidv4(); @@ -921,6 +966,7 @@ apiRoute(ctx.app, ctx.registry, { ...(profileId ? { profileId } : {}), ...(profileVersionId ? { profileVersionId } : {}), ...(persistedGates ? { gates: persistedGates } : {}), + ...(persistedObservations ? { observations: persistedObservations } : {}), submissionId, // Mint a distinct run id for the first attempt. Blob artifacts // are scoped under `{requestId}/runs/{runId}/...` so retries @@ -981,6 +1027,7 @@ apiRoute(ctx.app, ctx.registry, { ...(profileId ? { profileId } : {}), ...(profileVersionId ? { profileVersionId } : {}), ...(persistedGates ? { gates: persistedGates } : {}), + ...(persistedObservations ? { observations: persistedObservations } : {}), submissionId, // Mint a distinct run id for the first attempt. Blob artifacts // are scoped under `{requestId}/runs/{runId}/...` so retries diff --git a/apps/cli/src/__snapshots__/cli-commands.test.ts.snap b/apps/cli/src/__snapshots__/cli-commands.test.ts.snap index 065ced3aa..f22265fbc 100644 --- a/apps/cli/src/__snapshots__/cli-commands.test.ts.snap +++ b/apps/cli/src/__snapshots__/cli-commands.test.ts.snap @@ -131,7 +131,9 @@ exports[`CLI command registration > full command tree matches snapshot 1`] = ` "--depends-on", "--gates", "--id", + "--kind", "--prompt", + "--taxonomy", "--url", ], }, @@ -179,7 +181,9 @@ exports[`CLI command registration > full command tree matches snapshot 1`] = ` "--depends-on", "--gates", "--id", + "--kind", "--prompt", + "--taxonomy", "--url", ], }, @@ -661,6 +665,7 @@ exports[`CLI command registration > full command tree matches snapshot 1`] = ` "--message", "--model", "--no-stream", + "--observations", "--persona", "--profile", "--profile-variations-file", diff --git a/apps/cli/src/commands/criteria.ts b/apps/cli/src/commands/criteria.ts index 17d181422..7e890f9ac 100644 --- a/apps/cli/src/commands/criteria.ts +++ b/apps/cli/src/commands/criteria.ts @@ -46,7 +46,7 @@ criteria process.exit(1); } - const items = await response.json() as Array<{ id: string; prompt: string; dependsOn?: string[]; gates?: GateId[] }>; + const items = await response.json() as Array<{ id: string; prompt: string; dependsOn?: string[]; gates?: GateId[]; kind?: string; taxonomyElementId?: string }>; if (items.length === 0) { if (!isMachineReadable(format)) console.log(warnBanner("No criteria found.")); return; @@ -60,6 +60,7 @@ criteria { key: 'id', label: 'ID', tableFormatter: (c: any) => value(c.id), }, + { key: 'kind', label: 'Kind', formatter: (c: any) => c.kind ?? 'gate' }, { key: 'dependsOn', label: 'Deps', formatter: (c: any) => String((c.dependsOn ?? []).length) }, { key: 'gates', label: 'Gates', formatter: (c: any) => formatGateList(c.gates) }, { key: 'prompt', label: 'Prompt', tableFormatter: (c: any) => { @@ -96,6 +97,7 @@ criteria const c = await response.json() as { id: string; prompt: string; dependsOn?: string[]; gates?: GateId[]; + kind?: string; taxonomyElementId?: string; dependents: string[]; createdAt: string; updatedAt?: string; }; @@ -103,6 +105,8 @@ criteria const fields: DisplayField[] = [ { key: 'id', label: 'ID' }, { key: 'prompt', label: 'Prompt' }, + { key: 'kind', label: 'Kind', formatter: (item: any) => item.kind ?? 'gate' }, + { key: 'taxonomyElementId', label: 'Taxonomy', formatter: (item: any) => item.taxonomyElementId ?? '(none)' }, { key: 'dependsOn', label: 'Depends On', formatter: (item: any) => (item.dependsOn ?? []).join(', ') || '(none)' }, { key: 'gates', label: 'Gates', formatter: (item: any) => formatGateList(item.gates) }, { key: 'dependents', label: 'Dependents', formatter: (item: any) => (item.dependents ?? []).join(', ') || '(none)' }, @@ -124,6 +128,10 @@ criteria console.log(`${label('Depends on:')} ${dimTimestamp('(none — root criterion)')}`); } console.log(`${label('Gates:')} ${value(formatGateList(c.gates))}`); + console.log(`${label('Kind:')} ${value(c.kind ?? 'gate')}`); + if (c.taxonomyElementId) { + console.log(`${label('Taxonomy:')} ${value(c.taxonomyElementId)}`); + } if (c.dependents.length > 0) { console.log(`${label('Dependents:')} ${c.dependents.map(d => value(d)).join(', ')}`); } @@ -142,6 +150,8 @@ criteria .requiredOption("--prompt ", "Evaluation prompt for the judge") .option("-d, --depends-on ", "IDs of parent criteria") .option("--gates ", "Compatible gates (space/comma separated), or all/* for unrestricted") + .option("--kind ", "Criterion kind: gate (default) or observation") + .option("--taxonomy ", "Taxonomy element id (observation only), e.g. dimension:dependency-currency") .option("-u, --url ", "API base URL", getDefaultApiUrl()) .action(async (options) => { try { @@ -154,6 +164,8 @@ criteria } const gates = parseGateListOption(options.gates); if (gates !== undefined) body.gates = gates; + if (options.kind) body.kind = options.kind; + if (options.taxonomy) body.taxonomyElementId = options.taxonomy; const response = await fetch(`${normalizeUrl(options.url)}/api/v1/criteria`, { method: "POST", @@ -182,6 +194,8 @@ criteria .option("--prompt ", "New evaluation prompt") .option("-d, --depends-on ", "New parent criteria IDs (replaces all)") .option("--gates ", "New compatible gates (space/comma separated), or all/* for unrestricted") + .option("--kind ", "Criterion kind: gate or observation") + .option("--taxonomy ", "Taxonomy element id (observation only)") .option("-u, --url ", "API base URL", getDefaultApiUrl()) .action(async (options) => { try { @@ -190,9 +204,11 @@ criteria if (options.dependsOn !== undefined) body.dependsOn = options.dependsOn; const gates = parseGateListOption(options.gates); if (gates !== undefined) body.gates = gates; + if (options.kind) body.kind = options.kind; + if (options.taxonomy) body.taxonomyElementId = options.taxonomy; if (Object.keys(body).length === 0) { - console.error(errorText("Error: provide --prompt, --depends-on, and/or --gates")); + console.error(errorText("Error: provide --prompt, --depends-on, --gates, --kind, and/or --taxonomy")); process.exit(1); } @@ -347,7 +363,7 @@ criteria process.exit(1); } - const items = await response.json() as Array<{ id: string; prompt: string; dependsOn?: string[] }>; + const items = await response.json() as Array<{ id: string; prompt: string; dependsOn?: string[]; gates?: GateId[]; kind?: string; taxonomyElementId?: string }>; if (items.length === 0) { console.error(errorText("No criteria found to export.")); @@ -383,6 +399,15 @@ criteria if (c.dependsOn && c.dependsOn.length > 0) { doc.depends_on = c.dependsOn; } + if (c.gates && c.gates.length > 0) { + doc.gates = c.gates; + } + if (c.kind && c.kind !== 'gate') { + doc.kind = c.kind; + } + if (c.taxonomyElementId) { + doc.taxonomy_element_id = c.taxonomyElementId; + } return doc; }); @@ -435,7 +460,7 @@ criteria } // Parse all criteria from files (supports multi-document YAML) - const allCriteria: Array<{ id: string; prompt: string; dependsOn?: string[]; gates?: GateId[] }> = []; + const allCriteria: Array<{ id: string; prompt: string; dependsOn?: string[]; gates?: GateId[]; kind?: string; taxonomyElementId?: string }> = []; const parseErrors: string[] = []; for (const file of yamlFiles) { @@ -480,7 +505,8 @@ criteria const deps = (c.dependsOn ?? []).length; const depsStr = deps > 0 ? ` ${dimTimestamp(`(${deps} dep${deps > 1 ? 's' : ''})`)}` : ''; const gatesStr = c.gates ? ` ${dimTimestamp(`[${formatGateList(c.gates)}]`)}` : ''; - console.log(` ${value(c.id)}${depsStr}${gatesStr}`); + const kindStr = c.kind === 'observation' ? ` ${dimTimestamp(``)}` : ''; + console.log(` ${value(c.id)}${depsStr}${gatesStr}${kindStr}`); } if (options.dryRun) { diff --git a/apps/cli/src/commands/run.ts b/apps/cli/src/commands/run.ts index 7da9840ea..605460817 100644 --- a/apps/cli/src/commands/run.ts +++ b/apps/cli/src/commands/run.ts @@ -49,10 +49,11 @@ run .addOption(new Option("--base-profile ", "Deprecated alias for --profile.").hideHelp()) .option("--profile-variations-file ", "Path to JSON file containing profile variation entries") .option("--gates ", "GateConfig[] JSON or path/@path to a JSON file for gated runs") + .option("--observations ", "Observation criteria ids to record post-run (non-gating)") .option("-u, --url ", "API base URL", process.env.SCOPE_API_URL || "http://localhost:3100") .option("--no-stream", "Don't stream logs, just submit") .action(async (options, command) => { - const { scenario, persona, traits, worker, url, stream, maxIterations, model, reasoningEffort, mcpServers: mcpServerSlugs, skills: skillSlugs, codebase: codebaseRef, extensions: extensionIds, agentVersion, profile, baseProfile, profileVariationsFile, gates: gatesOption } = options; + const { scenario, persona, traits, worker, url, stream, maxIterations, model, reasoningEffort, mcpServers: mcpServerSlugs, skills: skillSlugs, codebase: codebaseRef, extensions: extensionIds, agentVersion, profile, baseProfile, profileVariationsFile, gates: gatesOption, observations: observationIds } = options; // `--profile` is the documented flag; `--base-profile` is kept as a hidden // back-compat alias. Both resolve to the same request `profileId`. const profileId = profile ?? baseProfile; @@ -127,6 +128,9 @@ run if (gatesOption) { body.gates = parseGatesOption(gatesOption, maxIterations); } + if (observationIds && observationIds.length > 0) { + body.observations = observationIds; + } if (profileVariationsFile) { if (!profileId) { @@ -176,6 +180,7 @@ run if (result.reasoningEffort) console.log(`${label('Reasoning Effort:')} ${value(result.reasoningEffort)}`); console.log(`${label('Mode:')} ${value(result.mode || 'one-shot')}`); if (Array.isArray(body.gates)) console.log(`${label('Gates:')} ${value(String(body.gates.length))}`); + if (Array.isArray(body.observations)) console.log(`${label('Observations:')} ${value(String(body.observations.length))}`); console.log(`${label('Status:')} ${value(result.status)}`); // Display warnings (e.g. model effort compatibility) diff --git a/apps/cli/src/run-get-action.ts b/apps/cli/src/run-get-action.ts index c3090b494..e2a9c9a8b 100644 --- a/apps/cli/src/run-get-action.ts +++ b/apps/cli/src/run-get-action.ts @@ -5,7 +5,7 @@ * Action handler for `run get` subcommand — extracted for testability. */ import { colorLevel, dimTimestamp, errorText, successText, label, value, banner, warnBanner, criterionIcon } from "./utils/style.js"; -import { GATE_METADATA, GATE_ORDER, type ConversationTurn, type GateId, type GateRunSummary, type RequestDocument } from "shared"; +import { GATE_METADATA, GATE_ORDER, TAXONOMY_ELEMENT_METADATA, type ConversationTurn, type GateId, type GateRunSummary, type RequestDocument, type TaxonomyElementId } from "shared"; import { formatData, isMachineReadable } from "./utils/formatters.js"; import type { OutputFormat, DisplayField } from "./utils/types.js"; @@ -172,6 +172,49 @@ export async function runGetAction(options: RunGetOptions): Promise { } } + // Observations (kind:"observation" criteria), grouped by taxonomy dimension. + const turnsWithObs = (rs?.turns ?? []).filter((t) => (t.observationResults?.length ?? 0) > 0); + if (turnsWithObs.length > 0) { + // Build criterionId → taxonomyElementId map from the criteria store (best effort). + const taxById = new Map(); + try { + const cr = await fetch(`${normalizeUrl(options.url)}/api/v1/criteria?kind=observation`); + if (cr.ok) { + const obs = await cr.json() as Array<{ id: string; taxonomyElementId?: TaxonomyElementId }>; + for (const o of obs) taxById.set(o.id, o.taxonomyElementId); + } + } catch { /* grouping is best-effort */ } + + // detected/evaluated tally per criterion id across iterations. + const tally = new Map(); + for (const t of turnsWithObs) { + for (const r of t.observationResults ?? []) { + const e = tally.get(r.criterionId) ?? { detected: 0, evaluated: 0 }; + e.evaluated += 1; + if (r.passed) e.detected += 1; + tally.set(r.criterionId, e); + } + } + + const byDim = new Map(); + for (const id of tally.keys()) { + const dim = taxById.get(id) ?? "unclassified"; + const arr = byDim.get(dim) ?? []; + arr.push(id); + byDim.set(dim, arr); + } + + console.log(`\n${banner('─── Observations ───')}`); + for (const [dim, ids] of byDim) { + const dimLabel = dim === "unclassified" ? "Unclassified" : (TAXONOMY_ELEMENT_METADATA[dim as TaxonomyElementId]?.label ?? dim); + console.log(` ${label(dimLabel)}`); + for (const id of ids.sort()) { + const { detected, evaluated } = tally.get(id)!; + console.log(` ${value(id)} — ${detected}/${evaluated} iterations detected`); + } + } + } + // Error if (rs?.error) { console.log(`${label('Error:')} ${errorText(rs.error)}`); diff --git a/apps/cli/src/utils/yaml-mappers.ts b/apps/cli/src/utils/yaml-mappers.ts index 04bc54fb6..cad0c23dd 100644 --- a/apps/cli/src/utils/yaml-mappers.ts +++ b/apps/cli/src/utils/yaml-mappers.ts @@ -12,7 +12,7 @@ export function mapYamlCriterion( filename: string, _docIndex: number, options: { includeGates?: boolean } = {}, -): { id: string; prompt: string; dependsOn?: string[]; gates?: GateId[] } | null { +): { id: string; prompt: string; dependsOn?: string[]; gates?: GateId[]; kind?: string; taxonomyElementId?: string } | null { const id = doc.id as string | undefined; const prompt = doc.prompt as string | undefined; if (!id || !prompt) return null; @@ -24,11 +24,18 @@ export function mapYamlCriterion( const gatesRaw = doc.gates as string | string[] | undefined; const gates = options.includeGates ? parseGateListOption(gatesRaw) : undefined; + const kindRaw = doc.kind as string | undefined; + const kind = kindRaw ? String(kindRaw).trim() : undefined; + const taxRaw = (doc.taxonomy_element_id ?? doc.taxonomyElementId) as string | undefined; + const taxonomyElementId = taxRaw ? String(taxRaw).trim() : undefined; + return { id: id.trim(), prompt: prompt.trim(), ...(dependsOn && dependsOn.length > 0 ? { dependsOn } : {}), ...(gates !== undefined ? { gates } : {}), + ...(kind ? { kind } : {}), + ...(taxonomyElementId ? { taxonomyElementId } : {}), }; } diff --git a/apps/judge/src/index.ts b/apps/judge/src/index.ts index e9718131a..0dea452cd 100644 --- a/apps/judge/src/index.ts +++ b/apps/judge/src/index.ts @@ -52,7 +52,7 @@ app.post( const startTime = Date.now(); try { - const { snapshotUrl, criteria, conversationHistory, personaInstructions, requestId, gate, toolCallsUrl } = req.body; + const { snapshotUrl, criteria, conversationHistory, personaInstructions, requestId, gate, toolCallsUrl, atifUrl } = req.body; // Validate required fields if (!snapshotUrl || typeof snapshotUrl !== "string") { @@ -106,6 +106,31 @@ app.post( } } + // Load the ATIF trajectory (normalized superset of tool calls) when + // provided — used by pp-taxonomy to evaluate observations against the + // full agent trajectory, not just the end-state snapshot. Exposed to the + // judge as a synthetic tool output so trajectory-only observations (e.g. + // a dependency added then removed mid-run) are detectable. Issue #1156. + if (atifUrl && typeof atifUrl === "string") { + try { + const atif = await blobStorage.downloadJson(atifUrl); + toolCalls = [ + ...toolCalls, + { + id: "atif-trajectory", + name: "agent_trajectory_atif", + arguments: {}, + response: typeof atif === "string" ? atif : JSON.stringify(atif), + }, + ]; + console.log(`[judge] Loaded ATIF trajectory from ${atifUrl}`); + } catch (err) { + console.warn( + `[judge] Failed to load ATIF from ${atifUrl}: ${err instanceof Error ? err.message : String(err)}`, + ); + } + } + // Build onProgress callback that publishes criterion results via Redis const onProgress = (requestId && logPublisher) ? (result: import("shared").CriterionResult) => { diff --git a/apps/workers/post-processor/handler.taxonomy.yaml b/apps/workers/post-processor/handler.taxonomy.yaml new file mode 100644 index 000000000..37411625f --- /dev/null +++ b/apps/workers/post-processor/handler.taxonomy.yaml @@ -0,0 +1,17 @@ +# Post-process handler registration metadata for the observation evaluator. +# Read by the generic register-handler script and POSTed to the +# scheduler's POST /handlers/register endpoint on deploy. +# +# pp-taxonomy records per-iteration boolean observations (kind:"observation" +# criteria) by reusing the judge. It depends on pp-atif so each turn's ATIF +# trajectory is available, giving the judge codebase (snapshot) + trajectory +# (ATIF) access. Shares the post-processor-queue with pp-atif (same worker). +# See issue #1156. +_id: pp-taxonomy +type: post-process-handler +version: 1 +queue: post-processor-queue +selector: taxonomy +autoBackfill: true +dependsOn: + - pp-atif diff --git a/apps/workers/post-processor/src/handlers/taxonomy-handler.test.ts b/apps/workers/post-processor/src/handlers/taxonomy-handler.test.ts new file mode 100644 index 000000000..18831592a --- /dev/null +++ b/apps/workers/post-processor/src/handlers/taxonomy-handler.test.ts @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { JudgeInfrastructureError, type JudgeClient } from "shared"; +import { TaxonomyHandler } from "./taxonomy-handler.js"; +import type { HandlerContext, PostProcessorMessage } from "../types.js"; + +function makeCtx(doc: unknown): HandlerContext & { collection: { updateOne: ReturnType } } { + return { + blobStorage: {} as any, + collection: { + findOne: vi.fn().mockResolvedValue(doc), + updateOne: vi.fn().mockResolvedValue({ modifiedCount: 1 }), + } as any, + log: vi.fn().mockResolvedValue(undefined), + } as any; +} + +const msg: PostProcessorMessage = { type: "taxonomy", requestId: "req-1", runId: "run-1" }; + +describe("TaxonomyHandler", () => { + let judge: { evaluate: ReturnType }; + + beforeEach(() => { + judge = { evaluate: vi.fn() }; + }); + + it("has type 'taxonomy'", () => { + expect(new TaxonomyHandler(judge as unknown as JudgeClient).type).toBe("taxonomy"); + }); + + it("no-ops when no observations are selected", async () => { + const ctx = makeCtx({ _id: "req-1", run: { observations: [], turns: [{ iteration: 1, snapshotUrl: "s://1" }] } }); + await new TaxonomyHandler(judge as unknown as JudgeClient).process(msg, ctx); + expect(judge.evaluate).not.toHaveBeenCalled(); + expect(ctx.collection.updateOne).not.toHaveBeenCalled(); + }); + + it("writes judge criteriaResults to each turn's observationResults and sends atifUrl", async () => { + judge.evaluate.mockResolvedValue({ + passed: true, + feedback: "ok", + criteriaResults: [{ criterionId: "dep_removed", passed: true, feedback: "left-pad removed", evaluated: true }], + }); + const ctx = makeCtx({ + _id: "req-1", + run: { + observations: ["dep_removed"], + turns: [{ iteration: 1, snapshotUrl: "s://1", atifUrl: "a://1" }], + }, + }); + + await new TaxonomyHandler(judge as unknown as JudgeClient).process(msg, ctx); + + expect(judge.evaluate).toHaveBeenCalledWith( + expect.objectContaining({ snapshotUrl: "s://1", criteria: ["dep_removed"], atifUrl: "a://1" }), + ); + const call = judge.evaluate.mock.calls[0][0]; + expect(call.gate).toBeUndefined(); + expect(call.toolCallsUrl).toBeUndefined(); + expect(ctx.collection.updateOne).toHaveBeenCalledWith( + { _id: "req-1", "run.turns.iteration": 1 }, + { $set: { "run.turns.$.observationResults": [{ criterionId: "dep_removed", passed: true, feedback: "left-pad removed", evaluated: true }] } }, + ); + }); + + it("skips iterations without a snapshotUrl", async () => { + judge.evaluate.mockResolvedValue({ passed: true, feedback: "", criteriaResults: [] }); + const ctx = makeCtx({ _id: "req-1", run: { observations: ["c1"], turns: [{ iteration: 1 }] } }); + await new TaxonomyHandler(judge as unknown as JudgeClient).process(msg, ctx); + expect(judge.evaluate).not.toHaveBeenCalled(); + }); + + it("throws on judge infrastructure error so the handler is marked failed", async () => { + judge.evaluate.mockRejectedValue(new JudgeInfrastructureError("down", { httpStatus: 503 })); + const ctx = makeCtx({ _id: "req-1", run: { observations: ["c1"], turns: [{ iteration: 1, snapshotUrl: "s://1" }] } }); + await expect(new TaxonomyHandler(judge as unknown as JudgeClient).process(msg, ctx)).rejects.toThrow("down"); + }); +}); diff --git a/apps/workers/post-processor/src/handlers/taxonomy-handler.ts b/apps/workers/post-processor/src/handlers/taxonomy-handler.ts new file mode 100644 index 000000000..3701c4cd8 --- /dev/null +++ b/apps/workers/post-processor/src/handlers/taxonomy-handler.ts @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { JudgeClient, isRetryableJudgeError } from "shared"; +import type { ConversationTurn, CriterionResult } from "shared"; +import type { PostProcessHandler, PostProcessorMessage, HandlerContext } from "../types.js"; + +/** Minimal shape of the run document fields this handler reads/writes. */ +interface RunDoc { + run?: { + _id?: string; + observations?: string[]; + turns?: ConversationTurn[]; + }; +} + +/** + * Taxonomy Handler (pp-taxonomy): records per-iteration boolean observations. + * + * For each iteration turn with a `snapshotUrl`, reuses the judge service to + * evaluate the run's selected observation criteria (`run.observations`) against + * the codebase snapshot AND the agent trajectory (ATIF) — sending `atifUrl` in + * place of `toolCallsUrl`. Results are written to `turn.observationResults`, + * mirroring gate `criteriaResults`. Never gates, never steers the agent. + * Empty/absent `observations` → no-op. See issue #1156. + */ +export class TaxonomyHandler implements PostProcessHandler { + readonly type = "taxonomy"; + private readonly judge: JudgeClient; + + constructor(judge?: JudgeClient, judgeUrl = process.env.JUDGE_URL || process.env.JUDGE_SERVICE_URL || "http://localhost:3002") { + this.judge = judge ?? new JudgeClient(judgeUrl); + } + + async process(message: PostProcessorMessage, ctx: HandlerContext): Promise { + const { requestId, iteration } = message; + + const doc = (await ctx.collection.findOne({ _id: requestId } as any)) as RunDoc | null; + const observations = doc?.run?.observations ?? []; + const turns = doc?.run?.turns ?? []; + + if (observations.length === 0) { + await ctx.log("info", "No observations selected, skipping taxonomy evaluation"); + return; + } + if (turns.length === 0) { + await ctx.log("info", "No turns found, skipping taxonomy evaluation"); + return; + } + + const turnsToProcess = iteration ? turns.filter((t) => t.iteration === iteration) : turns; + let processedCount = 0; + + for (const turn of turnsToProcess) { + if (!turn.snapshotUrl) { + await ctx.log("info", `Iteration ${turn.iteration}: no snapshot, skipping`); + continue; + } + + try { + const result = await this.judge.evaluate({ + snapshotUrl: turn.snapshotUrl, + criteria: observations, + conversationHistory: turns, + ...(turn.atifUrl ? { atifUrl: turn.atifUrl } : {}), + requestId, + }); + + const observationResults: CriterionResult[] = result.criteriaResults ?? []; + + await ctx.collection.updateOne( + { _id: requestId, "run.turns.iteration": turn.iteration } as any, + { $set: { "run.turns.$.observationResults": observationResults } } as any, + ); + + processedCount++; + await ctx.log("info", `Iteration ${turn.iteration}: ${observationResults.length} observations recorded`); + } catch (err) { + const errMsg = err instanceof Error ? err.message : String(err); + if (isRetryableJudgeError(err)) { + await ctx.log("error", `Iteration ${turn.iteration}: judge infrastructure error, failing handler: ${errMsg}`); + throw err; + } + await ctx.log("warn", `Iteration ${turn.iteration}: observation evaluation failed: ${errMsg}`); + } + } + + await ctx.log("info", `Taxonomy evaluation complete: ${processedCount}/${turnsToProcess.length} iterations processed`); + } +} diff --git a/apps/workers/post-processor/src/index.ts b/apps/workers/post-processor/src/index.ts index b6b6ce3c9..c6a756cfb 100644 --- a/apps/workers/post-processor/src/index.ts +++ b/apps/workers/post-processor/src/index.ts @@ -4,6 +4,7 @@ import "dotenv/config"; import { PostProcessor, type PostProcessorConfig } from "./post-processor.js"; import { AtifHandler } from "./handlers/atif-handler.js"; +import { TaxonomyHandler } from "./handlers/taxonomy-handler.js"; const config: PostProcessorConfig = { mongoUri: process.env.MONGO_CONNECTION_STRING || process.env.AZURE_COSMOS_CONNECTION_STRING || "mongodb://localhost:27017", @@ -24,6 +25,7 @@ const processor = new PostProcessor(config); // Register handlers processor.registerHandler(new AtifHandler()); +processor.registerHandler(new TaxonomyHandler()); processor.start().catch((err) => { console.error("[post-processor] Fatal error:", err); diff --git a/config/criteria/auth_configured_correctly.yaml b/config/criteria/auth_configured_correctly.yaml new file mode 100644 index 000000000..8c4b62410 --- /dev/null +++ b/config/criteria/auth_configured_correctly.yaml @@ -0,0 +1,8 @@ +id: auth_configured_correctly +prompt: | + Authentication, connection, environment, and deployment settings are + configured properly (e.g. credentials/connection strings sourced from + environment or secret stores, correct endpoints, no hard-coded secrets, valid + deployment configuration). +kind: observation +taxonomy_element_id: dimension:configuration-correctness diff --git a/config/criteria/dependency_added_then_removed.yaml b/config/criteria/dependency_added_then_removed.yaml new file mode 100644 index 000000000..1706e1e64 --- /dev/null +++ b/config/criteria/dependency_added_then_removed.yaml @@ -0,0 +1,9 @@ +id: dependency_added_then_removed +prompt: | + During the run the agent installed a package and later uninstalled or removed + it before finishing (e.g. added left-pad then removed it). This is only + derivable from the agent's trajectory (mid-run tool calls), not from the final + codebase snapshot, because the dependency is absent in the end state. Inspect + the trajectory of tool calls to detect a transient add-then-remove. +kind: observation +taxonomy_element_id: dimension:dependency-currency diff --git a/config/criteria/idiomatic_api_usage.yaml b/config/criteria/idiomatic_api_usage.yaml new file mode 100644 index 000000000..13ec3e949 --- /dev/null +++ b/config/criteria/idiomatic_api_usage.yaml @@ -0,0 +1,8 @@ +id: idiomatic_api_usage +prompt: | + The agent used the product's recommended patterns and best practices when + calling its APIs (idiomatic usage), rather than working around them or using + deprecated/low-level approaches. Judge the quality of HOW the product is used, + not whether it is used at all. +kind: observation +taxonomy_element_id: dimension:idiomatic-use diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml index daa4d9c9f..fe8c064ad 100644 --- a/docker-compose.dev.yml +++ b/docker-compose.dev.yml @@ -184,6 +184,10 @@ services: build: target: dev + register-handler-taxonomy: + build: + target: dev + post-processor: build: target: dev diff --git a/docker-compose.yml b/docker-compose.yml index 0bbc99234..aea2d76f7 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -659,6 +659,23 @@ services: restart: "no" entrypoint: ["npx", "tsx", "packages/shared/src/scripts/register-handler.ts"] + # Registers the pp-taxonomy handler (observation evaluator) — shares the + # post-processor worker + post-processor-queue, depends on pp-atif. Issue #1156. + register-handler-taxonomy: + build: + context: . + dockerfile: apps/workers/post-processor/Dockerfile + profiles: [post-processor] + environment: + <<: *common-env + HANDLER_YAML_PATH: apps/workers/post-processor/handler.taxonomy.yaml + SCHEDULER_URL: http://scheduler:8080 + depends_on: + scheduler: + condition: service_started + restart: "no" + entrypoint: ["npx", "tsx", "packages/shared/src/scripts/register-handler.ts"] + post-processor: build: context: . @@ -681,6 +698,8 @@ services: condition: service_started register-handler-post-processor: condition: service_completed_successfully + register-handler-taxonomy: + condition: service_completed_successfully volumes: mongodb_data: diff --git a/docs/architecture/app-design.md b/docs/architecture/app-design.md index a5babb604..6f1b528a7 100644 --- a/docs/architecture/app-design.md +++ b/docs/architecture/app-design.md @@ -115,7 +115,7 @@ Currently all versions of an agent share a single queue (e.g., `queue-coder-acp- ### Run submission flow -1. User submits via Portal or CLI with: **task**, **criteria** (required), **worker**, **model** (required), and optionally **agentVersion**, a **codebase** selection, and/or a per-gate **`gates`** configuration (see [Gates](#gates--multi-phase-evaluation-pipeline)) +1. User submits via Portal or CLI with: **task**, **criteria** (required), **worker**, **model** (required), and optionally **agentVersion**, a **codebase** selection, record-only **`observations`** criteria, and/or a per-gate **`gates`** configuration (see [Gates](#gates--multi-phase-evaluation-pipeline)) 2. API resolves `agentVersion`: explicit selection → validate active; omitted → latest active by `createdAt` 3. API resolves `model`: explicit → validate against `supportedModels`; omitted → `defaultModel` 4. API looks up `AgentVersion.queueName` and routes message to that queue @@ -146,6 +146,11 @@ Criteria are reusable evaluation rules stored in the database and optionally def - **AI-generated prompts** — natural language behavior descriptions can be converted to evaluation prompts via LLM - **Traits** — reusable labels for filtering and composition (e.g., `has_azure`, `has_node`) - **Gate compatibility** — a `gates: GateId[]` list controls which [gates](#gates--multi-phase-evaluation-pipeline) a criterion may be selected for (empty = all); the list is downward-closed along the DAG +- **Criterion kind** — `kind: "gate" | "observation"` distinguishes criteria that gate the agent from record-only observations. Observation criteria can optionally set `taxonomyElementId` to one of the hard-coded observation dimensions; run detail derives dimension grouping by joining each per-turn `observationResults[].criterionId` back to the criterion metadata. +- **Kind** — `kind: "gate" | "observation"` (default `gate`). **Gate** criteria steer the coding agent through the gate DAG. **Observation** criteria (issue #1156) are record-only: they produce a boolean + evidence per iteration, never feed back to the agent, never pass/fail a gate, and never enter the gate DAG. Dependencies may only reference same-kind criteria. +- **Taxonomy classification** — observation criteria carry an optional `taxonomyElementId` from a hard-coded enum of the three R&A Readout quality dimensions (`dimension:idiomatic-use`, `dimension:dependency-currency`, `dimension:configuration-correctness`). Classification is static/design-time, not per-run. + +Observation evaluation happens off the coding-agent critical path in the `pp-taxonomy` post-processor (see [post-processing](post-processing.md)). A run carries the chosen `observations: string[]` (observation-criteria ids); each evaluated turn stores `observationResults: CriterionResult[]` (same shape as gate `criteriaResults`). Dimension grouping is derived at read time by joining `criterionId` → criterion `taxonomyElementId`. See [`ENV_VARIABLES.md`](../../scope-mt-app/ENV_VARIABLES.md) for related configuration options. diff --git a/docs/architecture/criteria-provider.md b/docs/architecture/criteria-provider.md index de2fc8284..08e623fbb 100644 --- a/docs/architecture/criteria-provider.md +++ b/docs/architecture/criteria-provider.md @@ -160,6 +160,10 @@ bypassed or drift between callers: - **Gate-compatibility invariant** — enforced from both sides: a child's gates must be a subset of every parent's gates, and narrowing a parent may not strand an existing dependent. +- **Same-kind dependency partition** — a criterion's `dependsOn` may only reference + criteria of the same `kind`. This keeps the gate DAG closed under + `resolveWithAncestors` (observations never leak into a gate's evaluation set) and + lets `kind:"observation"` criteria form their own optional dependency chains. - **Referential integrity on delete** — deleting a criterion that still has dependents is rejected. diff --git a/docs/architecture/overview.md b/docs/architecture/overview.md index 9eb7cafbe..ea118f342 100644 --- a/docs/architecture/overview.md +++ b/docs/architecture/overview.md @@ -80,6 +80,7 @@ flowchart TB | `workers/coder-acp-claude-code` | Claude Code agent via Agent Client Protocol (ACP) | | `workers/coder-acp-copilot` | GitHub Copilot agent via Agent Client Protocol (ACP) | | `workers/report-generator` | Copilot SDK worker that generates post-run markdown reports | +| `workers/post-processor` | DAG-based post-run handlers: `pp-atif` (trajectory ATIF) and `pp-taxonomy` (per-iteration boolean observations via the judge) | | `gateway` | AI Gateway — shared Rust TLS-intercepting proxy with plugin architecture (HAR capture, future: token refresh, rate limiting) | ## Data Flow diff --git a/docs/architecture/post-processing.md b/docs/architecture/post-processing.md index 910812ac0..baeed6e44 100644 --- a/docs/architecture/post-processing.md +++ b/docs/architecture/post-processing.md @@ -56,6 +56,24 @@ Two paths trigger post-processing: The `iteration` query parameter is mandatory for the ATIF endpoints. ATIF files are also included in archive exports as `iteration-{N}.atif.trajectory.json`. +## Taxonomy Observations (`pp-taxonomy`) + +The `pp-taxonomy` handler records **observation criteria** — per-iteration boolean +outcomes + evidence about the codebase and the agent's trajectory, **without gating +or steering** the coding agent (issue #1156). It is a DAG node `dependsOn: [pp-atif]`, +because some observations are only derivable from the trajectory (ATIF), not the +final snapshot. + +### Flow + +1. Reads the run's `observations: string[]` (observation-criteria ids chosen at submit). Empty/absent ⇒ no-op, handler `done`. +2. For each iteration with a `snapshotUrl`, calls the existing judge via the shared `JudgeClient` (`POST /api/v1/evaluate`) with `snapshotUrl` + `atifUrl` + the observation-criteria ids — no persona, no gate, no taxonomyElementId (the classifier lives on the criterion). ATIF supersedes per-turn `toolCallsUrl`, so only ATIF is sent. +3. Writes the returned per-criterion `{criterionId, passed, feedback}` to that turn's **`observationResults`** — same shape/storage as gate `criteriaResults`. No new blob, no `run.taxonomyUrl`. +4. Stamps `run.handlerStatus["pp-taxonomy"] = { status: "done", version: N }` and notifies the scheduler. + +Dimension grouping is **derived at read time** by joining each result's `criterionId` → criterion `taxonomyElementId` (the three R&A Readout dimensions; unset = unclassified). It never feeds back to the agent and never affects pass/fail. (#1053 later extends this worker with a richer scorecard artifact.) + + ## Handler Interface The post-processor uses a registry pattern for extensibility: @@ -85,6 +103,7 @@ Handlers are registered at startup in `index.ts`: ```typescript const processor = new PostProcessor(config); processor.registerHandler(new AtifHandler()); +processor.registerHandler(new TaxonomyHandler()); processor.start(); ``` @@ -140,7 +159,7 @@ flowchart LR **Where it runs:** - **Docker Compose:** one `register-handler-` init service per handler (e.g. `pp-atif`) runs the generic script via `tsx`, gated on the scheduler being up. The worker waits for its registration service to complete. -- **Kubernetes:** a `register-handler-post-processor` Job runs the compiled script (`node packages/shared/dist/scripts/register-handler.js`) on each deploy. Only `pp-atif` is registered in K8s today because it is the only post-process handler deployed to the cluster. The scheduler exposes a `Service` (`scheduler.scoped.svc.cluster.local:8080`) so Jobs and workers can reach `/handlers/register` and the notify endpoints. +- **Kubernetes:** a `register-handler-post-processor` Job runs the compiled script (`node packages/shared/dist/scripts/register-handler.js`) on each deploy. `pp-atif` and `pp-taxonomy` are registered in K8s via their respective registration Jobs (`register-handler-taxonomy` points its `HANDLER_YAML_PATH` at `handler.taxonomy.yaml`). The scheduler exposes a `Service` (`scheduler.scoped.svc.cluster.local:8080`) so Jobs and workers can reach `/handlers/register` and the notify endpoints. To **add or change a handler**, edit its `handler.yaml` (bump `version`, adjust `dependsOn`, etc.) — no code or migration changes are needed for registration. diff --git a/packages/db-migrations/src/migrations/021-backfill-criteria-kind.ts b/packages/db-migrations/src/migrations/021-backfill-criteria-kind.ts new file mode 100644 index 000000000..743d9a38d --- /dev/null +++ b/packages/db-migrations/src/migrations/021-backfill-criteria-kind.ts @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * Migration: Backfill criteria kind. + * + * The observation-criteria feature (issue #1156) introduces a `kind` field on + * criteria — `"gate"` (default) gates the coding-agent session via the DAG, + * while `"observation"` is record-only. To preserve existing behaviour every + * legacy criterion must be a gate, so we backfill rows whose `kind` field is + * absent or null with `"gate"`. Mirrors 018-backfill-criteria-gates.ts. + * + * down() reverses only the rows this migration set to exactly "gate", + * unsetting the field to restore the pre-migration state. + */ + +import type { Db } from "mongodb"; +import type { MigrationInterface } from "mongo-migrate-ts"; +import { batchUpdate } from "../batch-update.js"; + +export class BackfillCriteriaKind implements MigrationInterface { + async up(db: Db): Promise { + const criteria = db.collection("criteria"); + + const count = await batchUpdate( + criteria, + { $or: [{ kind: { $exists: false } }, { kind: null }] }, + { $set: { kind: "gate" } }, + "[021] backfill criteria.kind=gate", + ); + + console.log(`[021] Backfilled kind=gate on ${count} criteria`); + } + + async down(db: Db): Promise { + const criteria = db.collection("criteria"); + + const count = await batchUpdate( + criteria, + { kind: "gate" }, + { $unset: { kind: "" } }, + "[021-down] unset criteria.kind", + ); + + console.log(`[021-down] Unset kind on ${count} criteria`); + } +} diff --git a/packages/db-migrations/src/required-migrations.ts b/packages/db-migrations/src/required-migrations.ts index e6d8e82ae..f5742e603 100644 --- a/packages/db-migrations/src/required-migrations.ts +++ b/packages/db-migrations/src/required-migrations.ts @@ -36,4 +36,5 @@ export const REQUIRED_MIGRATIONS: readonly string[] = [ "019-backfill-task-prompt-type.ts", "020-backfill-handler-status.ts", "020-create-codebase-indexes.ts", + "021-backfill-criteria-kind.ts", ]; diff --git a/packages/shared/src/criteria/criteria-provider-api.ts b/packages/shared/src/criteria/criteria-provider-api.ts index f66c6cc70..080dd1c9e 100644 --- a/packages/shared/src/criteria/criteria-provider-api.ts +++ b/packages/shared/src/criteria/criteria-provider-api.ts @@ -203,10 +203,14 @@ export class RestApiCriteriaProvider implements CriteriaProvider { function mapToCriteriaConfig(data: Record): CriteriaConfig { const dependsOn = (data.dependsOn as string[] | undefined) ?? []; const gates = data.gates as CriteriaConfig["gates"] | undefined; + const kind = data.kind as CriteriaConfig["kind"] | undefined; + const taxonomyElementId = data.taxonomyElementId as CriteriaConfig["taxonomyElementId"] | undefined; return { id: String(data.id), prompt: String(data.prompt), dependsOn: dependsOn.length > 0 ? dependsOn : undefined, ...(gates && gates.length > 0 ? { gates } : {}), + ...(kind ? { kind } : {}), + ...(taxonomyElementId ? { taxonomyElementId } : {}), }; } diff --git a/packages/shared/src/criteria/criteria-provider-fs.ts b/packages/shared/src/criteria/criteria-provider-fs.ts index 9922327ea..9c5042700 100644 --- a/packages/shared/src/criteria/criteria-provider-fs.ts +++ b/packages/shared/src/criteria/criteria-provider-fs.ts @@ -68,6 +68,19 @@ export class FileSystemCriteriaProvider implements CriteriaProvider { criteria.gates = gates.map((g: any) => String(g).trim()) as CriteriaConfig["gates"]; } + const kind = data.kind; + if (kind !== undefined) { + if (kind !== "gate" && kind !== "observation") { + throw new Error(`'kind' must be 'gate' or 'observation' in ${file}`); + } + criteria.kind = kind; + } + + const taxonomyElementId = data.taxonomy_element_id || data.taxonomyElementId; + if (taxonomyElementId !== undefined) { + criteria.taxonomyElementId = String(taxonomyElementId).trim() as CriteriaConfig["taxonomyElementId"]; + } + if (this.registry.has(criteria.id)) { throw new Error(`Duplicate criteria id '${criteria.id}' found in ${file}`); } diff --git a/packages/shared/src/criteria/criteria-store.test.ts b/packages/shared/src/criteria/criteria-store.test.ts index ce6c7645e..07908886e 100644 --- a/packages/shared/src/criteria/criteria-store.test.ts +++ b/packages/shared/src/criteria/criteria-store.test.ts @@ -311,3 +311,62 @@ describe("CriteriaStore revives soft-deleted ids on re-create", () => { }); }); + +describe("CriteriaStore kind + taxonomy (issue #1156)", () => { + it("defaults kind to 'gate' on create when absent", async () => { + const store = new CriteriaStore(fakeCollection()); + const created = await store.create({ id: "g1", prompt: "p" }); + expect(created.kind).toBe("gate"); + expect(created.taxonomyElementId).toBeUndefined(); + }); + + it("persists kind:'observation' + taxonomyElementId", async () => { + const store = new CriteriaStore(fakeCollection()); + const created = await store.create({ + id: "obs1", + prompt: "p", + kind: "observation", + taxonomyElementId: "dimension:idiomatic-use", + }); + expect(created.kind).toBe("observation"); + expect(created.taxonomyElementId).toBe("dimension:idiomatic-use"); + }); + + it("rejects taxonomyElementId on a gate criterion", async () => { + const store = new CriteriaStore(fakeCollection()); + await expect( + store.create({ id: "g2", prompt: "p", kind: "gate", taxonomyElementId: "dimension:idiomatic-use" }), + ).rejects.toThrow(CriteriaValidationError); + }); + + it("rejects a gate depending on an observation (same-kind rule)", async () => { + const col = fakeCollection([ + { id: "obs", prompt: "o", dependsOn: [], kind: "observation", createdAt: new Date() }, + ]); + const store = new CriteriaStore(col); + await expect( + store.create({ id: "g3", prompt: "p", kind: "gate", dependsOn: ["obs"] }), + ).rejects.toThrow(CriteriaValidationError); + }); + + it("allows an observation depending on an observation", async () => { + const col = fakeCollection([ + { id: "obs_parent", prompt: "o", dependsOn: [], kind: "observation", createdAt: new Date() }, + ]); + const store = new CriteriaStore(col); + await expect( + store.create({ id: "obs_child", prompt: "c", kind: "observation", dependsOn: ["obs_parent"] }), + ).resolves.toBeTruthy(); + }); + + it("resolveObservations accepts observation ids and rejects gate ids", async () => { + const col = fakeCollection([ + { id: "obs", prompt: "o", dependsOn: [], kind: "observation", createdAt: new Date() }, + { id: "gate", prompt: "g", dependsOn: [], kind: "gate", createdAt: new Date() }, + ]); + const store = new CriteriaStore(col); + const resolved = await store.resolveObservations(["obs"]); + expect(resolved.map((c) => c.id)).toEqual(["obs"]); + await expect(store.resolveObservations(["gate"])).rejects.toThrow(CriteriaValidationError); + }); +}); diff --git a/packages/shared/src/criteria/criteria-store.ts b/packages/shared/src/criteria/criteria-store.ts index 34893c7cb..de51748df 100644 --- a/packages/shared/src/criteria/criteria-store.ts +++ b/packages/shared/src/criteria/criteria-store.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. import { Collection } from 'mongodb'; -import { CriteriaConfig, CriteriaDocument, GateId } from '../types/types.js'; +import { CriteriaConfig, CriteriaDocument, CriterionKind, GateId, TaxonomyElementId } from '../types/types.js'; import { DependencyGraph } from '../graph/dependency-graph.js'; import { gatesSatisfyInvariant } from '../gates/gates.js'; import { @@ -40,8 +40,11 @@ export class CriteriaStore { prompt: string; dependsOn?: string[]; gates?: GateId[]; + kind?: CriterionKind; + taxonomyElementId?: TaxonomyElementId; }): Promise { - const { id, prompt, dependsOn = [], gates } = input; + const { id, prompt, dependsOn = [], gates, taxonomyElementId } = input; + const kind: CriterionKind = input.kind ?? 'gate'; // Validate ID format if (!/^[a-z][a-z0-9_]*$/.test(id)) { @@ -50,6 +53,13 @@ export class CriteriaStore { ); } + // taxonomyElementId only applies to observation criteria. + if (taxonomyElementId !== undefined && kind !== 'observation') { + throw new CriteriaValidationError( + `taxonomyElementId can only be set on observation criteria (got kind '${kind}')` + ); + } + // Check for duplicates among *active* criteria. const existing = await this.collection.findOne({ id, deletedAt: { $exists: false } }); if (existing) { @@ -72,6 +82,11 @@ export class CriteriaStore { await this.validateNoCycles(id, dependsOn); } + // Validate same-kind dependencies (gate↔gate, observation↔observation). + if (dependsOn.length > 0) { + await this.validateSameKindDependencies(id, dependsOn, kind); + } + // Validate the downward-closed gate-compatibility invariant. await this.validateGateCompatibility(id, dependsOn, gates); @@ -80,6 +95,8 @@ export class CriteriaStore { prompt: prompt.trim(), dependsOn, ...(gates !== undefined && { gates }), + kind, + ...(taxonomyElementId !== undefined && { taxonomyElementId }), createdAt: new Date(), }; @@ -121,7 +138,7 @@ export class CriteriaStore { /** Update a criterion's prompt, dependencies and/or gate compatibility */ async update( id: string, - patch: { prompt?: string; dependsOn?: string[]; gates?: GateId[] } + patch: { prompt?: string; dependsOn?: string[]; gates?: GateId[]; kind?: CriterionKind; taxonomyElementId?: TaxonomyElementId } ): Promise { const existing = await this.get(id); if (!existing) { @@ -147,10 +164,28 @@ export class CriteriaStore { await this.validateDependentsRemainCompatible(id, effectiveGates); } + // Validate same-kind dependencies against the resulting kind + dependsOn. + const effectiveKind: CriterionKind = patch.kind ?? existing.kind ?? 'gate'; + const resultingDependsOn = patch.dependsOn ?? existing.dependsOn ?? []; + if (resultingDependsOn.length > 0) { + await this.validateSameKindDependencies(id, resultingDependsOn, effectiveKind); + } + + // taxonomyElementId only applies to observation criteria. + const effectiveTaxonomy = + patch.taxonomyElementId !== undefined ? patch.taxonomyElementId : existing.taxonomyElementId; + if (effectiveTaxonomy !== undefined && effectiveKind !== 'observation') { + throw new CriteriaValidationError( + `taxonomyElementId can only be set on observation criteria (got kind '${effectiveKind}')` + ); + } + const update: Record = { updatedAt: new Date() }; if (patch.prompt !== undefined) update.prompt = patch.prompt.trim(); if (patch.dependsOn !== undefined) update.dependsOn = patch.dependsOn; if (patch.gates !== undefined) update.gates = patch.gates; + if (patch.kind !== undefined) update.kind = patch.kind; + if (patch.taxonomyElementId !== undefined) update.taxonomyElementId = patch.taxonomyElementId; await this.collection.updateOne( { id, deletedAt: { $exists: false } }, @@ -213,7 +248,14 @@ export class CriteriaStore { ); } - collected.set(id, { id: doc.id, prompt: doc.prompt, dependsOn: doc.dependsOn, ...(doc.gates !== undefined && { gates: doc.gates }) }); + collected.set(id, { + id: doc.id, + prompt: doc.prompt, + dependsOn: doc.dependsOn, + ...(doc.gates !== undefined && { gates: doc.gates }), + ...(doc.kind !== undefined && { kind: doc.kind }), + ...(doc.taxonomyElementId !== undefined && { taxonomyElementId: doc.taxonomyElementId }), + }); if (doc.dependsOn) { for (const parentId of doc.dependsOn) { @@ -240,6 +282,8 @@ export class CriteriaStore { prompt: c.prompt, dependsOn: c.dependsOn, ...(c.gates !== undefined && { gates: c.gates }), + ...(c.kind !== undefined && { kind: c.kind }), + ...(c.taxonomyElementId !== undefined && { taxonomyElementId: c.taxonomyElementId }), })); const edges: { from: string; to: string }[] = []; @@ -268,6 +312,8 @@ export class CriteriaStore { prompt: config.prompt, dependsOn: config.dependsOn || [], ...(config.gates !== undefined && { gates: config.gates }), + kind: config.kind ?? 'gate', + ...(config.taxonomyElementId !== undefined && { taxonomyElementId: config.taxonomyElementId }), createdAt: new Date(), } as any); inserted++; @@ -288,6 +334,52 @@ export class CriteriaStore { } } + /** + * Validate that every dependency shares the criterion's kind. Keeps the gate + * DAG closed under resolveWithAncestors and lets observation criteria form + * their own dependency chains. Missing parents are caught by + * validateDependencies, so they are skipped here. See issue #1156. + */ + private async validateSameKindDependencies( + criterionId: string, + dependsOn: string[], + kind: CriterionKind, + ): Promise { + for (const parentId of dependsOn) { + const parent = await this.get(parentId); + if (!parent) continue; + const parentKind = parent.kind ?? 'gate'; + if (parentKind !== kind) { + throw new CriteriaValidationError( + `'${criterionId}' (kind '${kind}') cannot depend on '${parentId}' (kind '${parentKind}'). ` + + `A criterion may only depend on same-kind criteria.`, + ); + } + } + } + + /** + * Resolve observation-criteria ids, asserting each is an active + * kind:"observation" criterion. Used by submit validation + pp-taxonomy. + * Throws CriteriaValidationError on a missing or non-observation id. + */ + async resolveObservations(ids: string[]): Promise { + const resolved: CriteriaDocument[] = []; + for (const id of ids) { + const doc = await this.get(id); + if (!doc) { + throw new CriteriaValidationError(`Observation criterion '${id}' does not exist`); + } + if ((doc.kind ?? 'gate') !== 'observation') { + throw new CriteriaValidationError( + `Criterion '${id}' is not an observation (kind '${doc.kind ?? 'gate'}')` + ); + } + resolved.push(doc); + } + return resolved; + } + /** Validate that adding edges would not introduce a cycle */ private async validateNoCycles( criterionId: string, diff --git a/packages/shared/src/criteria/index.ts b/packages/shared/src/criteria/index.ts index 4cca92abd..413c36636 100644 --- a/packages/shared/src/criteria/index.ts +++ b/packages/shared/src/criteria/index.ts @@ -7,3 +7,4 @@ export * from "./criteria-provider.js"; export * from "./criteria-provider-fs.js"; export * from "./criteria-provider-api.js"; export * from "./criteria-provider-factory.js"; +export * from "./observation-taxonomy.js"; diff --git a/packages/shared/src/criteria/observation-taxonomy.ts b/packages/shared/src/criteria/observation-taxonomy.ts new file mode 100644 index 000000000..3781e36c6 --- /dev/null +++ b/packages/shared/src/criteria/observation-taxonomy.ts @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { + TAXONOMY_ELEMENT_IDS, + TaxonomyElementId, + isTaxonomyElementId, +} from "../types/types.js"; + +/** Re-export the hard-coded taxonomy constants from the shared barrel. */ +export { TAXONOMY_ELEMENT_IDS, isTaxonomyElementId }; +export type { TaxonomyElementId }; + +/** Static, human-facing metadata for a taxonomy element. */ +export interface TaxonomyElementMetadata { + id: TaxonomyElementId; + label: string; + description: string; +} + +/** + * Hard-coded metadata for every observation taxonomy element, keyed by id — + * the three quality dimensions from the R&A Readout design. See issue #1156. + */ +export const TAXONOMY_ELEMENT_METADATA: Record = { + "dimension:idiomatic-use": { + id: "dimension:idiomatic-use", + label: "Idiomatic use", + description: + "Did the agent follow the product's recommended patterns and best practices " + + "(quality of how the product is used, not whether it is used at all)?", + }, + "dimension:dependency-currency": { + id: "dimension:dependency-currency", + label: "Dependency currency", + description: "Did the agent use current versions, packages, and namespaces?", + }, + "dimension:configuration-correctness": { + id: "dimension:configuration-correctness", + label: "Configuration correctness", + description: "Are auth, connection, environment, and deployment settings configured properly?", + }, +}; diff --git a/packages/shared/src/judge/judge-client.ts b/packages/shared/src/judge/judge-client.ts index f94e3c856..c07cfa82f 100644 --- a/packages/shared/src/judge/judge-client.ts +++ b/packages/shared/src/judge/judge-client.ts @@ -17,6 +17,10 @@ export interface JudgeEvaluateRequest { gate?: GateId; /** Blob URL of this iteration's captured tool calls/outputs (build/test/run output). */ toolCallsUrl?: string; + /** Blob URL of this iteration's ATIF trajectory JSON. Normalized superset of + * tool calls; sent by pp-taxonomy in place of toolCallsUrl so observations + * can be evaluated against the full agent trajectory. See issue #1156. */ + atifUrl?: string; } /** diff --git a/packages/shared/src/schemas/criteria.ts b/packages/shared/src/schemas/criteria.ts index 29b50ddc3..efe0761c1 100644 --- a/packages/shared/src/schemas/criteria.ts +++ b/packages/shared/src/schemas/criteria.ts @@ -3,11 +3,13 @@ import { z } from "zod"; import { extendZodWithOpenApi } from "@asteasolutions/zod-to-openapi"; -import { GATES } from "../types/types.js"; +import { GATES, CRITERION_KINDS, TAXONOMY_ELEMENT_IDS } from "../types/types.js"; extendZodWithOpenApi(z); export const GateIdSchema = z.enum(GATES); +export const CriterionKindSchema = z.enum(CRITERION_KINDS); +export const TaxonomyElementIdSchema = z.enum(TAXONOMY_ELEMENT_IDS); export const CreateCriteriaInputSchema = z .object({ @@ -15,6 +17,8 @@ export const CreateCriteriaInputSchema = z prompt: z.string(), dependsOn: z.array(z.string()).optional(), gates: z.array(GateIdSchema).optional(), + kind: CriterionKindSchema.default("gate"), + taxonomyElementId: TaxonomyElementIdSchema.optional(), }) .openapi("CreateCriteriaInput"); @@ -23,6 +27,8 @@ export const UpdateCriteriaInputSchema = z prompt: z.string().optional(), dependsOn: z.array(z.string()).optional(), gates: z.array(GateIdSchema).optional(), + kind: CriterionKindSchema.optional(), + taxonomyElementId: TaxonomyElementIdSchema.optional(), }) .openapi("UpdateCriteriaInput"); @@ -32,6 +38,8 @@ export const CriteriaResponseSchema = z prompt: z.string(), dependsOn: z.array(z.string()).optional(), gates: z.array(GateIdSchema).optional(), + kind: CriterionKindSchema.optional(), + taxonomyElementId: TaxonomyElementIdSchema.optional(), createdAt: z.coerce.date(), updatedAt: z.coerce.date().optional(), deletedAt: z.coerce.date().optional(), @@ -44,6 +52,8 @@ export const CriteriaGraphNodeSchema = z prompt: z.string(), dependsOn: z.array(z.string()).optional(), gates: z.array(GateIdSchema).optional(), + kind: CriterionKindSchema.optional(), + taxonomyElementId: TaxonomyElementIdSchema.optional(), }) .openapi("CriteriaGraphNode"); diff --git a/packages/shared/src/schemas/request.ts b/packages/shared/src/schemas/request.ts index 513e54996..1abc04062 100644 --- a/packages/shared/src/schemas/request.ts +++ b/packages/shared/src/schemas/request.ts @@ -70,6 +70,7 @@ export const ConversationTurnSchema = z passed: z.boolean(), timestamp: z.coerce.date(), criteriaResults: z.array(CriterionResultSchema).optional(), + observationResults: z.array(CriterionResultSchema).optional(), harUrl: z.string().optional(), videoUrls: z.array(z.string()).optional(), tokenUsage: TokenUsageSchema.optional(), @@ -130,6 +131,7 @@ export const CreateRequestInputSchema = z profileVariations: z.array(z.string()).optional(), priority: z.number().int().optional(), gates: z.array(GateConfigSchema).optional(), + observations: z.array(z.string()).optional(), }) .openapi("CreateRequestInput"); @@ -157,6 +159,7 @@ export const RequestResponseSchema = z submissionId: z.string().optional(), priority: z.number().int().default(0), gates: z.array(GateConfigSchema).optional(), + observations: z.array(z.string()).optional(), gateSummaries: z.array(GateRunSummarySchema).optional(), // Per-attempt state lives in the run sub-document. run: z diff --git a/packages/shared/src/schemas/schemas.test.ts b/packages/shared/src/schemas/schemas.test.ts index c8e8adceb..0878e3cf3 100644 --- a/packages/shared/src/schemas/schemas.test.ts +++ b/packages/shared/src/schemas/schemas.test.ts @@ -515,6 +515,33 @@ describe("criteria schemas", () => { it("rejects missing prompt", () => { expect(() => CreateCriteriaInputSchema.parse({ id: "abc" })).toThrow(); }); + + it("defaults kind to 'gate' when absent", () => { + const result = CreateCriteriaInputSchema.parse({ id: "abc", prompt: "p" }); + expect(result.kind).toBe("gate"); + }); + + it("accepts kind:'observation' with a valid taxonomyElementId", () => { + const result = CreateCriteriaInputSchema.parse({ + id: "obs", + prompt: "p", + kind: "observation", + taxonomyElementId: "dimension:idiomatic-use", + }); + expect(result.kind).toBe("observation"); + expect(result.taxonomyElementId).toBe("dimension:idiomatic-use"); + }); + + it("rejects an unknown taxonomyElementId", () => { + expect(() => + CreateCriteriaInputSchema.parse({ + id: "obs", + prompt: "p", + kind: "observation", + taxonomyElementId: "dimension:nope", + }), + ).toThrow(); + }); }); describe("CriteriaResponseSchema", () => { diff --git a/packages/shared/src/storage/blob-storage.ts b/packages/shared/src/storage/blob-storage.ts index 19a7e3db2..99e0bab46 100644 --- a/packages/shared/src/storage/blob-storage.ts +++ b/packages/shared/src/storage/blob-storage.ts @@ -485,4 +485,27 @@ export class BlobStorage { const blockBlobClient = this.containerClient.getBlockBlobClient(blobName); return blockBlobClient.downloadToBuffer(); } + + /** + * Downloads and parses a JSON blob. Accepts either a full blob URL (Azure or + * Azurite) or a bare blob name within the snapshots container. Used by the + * judge to load ATIF trajectory JSON for observation evaluation. Issue #1156. + */ + async downloadJson(urlOrBlobName: string): Promise { + await this.ensureContainer(); + let blobName = urlOrBlobName; + if (urlOrBlobName.startsWith("http://") || urlOrBlobName.startsWith("https://")) { + const url = new URL(urlOrBlobName); + const containerPrefix = `/${SNAPSHOTS_CONTAINER}/`; + const containerIndex = url.pathname.indexOf(containerPrefix); + if (containerIndex === -1) { + throw new Error( + `Blob URL does not contain container '${SNAPSHOTS_CONTAINER}': ${urlOrBlobName}`, + ); + } + blobName = decodeURIComponent(url.pathname.substring(containerIndex + containerPrefix.length)); + } + const buf = await this.downloadBlobToBuffer(blobName); + return JSON.parse(buf.toString("utf-8")) as T; + } } diff --git a/packages/shared/src/types/types.ts b/packages/shared/src/types/types.ts index f233c21cb..34e708e16 100644 --- a/packages/shared/src/types/types.ts +++ b/packages/shared/src/types/types.ts @@ -62,6 +62,42 @@ export function isGateId(value: unknown): value is GateId { return typeof value === "string" && (GATES as readonly string[]).includes(value); } +/** + * Discriminator for what a criterion is used for. `"gate"` (default) gates the + * coding-agent session via the DAG; `"observation"` is record-only — it produces + * a per-iteration boolean + evidence and never feeds back, never pass/fails a + * gate, and never enters the gate DAG. See issue #1156. + */ +export type CriterionKind = "gate" | "observation"; + +/** The hard-coded set of criterion kinds. */ +export const CRITERION_KINDS = ["gate", "observation"] as const; + +/** True when `value` is a valid criterion kind. */ +export function isCriterionKind(value: unknown): value is CriterionKind { + return typeof value === "string" && (CRITERION_KINDS as readonly string[]).includes(value); +} + +/** + * Hard-coded taxonomy elements for observation criteria — the three quality + * dimensions from the R&A Readout design. Gates (select/build/test/run/deploy) + * are excluded as they live in the criterion `gates` field. Namespaced ids keep + * a future first-class taxonomy a clean migration. See issue #1156. + */ +export const TAXONOMY_ELEMENT_IDS = [ + "dimension:idiomatic-use", + "dimension:dependency-currency", + "dimension:configuration-correctness", +] as const; + +/** A single taxonomy element id. */ +export type TaxonomyElementId = (typeof TAXONOMY_ELEMENT_IDS)[number]; + +/** True when `value` is a valid taxonomy element id. */ +export function isTaxonomyElementId(value: unknown): value is TaxonomyElementId { + return typeof value === "string" && (TAXONOMY_ELEMENT_IDS as readonly string[]).includes(value); +} + /** * A prompt's type discriminator — one literal per gate. The prompt that drives * a gate must have a `type` equal to that gate's id. @@ -132,6 +168,10 @@ export interface ConversationTurn { passed: boolean; timestamp: Date; criteriaResults?: CriterionResult[]; // Per-criterion breakdown from DAG evaluation + /** Per-iteration observation results (kind:"observation" criteria), recorded + * by the pp-taxonomy post-processor. Same shape as criteriaResults but never + * gates the agent. Empty/absent when no observations were selected. #1156. */ + observationResults?: CriterionResult[]; harUrl?: string; // Blob storage URL to the HAR file for this turn videoUrls?: string[]; // Blob storage URLs to session recording videos for this turn tokenUsage?: TokenUsage; // LLM token usage for this iteration @@ -284,6 +324,13 @@ export interface RequestDocument { * docs/design/gates.md §4.3). Gates run in `GATE_ORDER`. */ gates?: GateConfig[]; + /** + * Observation-criteria ids (kind:"observation") selected at submit. The + * pp-taxonomy post-processor evaluates exactly this set after the run + * completes and writes per-turn `observationResults`. Empty/absent = none. + * See issue #1156. + */ + observations?: string[]; /** * Per-gate execution summary, populated as the run progresses. Derived * from `run.turns` but stored explicitly for cheap querying. @@ -597,6 +644,13 @@ export interface CriteriaConfig { * (applies only to NEW criteria; legacy rows are backfilled to ["select"] * by migration 018). See docs/design/gates.md §4.2. */ gates?: GateId[]; + /** Whether this criterion gates the agent or is a record-only observation. + * Default "gate" applied at store/schema layer; legacy rows backfilled to + * "gate" by migration. See issue #1156. */ + kind?: CriterionKind; + /** Design-time classification under a hard-coded taxonomy element. Only set + * on observation criteria. Static — never stored per run. See issue #1156. */ + taxonomyElementId?: TaxonomyElementId; } // Per-criterion result from judge evaluation From 19b02998acc79b868ac7042c69ddcd68bd33609b Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Sun, 28 Jun 2026 19:16:50 -0700 Subject: [PATCH 011/210] feat(portal): observation criteria kind/taxonomy UI, submit picker, observations tab Carry criterion kind + taxonomyElementId, request observations, and turn.observationResults through the portal: kind selector + taxonomy picker on criteria pages, observations multi-select on Submit Run, and a Run-detail Observations tab grouped by dimension. Includes Storybook stories. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../src/components/CreateCriterionDialog.tsx | 6 +- .../src/components/CriteriaBadge.stories.tsx | 49 +++++++ apps/portal/src/components/CriteriaBadge.tsx | 48 +++++-- .../src/components/CriteriaFilterBar.tsx | 29 ++++ apps/portal/src/components/CriteriaPicker.tsx | 11 +- .../src/components/CriteriaWizardStep1.tsx | 43 +++++- .../src/components/CriteriaWizardStep2.tsx | 39 +++++- .../ObservationTaxonomySelect.stories.tsx | 31 ++++ .../components/ObservationTaxonomySelect.tsx | 48 +++++++ apps/portal/src/hooks/useCriteriaWizard.ts | 50 +++++-- apps/portal/src/lib/api.ts | 7 +- apps/portal/src/pages/CriteriaList.tsx | 64 ++++++++- apps/portal/src/pages/CriterionDetail.tsx | 70 +++++++++- apps/portal/src/pages/RunDetail.tsx | 132 +++++++++++++++++- apps/portal/src/pages/SubmitRun.tsx | 47 +++++++ apps/portal/src/types.ts | 40 +++++- 16 files changed, 659 insertions(+), 55 deletions(-) create mode 100644 apps/portal/src/components/CriteriaBadge.stories.tsx create mode 100644 apps/portal/src/components/ObservationTaxonomySelect.stories.tsx create mode 100644 apps/portal/src/components/ObservationTaxonomySelect.tsx diff --git a/apps/portal/src/components/CreateCriterionDialog.tsx b/apps/portal/src/components/CreateCriterionDialog.tsx index 188009aac..be51969f3 100644 --- a/apps/portal/src/components/CreateCriterionDialog.tsx +++ b/apps/portal/src/components/CreateCriterionDialog.tsx @@ -15,6 +15,7 @@ import { } from "@/components/ui/dialog"; import { ArrowLeft, Loader2, Sparkles } from "lucide-react"; import type { GateId } from "@/lib/gates"; +import type { CriterionKind } from "@/types"; interface CreateCriterionDialogProps { open: boolean; @@ -25,12 +26,15 @@ interface CreateCriterionDialogProps { defaultGates?: GateId[]; /** Gates that cannot be unselected (e.g. the gate this criterion is created for) */ lockedGates?: GateId[]; + /** Pre-populated criteria kind (defaults to gate) */ + defaultKind?: CriterionKind; } -export function CreateCriterionDialog({ open, onOpenChange, onCreated, defaultGates, lockedGates }: CreateCriterionDialogProps) { +export function CreateCriterionDialog({ open, onOpenChange, onCreated, defaultGates, lockedGates, defaultKind }: CreateCriterionDialogProps) { const wizard = useCriteriaWizard({ initialGates: defaultGates, lockedGates, + initialKind: defaultKind, onSuccess: (id) => { onCreated(id); handleOpenChange(false); diff --git a/apps/portal/src/components/CriteriaBadge.stories.tsx b/apps/portal/src/components/CriteriaBadge.stories.tsx new file mode 100644 index 000000000..e851b3aec --- /dev/null +++ b/apps/portal/src/components/CriteriaBadge.stories.tsx @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import type { Meta, StoryObj } from "@storybook/react-vite"; +import { CriteriaBadge, CriteriaKindBadge } from "./CriteriaBadge"; + +const meta = { + title: "Components/CriteriaBadge", + component: CriteriaBadge, + tags: ["ai-generated", "needs-work"], +} satisfies Meta; + +export default meta; +type Story = StoryObj; + +export const GateCriterion: Story = { + args: { + criterionId: "has_unit_tests", + kind: "gate", + evaluated: true, + result: true, + showStateLabel: true, + link: false, + }, +}; + +export const ObservationCriterion: Story = { + args: { + criterionId: "uses_current_sdk", + kind: "observation", + evaluated: true, + result: false, + showStateLabel: true, + link: false, + }, +}; + +export const KindBadges: Story = { + args: { + criterionId: "has_unit_tests", + link: false, + }, + render: () => ( +
+ + +
+ ), +}; diff --git a/apps/portal/src/components/CriteriaBadge.tsx b/apps/portal/src/components/CriteriaBadge.tsx index f05b00b77..d1cc1bbc3 100644 --- a/apps/portal/src/components/CriteriaBadge.tsx +++ b/apps/portal/src/components/CriteriaBadge.tsx @@ -5,6 +5,7 @@ import { Link } from "react-router-dom"; import { Badge } from "@/components/ui/badge"; import { cn } from "@/lib/utils"; import { criterionResultStyle, type CriterionResultState } from "@/lib/criteria-result"; +import type { CriterionKind } from "@/types"; interface CriteriaBadgeProps { criterionId: string; @@ -13,6 +14,7 @@ interface CriteriaBadgeProps { link?: boolean; showStateLabel?: boolean; className?: string; + kind?: CriterionKind; } export function CriteriaBadge({ @@ -22,22 +24,30 @@ export function CriteriaBadge({ link = true, showStateLabel = false, className, + kind, }: CriteriaBadgeProps) { + const kindLabel = kind === "observation" ? "Obs" : kind === "gate" ? "Gate" : undefined; const content = !evaluated ? ( - - {criterionId} - + + + {criterionId} + + {kindLabel && } + ) : (() => { const { colorClass, Icon, label, title } = criterionResultStyle(result); return ( - - - {showStateLabel ? `${criterionId}: ${label}` : criterionId} - + + + + {showStateLabel ? `${criterionId}: ${label}` : criterionId} + + {kindLabel && } + ); })(); @@ -49,3 +59,19 @@ export function CriteriaBadge({ ); } + +export function CriteriaKindBadge({ kind, className }: { kind?: CriterionKind; className?: string }) { + const normalized = kind ?? "gate"; + return ( + + {normalized === "observation" ? "Observation" : "Gate"} + + ); +} diff --git a/apps/portal/src/components/CriteriaFilterBar.tsx b/apps/portal/src/components/CriteriaFilterBar.tsx index 3c1dff4f0..ec34abfad 100644 --- a/apps/portal/src/components/CriteriaFilterBar.tsx +++ b/apps/portal/src/components/CriteriaFilterBar.tsx @@ -4,6 +4,7 @@ import { Filter, X } from "lucide-react"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { Badge } from "@/components/ui/badge"; +import type { CriterionKind } from "@/types"; interface CriteriaFilterBarProps { availableCriteria: string[]; @@ -16,6 +17,10 @@ interface CriteriaFilterBarProps { emptyDescription?: string; /** Override the description template when criteria are selected (receives count) */ selectedDescription?: (count: number) => string; + /** Optional kind metadata for rendering gate/observation filter chips. */ + criteriaKinds?: Record; + selectedKinds?: CriterionKind[]; + onToggleKind?: (kind: CriterionKind) => void; } export function CriteriaFilterBar({ @@ -27,12 +32,22 @@ export function CriteriaFilterBar({ emptyDescription = "Click criteria to filter runs and redefine success. Default: all criteria in each run must pass.", selectedDescription = (count: number) => `Success = all ${count} selected criteria pass. Runs without these criteria are excluded.`, + criteriaKinds, + selectedKinds = [], + onToggleKind, }: CriteriaFilterBarProps) { if (availableCriteria.length === 0) { return null; } const selectedSet = new Set(selectedCriteria); + const selectedKindSet = new Set(selectedKinds); + const kindCounts = criteriaKinds + ? { + gate: availableCriteria.filter((id) => (criteriaKinds[id] ?? "gate") === "gate").length, + observation: availableCriteria.filter((id) => criteriaKinds[id] === "observation").length, + } + : undefined; return ( @@ -58,6 +73,20 @@ export function CriteriaFilterBar({ + {kindCounts && onToggleKind && ( +
+ {(["gate", "observation"] as const).map((kind) => ( + onToggleKind(kind)} + > + {kind} ({kindCounts[kind]}) + + ))} +
+ )}
{availableCriteria.map((id) => { const isSelected = selectedSet.has(id); diff --git a/apps/portal/src/components/CriteriaPicker.tsx b/apps/portal/src/components/CriteriaPicker.tsx index 05e04a454..19ed40767 100644 --- a/apps/portal/src/components/CriteriaPicker.tsx +++ b/apps/portal/src/components/CriteriaPicker.tsx @@ -10,7 +10,7 @@ import { Input } from "@/components/ui/input"; import { Skeleton } from "@/components/ui/skeleton"; import { Search, X, Sparkles } from "lucide-react"; import { GATE_METADATA, isCriterionCompatibleWithGate, type GateId } from "@/lib/gates"; -import type { CriteriaDocument } from "@/types"; +import type { CriteriaDocument, CriterionKind } from "@/types"; interface CriteriaPickerProps { selected: string[]; @@ -23,6 +23,8 @@ interface CriteriaPickerProps { trailingAction?: ReactNode; /** Restrict suggestions to criteria compatible with this gate */ gate?: GateId; + /** Restrict suggestions by criterion kind. Missing kind is treated as "gate". */ + kind?: CriterionKind; /** * Additional predicate restricting which criteria are offered as suggestions. * Used to enforce gate-compatibility invariants (e.g. only show criteria that @@ -31,7 +33,7 @@ interface CriteriaPickerProps { filter?: (criterion: CriteriaDocument) => boolean; } -export function CriteriaPicker({ selected, onChange, aiSuggested = [], inputId, trailingAction, gate, filter }: CriteriaPickerProps) { +export function CriteriaPicker({ selected, onChange, aiSuggested = [], inputId, trailingAction, gate, kind, filter }: CriteriaPickerProps) { const [query, setQuery] = useState(""); const [open, setOpen] = useState(false); const [highlightIdx, setHighlightIdx] = useState(0); @@ -49,6 +51,7 @@ export function CriteriaPicker({ selected, onChange, aiSuggested = [], inputId, const suggestions = useMemo(() => { const available = criteria.filter((c) => !selected.includes(c.id) && + (!kind || (c.kind ?? "gate") === kind) && (!gate || isCriterionCompatibleWithGate(c.gates, gate)) && (!filter || filter(c)) ); @@ -57,7 +60,7 @@ export function CriteriaPicker({ selected, onChange, aiSuggested = [], inputId, return available.filter( (c) => c.id.toLowerCase().includes(q) || c.prompt.toLowerCase().includes(q), ); - }, [criteria, selected, query, gate, filter]); + }, [criteria, selected, query, gate, kind, filter]); // Reset highlight when suggestions change useEffect(() => { @@ -212,7 +215,7 @@ export function CriteriaPicker({ selected, onChange, aiSuggested = [], inputId, }} onFocus={() => setOpen(true)} onKeyDown={handleKeyDown} - placeholder={gate ? `Search ${GATE_METADATA[gate].label} criteria…` : "Type to search criteria…"} + placeholder={kind === "observation" ? "Search observation criteria…" : gate ? `Search ${GATE_METADATA[gate].label} criteria…` : "Type to search criteria…"} className="h-9 font-mono text-sm" /> {trailingAction} diff --git a/apps/portal/src/components/CriteriaWizardStep1.tsx b/apps/portal/src/components/CriteriaWizardStep1.tsx index 252ca52ae..c6a182b36 100644 --- a/apps/portal/src/components/CriteriaWizardStep1.tsx +++ b/apps/portal/src/components/CriteriaWizardStep1.tsx @@ -4,7 +4,9 @@ import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Textarea } from "@/components/ui/textarea"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { GateCompatibilityPicker } from "@/components/GateCompatibilityPicker"; +import { ObservationTaxonomySelect } from "@/components/ObservationTaxonomySelect"; import type { CriteriaWizardState } from "@/hooks/useCriteriaWizard"; interface CriteriaWizardStep1Props { @@ -26,6 +28,10 @@ export function CriteriaWizardStep1({ wizard, idPrefix = "" }: CriteriaWizardSte gates, setGates, lockedGates, + kind, + setKind, + taxonomyElementId, + setTaxonomyElementId, } = wizard; return ( @@ -89,15 +95,42 @@ export function CriteriaWizardStep1({ wizard, idPrefix = "" }: CriteriaWizardSte

- {/* Gate compatibility */} + {/* Criteria kind */}
- - + +

- Select the gates this criterion applies to. Parents must be compatible with every - selected gate. This drives the gate-aware parent/child suggestions on the next step. + Gate criteria drive judge feedback. Observations are recorded after each iteration and never gate the agent.

+ + {/* Gate compatibility */} + {kind === "gate" ? ( +
+ + +

+ Select the gates this criterion applies to. Parents must be compatible with every + selected gate. This drives the gate-aware parent/child suggestions on the next step. +

+
+ ) : ( + + )}
); } diff --git a/apps/portal/src/components/CriteriaWizardStep2.tsx b/apps/portal/src/components/CriteriaWizardStep2.tsx index 9d56df64a..2e4e52cb4 100644 --- a/apps/portal/src/components/CriteriaWizardStep2.tsx +++ b/apps/portal/src/components/CriteriaWizardStep2.tsx @@ -8,6 +8,7 @@ import { Badge } from "@/components/ui/badge"; import { Separator } from "@/components/ui/separator"; import { CriteriaPicker } from "@/components/CriteriaPicker"; import { gatesSatisfyInvariant, GATE_METADATA, orderGateIds } from "@/lib/gates"; +import { TAXONOMY_ELEMENT_METADATA } from "@/types"; import { Loader2, Check, RefreshCw } from "lucide-react"; import type { CriteriaWizardState } from "@/hooks/useCriteriaWizard"; @@ -22,6 +23,8 @@ export function CriteriaWizardStep2({ wizard }: CriteriaWizardStep2Props) { dependsOn, setDependsOn, gates, + kind = "gate", + taxonomyElementId, prompt, setPrompt, aiGenerated, @@ -55,6 +58,15 @@ export function CriteriaWizardStep2({ wizard }: CriteriaWizardStep2Props) { {id}
+
+

+ Kind +

+ + {kind === "observation" ? "Observation" : "Gate"} + +
+ {kind === "gate" ? (

Gate compatibility @@ -71,6 +83,16 @@ export function CriteriaWizardStep2({ wizard }: CriteriaWizardStep2Props) { )}

+ ) : ( +
+

+ Observation dimension +

+ + {taxonomyElementId ? TAXONOMY_ELEMENT_METADATA[taxonomyElementId].label : "Unclassified"} + +
+ )} @@ -84,11 +106,14 @@ export function CriteriaWizardStep2({ wizard }: CriteriaWizardStep2Props) { selected={dependsOn} onChange={setDependsOn} aiSuggested={suggestedParents} - filter={(c) => gatesSatisfyInvariant(c.gates, gates) && !acceptedChildren.includes(c.id)} + filter={(c) => + (c.kind ?? "gate") === kind && + (kind === "observation" || gatesSatisfyInvariant(c.gates, gates)) && + !acceptedChildren.includes(c.id) + } />

- Criteria that must pass before this one is evaluated. Only criteria compatible with - every selected gate are shown. List only direct parents — + Criteria that must pass before this one is evaluated. {kind === "gate" ? "Only criteria compatible with every selected gate are shown." : "Only observation criteria are shown."} List only direct parents — the judge automatically evaluates all transitive ancestors in topological order, so you don't need to repeat a parent's own dependencies here.

@@ -105,11 +130,15 @@ export function CriteriaWizardStep2({ wizard }: CriteriaWizardStep2Props) { selected={acceptedChildren} onChange={setAcceptedChildren} aiSuggested={suggestedChildren} - filter={(c) => gatesSatisfyInvariant(gates, c.gates) && !dependsOn.includes(c.id)} + filter={(c) => + (c.kind ?? "gate") === kind && + (kind === "observation" || gatesSatisfyInvariant(gates, c.gates)) && + !dependsOn.includes(c.id) + } />

These criteria will be updated to depend on {id || "this criterion"} after creation. - Only criteria compatible with a subset of the selected gates are shown. + {kind === "gate" ? " Only criteria compatible with a subset of the selected gates are shown." : " Only observation criteria are shown."}

diff --git a/apps/portal/src/components/ObservationTaxonomySelect.stories.tsx b/apps/portal/src/components/ObservationTaxonomySelect.stories.tsx new file mode 100644 index 000000000..aab2ab344 --- /dev/null +++ b/apps/portal/src/components/ObservationTaxonomySelect.stories.tsx @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { useState } from "react"; +import type { Meta, StoryObj } from "@storybook/react-vite"; +import { ObservationTaxonomySelect } from "./ObservationTaxonomySelect"; +import type { TaxonomyElementId } from "@/types"; + +const meta = { + title: "Components/ObservationTaxonomySelect", + component: ObservationTaxonomySelect, + tags: ["ai-generated", "needs-work"], +} satisfies Meta; + +export default meta; +type Story = StoryObj; + +export const Default: Story = { + args: { + value: "dimension:idiomatic-use", + onChange: () => undefined, + }, + render: () => { + const [value, setValue] = useState("dimension:idiomatic-use"); + return ( +
+ +
+ ); + }, +}; diff --git a/apps/portal/src/components/ObservationTaxonomySelect.tsx b/apps/portal/src/components/ObservationTaxonomySelect.tsx new file mode 100644 index 000000000..1bdfabd7e --- /dev/null +++ b/apps/portal/src/components/ObservationTaxonomySelect.tsx @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { Label } from "@/components/ui/label"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; +import { TAXONOMY_ELEMENT_IDS, TAXONOMY_ELEMENT_METADATA, type TaxonomyElementId } from "@/types"; + +interface ObservationTaxonomySelectProps { + value?: TaxonomyElementId; + onChange: (value: TaxonomyElementId | undefined) => void; + id?: string; + label?: string; +} + +export function ObservationTaxonomySelect({ + value, + onChange, + id, + label = "Observation dimension", +}: ObservationTaxonomySelectProps) { + return ( +
+ + +

+ {value ? TAXONOMY_ELEMENT_METADATA[value].description : "Leave unset to group results as unclassified."} +

+
+ ); +} diff --git a/apps/portal/src/hooks/useCriteriaWizard.ts b/apps/portal/src/hooks/useCriteriaWizard.ts index 88575feb6..3033c2d49 100644 --- a/apps/portal/src/hooks/useCriteriaWizard.ts +++ b/apps/portal/src/hooks/useCriteriaWizard.ts @@ -7,6 +7,7 @@ import { api } from "@/lib/api"; import { slugify } from "@/lib/utils"; import { toast } from "sonner"; import { gatesSatisfyInvariant, type GateId } from "@/lib/gates"; +import type { CriterionKind, TaxonomyElementId } from "@/types"; export interface UseCriteriaWizardOptions { /** Pre-populated parent dependency IDs */ @@ -15,11 +16,20 @@ export interface UseCriteriaWizardOptions { initialGates?: GateId[]; /** Gates that cannot be unselected in the gate picker (e.g. inline creation) */ lockedGates?: GateId[]; + initialKind?: CriterionKind; + initialTaxonomyElementId?: TaxonomyElementId; /** Called with the new criterion ID after successful creation */ onSuccess: (id: string) => void; } -export function useCriteriaWizard({ initialDependsOn = [], initialGates, lockedGates, onSuccess }: UseCriteriaWizardOptions) { +export function useCriteriaWizard({ + initialDependsOn = [], + initialGates, + lockedGates, + initialKind = "gate", + initialTaxonomyElementId, + onSuccess, +}: UseCriteriaWizardOptions) { const queryClient = useQueryClient(); // Wizard step (1 or 2) @@ -31,6 +41,8 @@ export function useCriteriaWizard({ initialDependsOn = [], initialGates, lockedG const [idManuallyEdited, setIdManuallyEdited] = useState(false); const [dependsOn, setDependsOn] = useState(initialDependsOn); const [gates, setGates] = useState(initialGates ?? ["select"]); + const [kind, setKind] = useState(initialKind); + const [taxonomyElementId, setTaxonomyElementId] = useState(initialTaxonomyElementId); // Step 2 fields const [prompt, setPrompt] = useState(""); @@ -53,7 +65,13 @@ export function useCriteriaWizard({ initialDependsOn = [], initialGates, lockedG () => existingCriteria.some((c) => c.id === id.trim()), [id, existingCriteria], ); - const canContinue = behavior.trim().length > 0 && id.trim().length > 0 && idValid && !idExists && !criteriaLoading; + const canContinue = + behavior.trim().length > 0 && + id.trim().length > 0 && + idValid && + !idExists && + !criteriaLoading && + (kind === "observation" || !!gates?.length); // Gate compatibility lookup for parent/child suggestion filtering. const criterionGatesById = useMemo(() => { @@ -71,17 +89,17 @@ export function useCriteriaWizard({ initialDependsOn = [], initialGates, lockedG useEffect(() => { setDependsOn((prev) => { const next = prev.filter( - (pid) => !criterionGatesById.has(pid) || gatesSatisfyInvariant(criterionGatesById.get(pid), gates), + (pid) => kind === "observation" || !criterionGatesById.has(pid) || gatesSatisfyInvariant(criterionGatesById.get(pid), gates), ); return next.length === prev.length ? prev : next; }); setAcceptedChildren((prev) => { const next = prev.filter( - (cid) => !criterionGatesById.has(cid) || gatesSatisfyInvariant(gates, criterionGatesById.get(cid)), + (cid) => kind === "observation" || !criterionGatesById.has(cid) || gatesSatisfyInvariant(gates, criterionGatesById.get(cid)), ); return next.length === prev.length ? prev : next; }); - }, [gates, criterionGatesById, suggestedParents, suggestedChildren]); + }, [gates, kind, criterionGatesById, suggestedParents, suggestedChildren]); // Auto-suggest ID from behavior (unless manually edited) const handleBehaviorChange = useCallback( @@ -166,8 +184,8 @@ export function useCriteriaWizard({ initialDependsOn = [], initialGates, lockedG // Step 1 → Step 2 const handleContinue = useCallback(() => { setStep(2); - generateMutation.mutate({ behavior: behavior.trim(), gates }); - }, [behavior, gates, generateMutation]); + generateMutation.mutate({ behavior: behavior.trim(), gates: kind === "gate" ? gates : undefined }); + }, [behavior, gates, kind, generateMutation]); // Step 2 → Submit const handleCreate = useCallback(() => { @@ -176,17 +194,19 @@ export function useCriteriaWizard({ initialDependsOn = [], initialGates, lockedG id: id.trim(), prompt: prompt.trim(), dependsOn: dependsOn.length > 0 ? dependsOn : undefined, - gates, + ...(kind === "gate" ? { gates } : {}), + kind, + ...(kind === "observation" && taxonomyElementId ? { taxonomyElementId } : {}), }); - }, [id, prompt, dependsOn, gates, createMutation]); + }, [id, prompt, dependsOn, gates, kind, taxonomyElementId, createMutation]); // Regenerate prompt const handleRegenerate = useCallback(() => { setSuggestedParents([]); setSuggestedChildren([]); setAcceptedChildren([]); - generateMutation.mutate({ behavior: behavior.trim(), gates }); - }, [behavior, gates, generateMutation]); + generateMutation.mutate({ behavior: behavior.trim(), gates: kind === "gate" ? gates : undefined }); + }, [behavior, gates, kind, generateMutation]); // Reset all state to initial values const reset = useCallback(() => { @@ -196,12 +216,14 @@ export function useCriteriaWizard({ initialDependsOn = [], initialGates, lockedG setIdManuallyEdited(false); setDependsOn(initialDependsOn); setGates(initialGates ?? ["select"]); + setKind(initialKind); + setTaxonomyElementId(initialTaxonomyElementId); setPrompt(""); setAiGenerated(false); setSuggestedParents([]); setSuggestedChildren([]); setAcceptedChildren([]); - }, [initialDependsOn, initialGates]); + }, [initialDependsOn, initialGates, initialKind, initialTaxonomyElementId]); return { // State @@ -217,6 +239,10 @@ export function useCriteriaWizard({ initialDependsOn = [], initialGates, lockedG gates, setGates, lockedGates, + kind, + setKind, + taxonomyElementId, + setTaxonomyElementId, prompt, setPrompt, aiGenerated, diff --git a/apps/portal/src/lib/api.ts b/apps/portal/src/lib/api.ts index c3e275f09..281fad7dd 100644 --- a/apps/portal/src/lib/api.ts +++ b/apps/portal/src/lib/api.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import type { Run, RunState, CriteriaDocument, CriteriaGraphData, GeneratePromptResponse, AnalysisResponse, PromptFeatureDocument, Report, BulkReportStatus, BulkReportSummary, ReportTemplate, ReportTrigger, ReportTemplateSystemPrompt, KeyDocument, KeyValidationResult, CreateKeyRequest, UpdateKeyRequest, CodingAgent, AgentVersion, McpServerDocument, CreateMcpServerRequest, UpdateMcpServerRequest, BulkResubmitOverrides, Insight, InsightWithReference, TaskPrompt, TaskPromptFeatureExtractionResult, Model, FeatureFlag, SkillDocument, SkillSearchResult, SkillDiscoveryResult, SkillRevisionDocument, CodebaseDocument, CodebaseRevisionDocument, CodebaseSourceType, ExtensionDocument, ExtensionSearchResult, ExtensionVersionInfo, MdpResponse, AccountDocument, CreateAccountRequest, UpdateAccountRequest, ProfileWithVersion, ProfileVersionDocument, ProfileDocument, RunGroup, CursorPaginatedResponse, IterationOp, GateConfig, GateId, PromptType } from "@/types"; +import type { Run, RunState, CriteriaDocument, CriteriaGraphData, GeneratePromptResponse, AnalysisResponse, PromptFeatureDocument, Report, BulkReportStatus, BulkReportSummary, ReportTemplate, ReportTrigger, ReportTemplateSystemPrompt, KeyDocument, KeyValidationResult, CreateKeyRequest, UpdateKeyRequest, CodingAgent, AgentVersion, McpServerDocument, CreateMcpServerRequest, UpdateMcpServerRequest, BulkResubmitOverrides, Insight, InsightWithReference, TaskPrompt, TaskPromptFeatureExtractionResult, Model, FeatureFlag, SkillDocument, SkillSearchResult, SkillDiscoveryResult, SkillRevisionDocument, CodebaseDocument, CodebaseRevisionDocument, CodebaseSourceType, ExtensionDocument, ExtensionSearchResult, ExtensionVersionInfo, MdpResponse, AccountDocument, CreateAccountRequest, UpdateAccountRequest, ProfileWithVersion, ProfileVersionDocument, ProfileDocument, RunGroup, CursorPaginatedResponse, IterationOp, GateConfig, GateId, PromptType, CriterionKind, TaxonomyElementId } from "@/types"; import { qs } from "./url"; import { recordServerDate } from "./serverClock"; @@ -81,6 +81,7 @@ export const api = { /** Submit a new run (or multiple runs if count > 1) */ submitRun: (body: { scenario: { task: string; criteria: string[]; version?: "v1" | "v2" }; + observations?: string[]; worker?: string; model?: string; reasoningEffort?: string; @@ -317,7 +318,7 @@ export const api = { }, /** Create a new criterion */ - createCriterion: (body: { id: string; prompt: string; dependsOn?: string[]; gates?: GateId[] }): Promise => { + createCriterion: (body: { id: string; prompt: string; dependsOn?: string[]; gates?: GateId[]; kind?: CriterionKind; taxonomyElementId?: TaxonomyElementId }): Promise => { return request("/criteria", { method: "POST", body: JSON.stringify(body), @@ -325,7 +326,7 @@ export const api = { }, /** Update an existing criterion */ - updateCriterion: (id: string, body: { prompt?: string; dependsOn?: string[]; gates?: GateId[] }): Promise => { + updateCriterion: (id: string, body: { prompt?: string; dependsOn?: string[]; gates?: GateId[]; kind?: CriterionKind; taxonomyElementId?: TaxonomyElementId }): Promise => { return request(`/criteria/${id}`, { method: "PUT", body: JSON.stringify(body), diff --git a/apps/portal/src/pages/CriteriaList.tsx b/apps/portal/src/pages/CriteriaList.tsx index 2f64e390a..3c07c9800 100644 --- a/apps/portal/src/pages/CriteriaList.tsx +++ b/apps/portal/src/pages/CriteriaList.tsx @@ -35,12 +35,16 @@ import { type CustomizeColumnsOption, } from "@/components/list-layout"; import { HelpTooltip } from "@/components/HelpTooltip"; +import { CriteriaKindBadge } from "@/components/CriteriaBadge"; +import { TAXONOMY_ELEMENT_METADATA } from "@/types"; -const FILTER_KEYS = ["gate"] as const; +const FILTER_KEYS = ["gate", "kind"] as const; const COLUMN_OPTIONS: CustomizeColumnsOption[] = [ { id: "id", label: "ID", required: true }, { id: "prompt", label: "Prompt" }, + { id: "kind", label: "Kind" }, + { id: "taxonomy", label: "Dimension" }, { id: "gates", label: "Gates" }, { id: "dependencies", label: "Dependencies" }, { id: "actions", label: "Actions" }, @@ -87,12 +91,17 @@ export function CriteriaList() { const sortedCriteria = useMemo(() => { const selectedGates = state.getFilterList("gate") as GateId[]; + const selectedKinds = state.getFilterList("kind"); // A criterion matches if it is compatible with any selected gate (OR). // Criteria with no explicit gates are compatible with every gate. - const filtered = + const gateFiltered = selectedGates.length === 0 ? criteria - : criteria.filter((c) => selectedGates.some((g) => isCriterionCompatibleWithGate(c.gates, g))); + : criteria.filter((c) => (c.kind ?? "gate") === "gate" && selectedGates.some((g) => isCriterionCompatibleWithGate(c.gates, g))); + const filtered = + selectedKinds.length === 0 + ? gateFiltered + : gateFiltered.filter((c) => selectedKinds.includes(c.kind ?? "gate")); if (!state.sort) return filtered; const sorted = [...filtered]; sorted.sort((a, b) => { @@ -111,11 +120,19 @@ export function CriteriaList() { visibleGates.map((gate) => ({ value: gate, label: GATE_METADATA[gate].label, - count: criteria.filter((c) => isCriterionCompatibleWithGate(c.gates, gate)).length, + count: criteria.filter((c) => (c.kind ?? "gate") === "gate" && isCriterionCompatibleWithGate(c.gates, gate)).length, })), [criteria, visibleGates], ); + const kindFilterOptions = useMemo( + () => [ + { value: "gate", label: "Gate", count: criteria.filter((c) => (c.kind ?? "gate") === "gate").length }, + { value: "observation", label: "Observation", count: criteria.filter((c) => c.kind === "observation").length }, + ], + [criteria], + ); + const total = sortedCriteria.length; const pageStart = (state.page - 1) * state.pageSize; const pageItems = sortedCriteria.slice(pageStart, pageStart + state.pageSize); @@ -159,15 +176,41 @@ export function CriteriaList() { {truncate(c.prompt, 100)} ), }, + { + id: "kind", + header: "Kind", + width: "130px", + hidden: visibility.isHidden("kind"), + cell: (c) => , + }, + { + id: "taxonomy", + header: "Dimension", + width: "190px", + hidden: visibility.isHidden("taxonomy"), + cell: (c) => ( + + {c.kind === "observation" && c.taxonomyElementId + ? TAXONOMY_ELEMENT_METADATA[c.taxonomyElementId].label + : c.kind === "observation" + ? "Unclassified" + : "—"} + + ), + }, { id: "gates", header: "Gates", width: "160px", hidden: visibility.isHidden("gates"), cell: (c) => ( - - {formatGateList(c.gates)} - + c.kind === "observation" ? ( + Record-only + ) : ( + + {formatGateList(c.gates)} + + ) ), }, { @@ -297,6 +340,13 @@ export function CriteriaList() { onToggle={(value) => state.toggleFilterValue("gate", value)} /> + + state.toggleFilterValue("kind", value)} + /> + } secondaryPanel={ diff --git a/apps/portal/src/pages/CriterionDetail.tsx b/apps/portal/src/pages/CriterionDetail.tsx index 82c951105..51ec8b358 100644 --- a/apps/portal/src/pages/CriterionDetail.tsx +++ b/apps/portal/src/pages/CriterionDetail.tsx @@ -11,6 +11,7 @@ import { Badge } from "@/components/ui/badge"; import { Input } from "@/components/ui/input"; import { Textarea } from "@/components/ui/textarea"; import { Label } from "@/components/ui/label"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Separator } from "@/components/ui/separator"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, @@ -19,7 +20,9 @@ import { import { Skeleton } from "@/components/ui/skeleton"; import { ArrowLeft, Save, Trash2, Loader2, Sparkles, Check, X, Plus, Download } from "lucide-react"; import { CriteriaPicker } from "@/components/CriteriaPicker"; +import { CriteriaKindBadge } from "@/components/CriteriaBadge"; import { GateCompatibilityPicker } from "@/components/GateCompatibilityPicker"; +import { ObservationTaxonomySelect } from "@/components/ObservationTaxonomySelect"; import { formatDate } from "@/lib/utils"; import { formatGateList, @@ -30,6 +33,7 @@ import { useCommandEnter } from "@/hooks/useCommandEnter"; import { KbdBadge } from "@/components/KbdBadge"; import { criteriaToExportYaml, downloadAsFile } from "@/lib/criteria-export"; import { toast } from "sonner"; +import { TAXONOMY_ELEMENT_METADATA, type CriterionKind, type TaxonomyElementId } from "@/types"; export function CriterionDetail() { const { id } = useParams<{ id: string }>(); @@ -49,6 +53,8 @@ export function CriterionDetail() { const [prompt, setPrompt] = useState(""); const [editDependsOn, setEditDependsOn] = useState([]); const [editGates, setEditGates] = useState(undefined); + const [editKind, setEditKind] = useState("gate"); + const [editTaxonomyElementId, setEditTaxonomyElementId] = useState(undefined); // AI Suggest state const [aiSuggestOpen, setAiSuggestOpen] = useState(false); @@ -64,7 +70,7 @@ export function CriterionDetail() { }); const updateMutation = useMutation({ - mutationFn: (body: { prompt?: string; dependsOn?: string[]; gates?: GateId[] }) => + mutationFn: (body: { prompt?: string; dependsOn?: string[]; gates?: GateId[]; kind?: CriterionKind; taxonomyElementId?: TaxonomyElementId }) => api.updateCriterion(id!, body), onSuccess: async () => { // Update accepted children to depend on this criterion @@ -125,6 +131,8 @@ export function CriterionDetail() { setPrompt(criterion.prompt); setEditDependsOn(criterion.dependsOn ?? []); setEditGates(criterion.gates && criterion.gates.length > 0 ? criterion.gates : ["select"]); + setEditKind(criterion.kind ?? "gate"); + setEditTaxonomyElementId(criterion.taxonomyElementId); setAiSuggestOpen(false); setBehaviorInput(""); setSuggestedPrompt(null); @@ -135,14 +143,16 @@ export function CriterionDetail() { }; const handleSave = () => { - if (!editGates || editGates.length === 0) return; + if (editKind === "gate" && (!editGates || editGates.length === 0)) return; updateMutation.mutate({ prompt: prompt.trim(), // Always send the array (even empty) so removing the last dependency // persists. The backend treats `undefined` as "no change", so collapsing // [] to undefined here silently dropped deletions. dependsOn: editDependsOn, - gates: editGates, + ...(editKind === "gate" ? { gates: editGates } : {}), + kind: editKind, + taxonomyElementId: editKind === "observation" ? editTaxonomyElementId : undefined, }); }; @@ -164,13 +174,13 @@ export function CriterionDetail() { ? [ ...editDependsOn.flatMap((depId) => { const parent = allCriteria.find((c) => c.id === depId); - return parent && !gatesSatisfyInvariant(parent.gates, editGates) + return editKind === "gate" && parent && !gatesSatisfyInvariant(parent.gates, editGates) ? [`Parent '${depId}' must include ${formatGateList(editGates)}.`] : []; }), ...(criterion?.dependents.flatMap((childId) => { const child = allCriteria.find((c) => c.id === childId); - return child && !gatesSatisfyInvariant(editGates, child.gates) + return editKind === "gate" && child && !gatesSatisfyInvariant(editGates, child.gates) ? [`Dependent '${childId}' requires ${formatGateList(child.gates)} compatibility.`] : []; }) ?? []), @@ -451,7 +461,54 @@ export function CriterionDetail() { + {/* Kind */} + + + Kind + + Whether this criterion gates iteration flow or records observation evidence. + + + + {editing ? ( + <> +
+ + +
+ {editKind === "observation" && ( + + )} + + ) : ( +
+ + {(criterion.kind ?? "gate") === "observation" && ( + + {criterion.taxonomyElementId + ? TAXONOMY_ELEMENT_METADATA[criterion.taxonomyElementId].label + : "Unclassified"} + + )} +
+ )} +
+
+ {/* Gate compatibility */} + {(editing ? editKind === "gate" : (criterion.kind ?? "gate") === "gate") && ( Gate compatibility @@ -479,6 +536,7 @@ export function CriterionDetail() { )} + )} {/* Dependencies */} @@ -495,6 +553,8 @@ export function CriterionDetail() { c.id !== criterion.id && (editKind === "observation" || gatesSatisfyInvariant(c.gates, editGates))} /> ) : (criterion.dependsOn ?? []).length > 0 ? (
diff --git a/apps/portal/src/pages/RunDetail.tsx b/apps/portal/src/pages/RunDetail.tsx index eb2732011..12308f173 100644 --- a/apps/portal/src/pages/RunDetail.tsx +++ b/apps/portal/src/pages/RunDetail.tsx @@ -41,7 +41,14 @@ import { } from "@/lib/gates"; import { useState, useMemo, useEffect, type ReactNode } from "react"; import { toast } from "sonner"; -import type { RunState, LogEvent } from "@/types"; +import { + TAXONOMY_ELEMENT_METADATA, + type CriteriaDocument, + type CriterionResult, + type RunState, + type LogEvent, + type TaxonomyElementId, +} from "@/types"; import { useShiftModifier } from "@/hooks/useShiftModifier"; import { getRetryButtonState } from "@/components/RetryButton"; @@ -202,6 +209,91 @@ function CriteriaGateTabs({ ); } +type ObservationDimensionKey = TaxonomyElementId | "unclassified"; + +function observationDimensionLabel(key: ObservationDimensionKey): string { + return key === "unclassified" ? "Unclassified" : TAXONOMY_ELEMENT_METADATA[key].label; +} + +function ObservationResultsPanel({ + turns, + criteria, +}: { + turns: RunState["turns"]; + criteria: CriteriaDocument[]; +}) { + const criteriaById = useMemo(() => new Map(criteria.map((criterion) => [criterion.id, criterion])), [criteria]); + const groups = useMemo(() => { + const byDimension = new Map[number]; result: CriterionResult; criterion?: CriteriaDocument }>>(); + for (const turn of turns ?? []) { + for (const result of turn.observationResults ?? []) { + const criterion = criteriaById.get(result.criterionId); + const key: ObservationDimensionKey = criterion?.taxonomyElementId ?? "unclassified"; + const existing = byDimension.get(key) ?? []; + existing.push({ turn, result, criterion }); + byDimension.set(key, existing); + } + } + return Array.from(byDimension.entries()).sort(([a], [b]) => observationDimensionLabel(a).localeCompare(observationDimensionLabel(b))); + }, [turns, criteriaById]); + + if (groups.length === 0) { + return ( + + + No observation results have been recorded for this attempt. + + + ); + } + + return ( +
+ {groups.map(([dimension, items]) => ( + + + + + Observation + + {observationDimensionLabel(dimension)} + + + + {items.map(({ turn, result, criterion }) => ( +
+
+ Iteration {turn.iteration} + {turn.gate && {GATE_METADATA[turn.gate].label}} + {result.criterionId} + + {result.evaluated ? ( + result.passed ? : + ) : ( + + )} + {result.evaluated ? (result.passed ? "True" : "False") : "Not evaluated"} + +
+ {criterion?.prompt && ( +

{criterion.prompt}

+ )} +
+

Evidence

+

{result.feedback || "No evidence provided."}

+
+
+ ))} +
+
+ ))} +
+ ); +} + export function RunDetail() { const { id, tab } = useParams<{ id: string; tab?: string }>(); const navigate = useNavigate(); @@ -300,6 +392,14 @@ export function RunDetail() { enabled: !!taskPromptId, }); + const hasObservationResults = (activeRun?.turns ?? []).some((turn) => (turn.observationResults?.length ?? 0) > 0); + const hasConfiguredObservations = (run?.observations?.length ?? 0) > 0; + const { data: observationCriteria = [] } = useQuery({ + queryKey: ["criteria", "observations", run?.observations], + queryFn: () => api.listCriteria(undefined, run?.observations?.length ? { ids: run.observations } : undefined), + enabled: hasConfiguredObservations || hasObservationResults, + }); + // Fetch reports for this run const { data: reports, refetch: refetchReports } = useQuery({ queryKey: ["run-reports", id], @@ -860,6 +960,11 @@ export function RunDetail() { {hasHarData && Network} {hasHarData && Tool Calls} {hasVideoData && } + {(hasConfiguredObservations || hasObservationResults) && ( + + Observations {hasObservationResults ? `(${activeRun?.turns?.reduce((count, turn) => count + (turn.observationResults?.length ?? 0), 0) ?? 0})` : ""} + + )} Logs Reports {reports && reports.length > 0 ? `(${reports.length})` : ""} @@ -955,6 +1060,12 @@ export function RunDetail() { )} + {(hasConfiguredObservations || hasObservationResults) && ( + + + + )} + {/* Logs tab */} {criteriaGates.length > 0 && ( @@ -1175,6 +1286,25 @@ export function RunDetail() {
)} + {(run.observations?.length ?? 0) > 0 && ( +
+

Observations ({run.observations!.length})

+
+ {run.observations!.map((criterionId) => ( + + ))} +
+
+ )}
diff --git a/apps/portal/src/pages/SubmitRun.tsx b/apps/portal/src/pages/SubmitRun.tsx index bb40f1fca..e0c075802 100644 --- a/apps/portal/src/pages/SubmitRun.tsx +++ b/apps/portal/src/pages/SubmitRun.tsx @@ -197,6 +197,7 @@ export function SubmitRun() { // Form state const [task, setTask] = useState(""); const [pickedCriteria, setPickedCriteria] = useState([]); + const [pickedObservations, setPickedObservations] = useState([]); const [worker, setWorker] = useState("coder-acp-copilot"); const [model, setModel] = useState(""); const [reasoningEffort, setReasoningEffort] = useState(""); @@ -228,6 +229,7 @@ export function SubmitRun() { // Inline criteria creation dialog const [createCriterionOpen, setCreateCriterionOpen] = useState(false); + const [createObservationOpen, setCreateObservationOpen] = useState(false); const [gateCriterionDialog, setGateCriterionDialog] = useState | null>(null); const [createProfileOpen, setCreateProfileOpen] = useState(false); @@ -459,6 +461,7 @@ export function SubmitRun() { const applyRecentRun = (run: Run) => { if (run.scenario?.task) setTask(run.scenario.task); if (run.scenario?.criteria) setPickedCriteria(run.scenario.criteria); + setPickedObservations(run.observations ?? []); setWorker(run.workerType); if (run.model) setModel(run.model); if (run.agentVersion) setSelectedAgentVersion(run.agentVersion); @@ -615,6 +618,7 @@ export function SubmitRun() { submitMutation.mutate({ scenario: { task: task.trim(), criteria: pickedCriteria }, + ...(pickedObservations.length > 0 ? { observations: pickedObservations } : {}), ...(inVariationMode ? {} : { ...(worker ? { worker } : {}) }), ...(inVariationMode ? {} : { ...(model ? { model } : {}) }), ...(inVariationMode ? {} : { ...(reasoningEffort ? { reasoningEffort } : {}) }), @@ -713,6 +717,7 @@ export function SubmitRun() { const summaryChips: string[] = [ `${maxIterations} iteration${maxIterations === 1 ? "" : "s"}`, `${pickedCriteria.length} select criteri${pickedCriteria.length === 1 ? "on" : "a"}`, + pickedObservations.length > 0 ? `${pickedObservations.length} observation${pickedObservations.length === 1 ? "" : "s"}` : "", gatesEnabled ? `${gateConfigs.length} configured gates` : "single-pass Select", occurrences > 1 ? `×${occurrences} runs` : "", worker, @@ -939,6 +944,7 @@ export function SubmitRun() { onChange={setPickedCriteria} inputId="criteria" gate="select" + kind="gate" trailingAction={( + )} + /> + setPickedObservations((prev) => [...prev, id])} + /> +

+ + Observation results appear in the run detail observations tab grouped by dimension. +

+ +
@@ -1099,6 +1145,7 @@ export function SubmitRun() { updateGateDraft(gate, { criteria })} trailingAction={( diff --git a/apps/portal/src/types.ts b/apps/portal/src/types.ts index 74918b4bf..079ef7b2d 100644 --- a/apps/portal/src/types.ts +++ b/apps/portal/src/types.ts @@ -27,6 +27,40 @@ export interface ToolCall { timestamp?: string; } +export type CriterionKind = "gate" | "observation"; + +export const TAXONOMY_ELEMENT_IDS = [ + "dimension:idiomatic-use", + "dimension:dependency-currency", + "dimension:configuration-correctness", +] as const; + +export type TaxonomyElementId = (typeof TAXONOMY_ELEMENT_IDS)[number]; + +export interface TaxonomyElementMetadata { + id: TaxonomyElementId; + label: string; + description: string; +} + +export const TAXONOMY_ELEMENT_METADATA: Record = { + "dimension:idiomatic-use": { + id: "dimension:idiomatic-use", + label: "Idiomatic use", + description: "Did the agent follow recommended patterns and best practices?", + }, + "dimension:dependency-currency": { + id: "dimension:dependency-currency", + label: "Dependency currency", + description: "Did the agent use current versions, packages, and namespaces?", + }, + "dimension:configuration-correctness": { + id: "dimension:configuration-correctness", + label: "Configuration correctness", + description: "Are auth, connection, environment, and deployment settings configured properly?", + }, +}; + export interface ConversationTurn { iteration: number; gate?: GateId; @@ -36,6 +70,7 @@ export interface ConversationTurn { passed: boolean; timestamp: string; criteriaResults?: CriterionResult[]; + observationResults?: CriterionResult[]; harUrl?: string; videoUrls?: string[]; tokenUsage?: TokenUsage; @@ -144,6 +179,7 @@ export interface Run { profileId?: string; profileVersionId?: string; gates?: GateConfig[]; + observations?: string[]; gateSummaries?: GateRunSummary[]; } @@ -206,6 +242,8 @@ export interface CriteriaConfig { prompt: string; dependsOn?: string[]; gates?: GateId[]; + kind?: CriterionKind; + taxonomyElementId?: TaxonomyElementId; } export interface CriteriaDocument extends CriteriaConfig { @@ -215,7 +253,7 @@ export interface CriteriaDocument extends CriteriaConfig { } export interface CriteriaGraphData { - nodes: Array<{ id: string; prompt: string; dependsOn: string[]; gates?: GateId[] }>; + nodes: Array<{ id: string; prompt: string; dependsOn: string[]; gates?: GateId[]; kind?: CriterionKind; taxonomyElementId?: TaxonomyElementId }>; edges: Array<{ source: string; target: string }>; } From 78899c20b1b1c7226f7e19efffe812c76206c795 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Mon, 29 Jun 2026 11:39:49 -0700 Subject: [PATCH 012/210] test(judge): live ATIF-trajectory observation acceptance (issue #1156) Proves the judge consumes atifUrl: a trajectory-only observation (dependency_added_then_removed) resolves passed:true WITH the synthetic agent_trajectory_atif tool call and passed:false WITHOUT it. Excluded from default vitest; runs via vitest.integration.config.ts with a Copilot token. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ...observation-trajectory.integration.test.ts | 165 ++++++++++++++++++ 1 file changed, 165 insertions(+) create mode 100644 apps/judge/src/observation-trajectory.integration.test.ts diff --git a/apps/judge/src/observation-trajectory.integration.test.ts b/apps/judge/src/observation-trajectory.integration.test.ts new file mode 100644 index 000000000..c8b31030b --- /dev/null +++ b/apps/judge/src/observation-trajectory.integration.test.ts @@ -0,0 +1,165 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * ATIF-trajectory observation acceptance test (issue #1156, acceptance step 3). + * + * Proves the judge resolves a trajectory-only observation — one whose answer is + * NOT derivable from the final workspace snapshot — by consuming the agent's + * ATIF trajectory that pp-taxonomy forwards as a synthetic `agent_trajectory_atif` + * tool call (see apps/judge/src/index.ts). The canonical case is + * `dependency_added_then_removed`: a package is installed then uninstalled mid-run, + * so it is invisible in the end-state snapshot and only the trajectory reveals it. + * + * Two assertions form the acceptance: + * 1. WITH the trajectory tool call → criterion resolves passed:true (the judge + * actually consumed the ATIF). + * 2. WITHOUT the trajectory (snapshot only) → the same criterion flips to + * passed:false, proving the verdict comes from the trajectory, not the files. + * + * Exercises the REAL Copilot SDK, so it requires GITHUB_TOKEN (copilot scope) and + * is skipped automatically when the token is absent — mirroring + * judge-evaluation.integration.test.ts. + */ +import { describe, it, expect, beforeAll, afterAll } from "vitest"; +import { mkdtempSync, writeFileSync, rmSync, realpathSync } from "fs"; +import { tmpdir } from "os"; +import { join } from "path"; +import { resetCriteriaProvider } from "shared/criteria-provider-factory"; +import type { ToolCall } from "shared"; +import { evaluateWorkspace } from "./judge-agent.js"; + +const hasToken = !!process.env.GITHUB_TOKEN; +const JUDGE_MODEL = process.env.JUDGE_MODEL || "gpt-5.4-mini"; + +/** + * Synthetic ATIF trajectory mirroring what pp-taxonomy forwards: the agent + * installs `left-pad`, uses it, then uninstalls it before finishing. The final + * package.json (below) therefore does NOT list left-pad. + */ +const ATIF_TRAJECTORY = { + schema: "atif/1", + steps: [ + { type: "tool_call", name: "run_in_terminal", arguments: { command: "npm install left-pad" }, response: "+ left-pad@1.3.0\nadded 1 package" }, + { type: "tool_call", name: "edit_file", arguments: { path: "index.js" }, response: "require('left-pad')" }, + { type: "tool_call", name: "run_in_terminal", arguments: { command: "npm uninstall left-pad" }, response: "removed 1 package" }, + ], +}; + +const TRAJECTORY_TOOL_CALL: ToolCall = { + id: "atif-trajectory", + name: "agent_trajectory_atif", + arguments: {}, + response: JSON.stringify(ATIF_TRAJECTORY), +}; + +describe("judge ATIF-trajectory observation (integration)", () => { + let workspaceDir: string; + let criteriaDir: string; + const saved: Record = {}; + + function setEnv(key: string, value: string): void { + saved[key] = process.env[key]; + process.env[key] = value; + } + + beforeAll(() => { + workspaceDir = realpathSync(mkdtempSync(join(tmpdir(), "judge-atif-ws-"))); + criteriaDir = realpathSync(mkdtempSync(join(tmpdir(), "judge-atif-crit-"))); + + // End-state snapshot: package.json WITHOUT left-pad. The add-then-remove is + // invisible here; only the trajectory reveals it. + writeFileSync( + join(workspaceDir, "package.json"), + JSON.stringify({ name: "demo", version: "1.0.0", dependencies: {} }, null, 2) + "\n", + ); + writeFileSync(join(workspaceDir, "index.js"), "console.log('hello');\n"); + + // Observation criterion (matches config/criteria/dependency_added_then_removed.yaml). + writeFileSync( + join(criteriaDir, "dependency_added_then_removed.yaml"), + [ + "id: dependency_added_then_removed", + "kind: observation", + "taxonomy_element_id: dimension:dependency-currency", + "prompt: |", + " During the run the agent installed a package and later uninstalled or", + " removed it before finishing (e.g. added left-pad then removed it). This", + " is only derivable from the agent's trajectory (mid-run tool calls), not", + " from the final codebase snapshot, because the dependency is absent in the", + " end state. Inspect the agent_trajectory_atif tool output to detect a", + " transient add-then-remove.", + "", + ].join("\n"), + ); + + setEnv("CRITERIA_DIR", criteriaDir); + setEnv("JUDGE_STRATEGY", process.env.JUDGE_STRATEGY || "independent"); + setEnv("JUDGE_MODEL", JUDGE_MODEL); + setEnv("FEEDBACK_MODEL", process.env.FEEDBACK_MODEL || JUDGE_MODEL); + resetCriteriaProvider(); + }); + + afterAll(() => { + for (const [key, value] of Object.entries(saved)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + resetCriteriaProvider(); + rmSync(workspaceDir, { recursive: true, force: true }); + rmSync(criteriaDir, { recursive: true, force: true }); + }); + + it.skipIf(!hasToken)( + "resolves a trajectory-only observation true WITH the ATIF, false WITHOUT it", + { timeout: 600_000 }, + async () => { + // (1) WITH the ATIF trajectory tool call → the agent's add-then-remove is + // visible, so the observation must resolve true. + const withAtif = await evaluateWorkspace({ + workspacePath: workspaceDir, + criteria: ["dependency_added_then_removed"], + conversationHistory: [], + toolCalls: [TRAJECTORY_TOOL_CALL], + }); + + const obsWith = withAtif.criteriaResults.find( + (r) => r.criterionId === "dependency_added_then_removed", + ); + expect(obsWith, "observation result missing (with ATIF)").toBeTruthy(); + expect(obsWith!.evaluated).toBe(true); + expect( + obsWith!.passed, + `expected trajectory-only observation to pass WITH ATIF. Feedback: ${obsWith!.feedback}`, + ).toBe(true); + + // (2) WITHOUT the ATIF (snapshot only) → the add-then-remove is invisible + // in the end state, so the same observation must flip to false. This proves + // the verdict was driven by the trajectory, not the workspace files. + const withoutAtif = await evaluateWorkspace({ + workspacePath: workspaceDir, + criteria: ["dependency_added_then_removed"], + conversationHistory: [], + }); + + const obsWithout = withoutAtif.criteriaResults.find( + (r) => r.criterionId === "dependency_added_then_removed", + ); + expect(obsWithout, "observation result missing (without ATIF)").toBeTruthy(); + expect(obsWithout!.evaluated).toBe(true); + expect( + obsWithout!.passed, + `expected trajectory-only observation to FAIL without ATIF (snapshot has no left-pad). Feedback: ${obsWithout!.feedback}`, + ).toBe(false); + }, + ); + + it("logs a skip note when GITHUB_TOKEN is absent (no real evaluation possible)", () => { + if (!hasToken) { + console.warn( + "[integration] GITHUB_TOKEN not set — ATIF-trajectory observation test skipped", + ); + } + expect(true).toBe(true); + }); +}); From c0a20936ddc1887bfa2545bb85a78c889501d0ed Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Mon, 29 Jun 2026 12:01:47 -0700 Subject: [PATCH 013/210] fix(post-processor): copy handler.taxonomy.yaml into image so pp-taxonomy registers The Dockerfile copied only handler.yaml, so the register-handler-taxonomy job (HANDLER_YAML_PATH=apps/workers/post-processor/handler.taxonomy.yaml) failed with ENOENT in the container, exit 1, gating the post-processor (hard depends_on service_completed_successfully). Use a handler*.yaml glob in both builder and prod stages so every handler manifest is baked in. Verified in compose: register-handler-taxonomy now exits 0 ("Registered pp-taxonomy successfully") and the post-processor loads both the atif and taxonomy handlers. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- apps/workers/post-processor/Dockerfile | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/apps/workers/post-processor/Dockerfile b/apps/workers/post-processor/Dockerfile index 6d6bf8e04..a70478630 100644 --- a/apps/workers/post-processor/Dockerfile +++ b/apps/workers/post-processor/Dockerfile @@ -15,7 +15,10 @@ COPY packages/shared/tsconfig.json ./packages/shared/ COPY packages/shared/src ./packages/shared/src/ COPY apps/workers/post-processor/tsconfig.json ./apps/workers/post-processor/ COPY apps/workers/post-processor/src ./apps/workers/post-processor/src/ -COPY apps/workers/post-processor/handler.yaml ./apps/workers/post-processor/ +# Copy every handler manifest (handler.yaml = pp-atif, handler.taxonomy.yaml = +# pp-taxonomy, plus any future handlers). The registration jobs read these by +# HANDLER_YAML_PATH, so all must be present in the image. +COPY apps/workers/post-processor/handler*.yaml ./apps/workers/post-processor/ RUN pnpm --filter shared build && pnpm --filter post-processor build @@ -44,7 +47,7 @@ RUN pnpm install --frozen-lockfile --prod COPY --from=builder /app/packages/shared/dist ./packages/shared/dist/ COPY --from=builder /app/apps/workers/post-processor/dist ./apps/workers/post-processor/dist/ -COPY --from=builder /app/apps/workers/post-processor/handler.yaml ./apps/workers/post-processor/handler.yaml +COPY --from=builder /app/apps/workers/post-processor/handler*.yaml ./apps/workers/post-processor/ WORKDIR /app/apps/workers/post-processor From d5f866badaa3350c859c781efa67a090e3456f0c Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Mon, 29 Jun 2026 13:30:53 -0700 Subject: [PATCH 014/210] fix(compose): give post-processor JUDGE_SERVICE_URL so pp-taxonomy reaches judge The post-processor service used the *common-env anchor, which omits JUDGE_SERVICE_URL (only *worker-env defines it). pp-atif never called the judge so the gap was invisible, but pp-taxonomy (issue #1156) evaluates observation criteria via JudgeClient and fell back to localhost:3002 inside the container. Set JUDGE_SERVICE_URL=http://judge:80 explicitly. k8s is unaffected: post-processor.yaml already pulls JUDGE_SERVICE_URL from the worker-config ConfigMap via envFrom. Verified in compose: the containerized post-processor reached the judge container, which loaded the ATIF and wrote run.turns[].observationResults (dependency_added_then_removed -> passed:true). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docker-compose.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docker-compose.yml b/docker-compose.yml index aea2d76f7..aa1c06821 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -686,6 +686,10 @@ services: AZURE_STORAGE_QUEUE_POSTPROCESSOR: post-processor-queue SCOPE_MT_API_URL: http://api:80 SCHEDULER_URL: http://scheduler:8080 + # pp-taxonomy (issue #1156) calls the judge service to evaluate + # observation criteria. Without this the JudgeClient falls back to + # localhost:3002 and cannot reach the judge container. + JUDGE_SERVICE_URL: http://judge:80 depends_on: mongodb: condition: service_healthy From 7fde27f8200624a4693a56b362e144b57d43cd0c Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Mon, 29 Jun 2026 13:32:02 -0700 Subject: [PATCH 015/210] docs(env): clarify post-processor JUDGE_SERVICE_URL wiring in compose vs k8s In k8s the post-processor inherits JUDGE_SERVICE_URL from the worker-config ConfigMap via envFrom; in docker-compose the service uses the common-env anchor (not worker-env), so JUDGE_SERVICE_URL is set explicitly on the post-processor service. Reflects the compose fix in 3f2e98cc. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ENV_VARIABLES.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ENV_VARIABLES.md b/ENV_VARIABLES.md index 3001c4b16..293c83db2 100644 --- a/ENV_VARIABLES.md +++ b/ENV_VARIABLES.md @@ -347,7 +347,7 @@ Azure Storage Queue name used by both the scheduler (to enqueue post-processing **Default:** falls back to `JUDGE_SERVICE_URL`, then `http://localhost:3002` **Type:** URL string -Base URL of the judge service used by the `pp-taxonomy` post-process handler to evaluate observation criteria per iteration (snapshot + ATIF trajectory → boolean + evidence). The handler reuses the shared `JudgeClient`, so `JUDGE_CLIENT_TIMEOUT` / `JUDGE_CLIENT_RETRIES` apply. In Docker/K8s the worker reads `JUDGE_SERVICE_URL` from `worker-config`; no extra var needed. See issue #1156 and [docs/architecture/post-processing.md](docs/architecture/post-processing.md). +Base URL of the judge service used by the `pp-taxonomy` post-process handler to evaluate observation criteria per iteration (snapshot + ATIF trajectory → boolean + evidence). The handler reuses the shared `JudgeClient`, so `JUDGE_CLIENT_TIMEOUT` / `JUDGE_CLIENT_RETRIES` apply. In K8s the post-processor reads `JUDGE_SERVICE_URL` from the `worker-config` ConfigMap (`envFrom`); in docker-compose the `post-processor` service sets `JUDGE_SERVICE_URL: http://judge:80` explicitly (it uses the `common-env` anchor, which — unlike `worker-env` — does not carry it). See issue #1156 and [docs/architecture/post-processing.md](docs/architecture/post-processing.md). ### SCHEDULER_URL **Default:** (not set) From 7a639ad33bef7f90cbea30fcead8082f038a17f7 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Mon, 29 Jun 2026 14:17:48 -0700 Subject: [PATCH 016/210] fix(pp-taxonomy): read selected observations from request top-level, not run.observations The API submit path persists the selected observation-criteria ids at the request document top-level (RequestDocument.observations, types.ts), but the TaxonomyHandler read them from doc.run.observations. They never met, so pp-taxonomy no-op'd on every real submitted run and never wrote turn.observationResults. Read doc.observations (top-level) instead; turns still come from doc.run.turns. Rename the local RunDoc interface to RequestDoc and document the placement. Update the handler unit tests to put observations at the canonical top-level, and add a regression test asserting that legacy run.observations is ignored (no-op), which would have caught this. Verified end-to-end on a real submitted run through the containerized stack: turn.observationResults is written with passed:true and feedback citing the mid-run install/uninstall trajectory (the judge consumed atifUrl). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../src/handlers/taxonomy-handler.test.ts | 22 ++++++++++++++---- .../src/handlers/taxonomy-handler.ts | 23 +++++++++++-------- 2 files changed, 31 insertions(+), 14 deletions(-) diff --git a/apps/workers/post-processor/src/handlers/taxonomy-handler.test.ts b/apps/workers/post-processor/src/handlers/taxonomy-handler.test.ts index 18831592a..4b328b8e6 100644 --- a/apps/workers/post-processor/src/handlers/taxonomy-handler.test.ts +++ b/apps/workers/post-processor/src/handlers/taxonomy-handler.test.ts @@ -31,7 +31,21 @@ describe("TaxonomyHandler", () => { }); it("no-ops when no observations are selected", async () => { - const ctx = makeCtx({ _id: "req-1", run: { observations: [], turns: [{ iteration: 1, snapshotUrl: "s://1" }] } }); + const ctx = makeCtx({ _id: "req-1", observations: [], run: { turns: [{ iteration: 1, snapshotUrl: "s://1" }] } }); + await new TaxonomyHandler(judge as unknown as JudgeClient).process(msg, ctx); + expect(judge.evaluate).not.toHaveBeenCalled(); + expect(ctx.collection.updateOne).not.toHaveBeenCalled(); + }); + + it("reads observations from the request top-level, not run.observations (#1156 regression)", async () => { + // The API persists selected observation ids at the request top-level + // (RequestDocument.observations). A doc that only carries the legacy + // run.observations must be treated as "none selected" → no-op, proving the + // handler reads the canonical location the submit path actually writes. + const ctx = makeCtx({ + _id: "req-1", + run: { observations: ["dep_removed"], turns: [{ iteration: 1, snapshotUrl: "s://1", atifUrl: "a://1" }] }, + }); await new TaxonomyHandler(judge as unknown as JudgeClient).process(msg, ctx); expect(judge.evaluate).not.toHaveBeenCalled(); expect(ctx.collection.updateOne).not.toHaveBeenCalled(); @@ -45,8 +59,8 @@ describe("TaxonomyHandler", () => { }); const ctx = makeCtx({ _id: "req-1", + observations: ["dep_removed"], run: { - observations: ["dep_removed"], turns: [{ iteration: 1, snapshotUrl: "s://1", atifUrl: "a://1" }], }, }); @@ -67,14 +81,14 @@ describe("TaxonomyHandler", () => { it("skips iterations without a snapshotUrl", async () => { judge.evaluate.mockResolvedValue({ passed: true, feedback: "", criteriaResults: [] }); - const ctx = makeCtx({ _id: "req-1", run: { observations: ["c1"], turns: [{ iteration: 1 }] } }); + const ctx = makeCtx({ _id: "req-1", observations: ["c1"], run: { turns: [{ iteration: 1 }] } }); await new TaxonomyHandler(judge as unknown as JudgeClient).process(msg, ctx); expect(judge.evaluate).not.toHaveBeenCalled(); }); it("throws on judge infrastructure error so the handler is marked failed", async () => { judge.evaluate.mockRejectedValue(new JudgeInfrastructureError("down", { httpStatus: 503 })); - const ctx = makeCtx({ _id: "req-1", run: { observations: ["c1"], turns: [{ iteration: 1, snapshotUrl: "s://1" }] } }); + const ctx = makeCtx({ _id: "req-1", observations: ["c1"], run: { turns: [{ iteration: 1, snapshotUrl: "s://1" }] } }); await expect(new TaxonomyHandler(judge as unknown as JudgeClient).process(msg, ctx)).rejects.toThrow("down"); }); }); diff --git a/apps/workers/post-processor/src/handlers/taxonomy-handler.ts b/apps/workers/post-processor/src/handlers/taxonomy-handler.ts index 3701c4cd8..571320317 100644 --- a/apps/workers/post-processor/src/handlers/taxonomy-handler.ts +++ b/apps/workers/post-processor/src/handlers/taxonomy-handler.ts @@ -5,11 +5,14 @@ import { JudgeClient, isRetryableJudgeError } from "shared"; import type { ConversationTurn, CriterionResult } from "shared"; import type { PostProcessHandler, PostProcessorMessage, HandlerContext } from "../types.js"; -/** Minimal shape of the run document fields this handler reads/writes. */ -interface RunDoc { +/** Minimal shape of the request document fields this handler reads/writes. */ +interface RequestDoc { + /** Observation-criteria ids selected at submit. Stored at the request + * top-level by the API (see RequestDocument.observations / issue #1156), + * NOT under `run` — the run subdocument only carries per-turn results. */ + observations?: string[]; run?: { _id?: string; - observations?: string[]; turns?: ConversationTurn[]; }; } @@ -18,11 +21,11 @@ interface RunDoc { * Taxonomy Handler (pp-taxonomy): records per-iteration boolean observations. * * For each iteration turn with a `snapshotUrl`, reuses the judge service to - * evaluate the run's selected observation criteria (`run.observations`) against - * the codebase snapshot AND the agent trajectory (ATIF) — sending `atifUrl` in - * place of `toolCallsUrl`. Results are written to `turn.observationResults`, - * mirroring gate `criteriaResults`. Never gates, never steers the agent. - * Empty/absent `observations` → no-op. See issue #1156. + * evaluate the run's selected observation criteria (top-level + * `request.observations`) against the codebase snapshot AND the agent + * trajectory (ATIF) — sending `atifUrl` in place of `toolCallsUrl`. Results are + * written to `turn.observationResults`, mirroring gate `criteriaResults`. Never + * gates, never steers the agent. Empty/absent `observations` → no-op. #1156. */ export class TaxonomyHandler implements PostProcessHandler { readonly type = "taxonomy"; @@ -35,8 +38,8 @@ export class TaxonomyHandler implements PostProcessHandler { async process(message: PostProcessorMessage, ctx: HandlerContext): Promise { const { requestId, iteration } = message; - const doc = (await ctx.collection.findOne({ _id: requestId } as any)) as RunDoc | null; - const observations = doc?.run?.observations ?? []; + const doc = (await ctx.collection.findOne({ _id: requestId } as any)) as RequestDoc | null; + const observations = doc?.observations ?? []; const turns = doc?.run?.turns ?? []; if (observations.length === 0) { From f689b013948c7ded948812dc2a63ebdc9336f004 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Mon, 29 Jun 2026 14:34:20 -0700 Subject: [PATCH 017/210] feat(portal): rename run-detail Observations tab to Taxonomy with Observations subsection The run-detail tab is now labeled "Taxonomy" and its content nests an "Observations" sub-section (heading + description) around the per-dimension ObservationResultsPanel, so the tab can host the broader taxonomy view with observations as one section within it. The internal tab value stays "observations" to preserve routing/state. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- apps/portal/src/pages/RunDetail.tsx | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/apps/portal/src/pages/RunDetail.tsx b/apps/portal/src/pages/RunDetail.tsx index 12308f173..74a1e9623 100644 --- a/apps/portal/src/pages/RunDetail.tsx +++ b/apps/portal/src/pages/RunDetail.tsx @@ -962,7 +962,7 @@ export function RunDetail() { {hasVideoData && } {(hasConfiguredObservations || hasObservationResults) && ( - Observations {hasObservationResults ? `(${activeRun?.turns?.reduce((count, turn) => count + (turn.observationResults?.length ?? 0), 0) ?? 0})` : ""} + Taxonomy {hasObservationResults ? `(${activeRun?.turns?.reduce((count, turn) => count + (turn.observationResults?.length ?? 0), 0) ?? 0})` : ""} )} Logs @@ -1061,8 +1061,16 @@ export function RunDetail() { )} {(hasConfiguredObservations || hasObservationResults) && ( - - + +
+
+

Observations

+

+ Per-iteration boolean observations recorded over the codebase and agent trajectory, grouped by taxonomy dimension. Non-gating — they never steer the agent. +

+
+ +
)} From 85eb446ea525af152305e935ff85563be55589a5 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Mon, 29 Jun 2026 14:53:11 -0700 Subject: [PATCH 018/210] fix(portal): aggregate Enrichment badge over handler DAG + rename observations tab URL to taxonomy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Enrichment badge read the legacy single `run.postProcessorStatus` scalar, which every post-processor handler overwrites on its own success. It therefore flipped to "Enriched" as soon as pp-atif finished, while pp-taxonomy was still computing observations. Derive an aggregate enrichment status from `run.handlerStatus` (the #1147 per-handler DAG state): stay "Enriching…" until every handler is terminal, treating pp-taxonomy as pending whenever observations are configured (which also covers the gap before the scheduler dispatches it). Use the derived status for both badge placements and the detail poller so taxonomy results auto-appear. Falls back to the legacy scalar for pre-DAG runs. Also rename the run-detail tab slug "observations" -> "taxonomy" so the URL reads /runs/:id/taxonomy, with an in-place redirect for legacy /observations deep-links. Proven live on the containerized stack: a real run held "Enriching…" from pp-atif done (legacy scalar already "done") through pp-taxonomy queued, and flipped to "Enriched" only once pp-taxonomy completed ~32s later. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- apps/portal/src/lib/enrichment.test.ts | 92 ++++++++++++++++++++++++++ apps/portal/src/lib/enrichment.ts | 48 ++++++++++++++ apps/portal/src/pages/RunDetail.tsx | 31 +++++++-- apps/portal/src/types.ts | 19 ++++++ 4 files changed, 183 insertions(+), 7 deletions(-) create mode 100644 apps/portal/src/lib/enrichment.test.ts create mode 100644 apps/portal/src/lib/enrichment.ts diff --git a/apps/portal/src/lib/enrichment.test.ts b/apps/portal/src/lib/enrichment.test.ts new file mode 100644 index 000000000..879bc5b11 --- /dev/null +++ b/apps/portal/src/lib/enrichment.test.ts @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { describe, expect, it } from "vitest"; +import { deriveEnrichmentStatus } from "./enrichment"; +import type { RunState } from "@/types"; + +function makeRun(partial: Partial): RunState { + return { _id: "r1", attemptNumber: 1, status: "done", ...partial } as RunState; +} + +describe("deriveEnrichmentStatus", () => { + it("returns undefined when there is no run", () => { + expect(deriveEnrichmentStatus(undefined, false)).toBeUndefined(); + }); + + it("falls back to the legacy scalar for runs without a handler DAG", () => { + expect(deriveEnrichmentStatus(makeRun({ postProcessorStatus: "done" }), false)).toBe("done"); + expect(deriveEnrichmentStatus(makeRun({ postProcessorStatus: "processing" }), true)).toBe("processing"); + expect(deriveEnrichmentStatus(makeRun({ handlerStatus: {} }), false)).toBeUndefined(); + }); + + it("stays processing while pp-atif is still running", () => { + const run = makeRun({ handlerStatus: { "pp-atif": { status: "processing" } } }); + expect(deriveEnrichmentStatus(run, false)).toBe("processing"); + }); + + it("reports done once the only handler (pp-atif) is done and no observations are configured", () => { + const run = makeRun({ + postProcessorStatus: "done", + handlerStatus: { "pp-atif": { status: "done" } }, + }); + expect(deriveEnrichmentStatus(run, false)).toBe("done"); + }); + + it("does NOT flip to done after pp-atif while pp-taxonomy is still pending (the bug)", () => { + // Observations configured, pp-atif done, pp-taxonomy not yet dispatched. + const beforeDispatch = makeRun({ + postProcessorStatus: "done", // legacy scalar already flipped — must be ignored + handlerStatus: { "pp-atif": { status: "done" } }, + }); + expect(deriveEnrichmentStatus(beforeDispatch, true)).toBe("processing"); + + // pp-taxonomy queued. + const queued = makeRun({ + postProcessorStatus: "done", + handlerStatus: { "pp-atif": { status: "done" }, "pp-taxonomy": { status: "queued" } }, + }); + expect(deriveEnrichmentStatus(queued, true)).toBe("processing"); + + // pp-taxonomy processing. + const processing = makeRun({ + postProcessorStatus: "done", + handlerStatus: { "pp-atif": { status: "done" }, "pp-taxonomy": { status: "processing" } }, + }); + expect(deriveEnrichmentStatus(processing, true)).toBe("processing"); + }); + + it("flips to done only once both pp-atif and pp-taxonomy are done", () => { + const run = makeRun({ + handlerStatus: { "pp-atif": { status: "done" }, "pp-taxonomy": { status: "done" } }, + }); + expect(deriveEnrichmentStatus(run, true)).toBe("done"); + }); + + it("reports failed when a handler failed and nothing is still in flight", () => { + const run = makeRun({ + handlerStatus: { "pp-atif": { status: "done" }, "pp-taxonomy": { status: "failed" } }, + }); + expect(deriveEnrichmentStatus(run, true)).toBe("failed"); + }); + + it("prefers processing over failed while another handler is still running", () => { + const run = makeRun({ + handlerStatus: { "pp-atif": { status: "processing" }, "pp-taxonomy": { status: "failed" } }, + }); + expect(deriveEnrichmentStatus(run, true)).toBe("processing"); + }); + + it("treats a no-op pp-taxonomy (no observations) as part of the DAG", () => { + // No observations configured, but pp-taxonomy still runs as a no-op handler. + const stillRunning = makeRun({ + handlerStatus: { "pp-atif": { status: "done" }, "pp-taxonomy": { status: "processing" } }, + }); + expect(deriveEnrichmentStatus(stillRunning, false)).toBe("processing"); + + const allDone = makeRun({ + handlerStatus: { "pp-atif": { status: "done" }, "pp-taxonomy": { status: "done" } }, + }); + expect(deriveEnrichmentStatus(allDone, false)).toBe("done"); + }); +}); diff --git a/apps/portal/src/lib/enrichment.ts b/apps/portal/src/lib/enrichment.ts new file mode 100644 index 000000000..99f5bfebc --- /dev/null +++ b/apps/portal/src/lib/enrichment.ts @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import type { RunState } from "@/types"; + +export type PostProcessorStatus = "queued" | "processing" | "done" | "failed"; + +/** + * Derive the aggregate enrichment status across the whole post-processing + * handler DAG (issue #1147), rather than trusting the legacy single + * `postProcessorStatus` scalar. + * + * Each post-processor handler overwrites that scalar on its own completion, so + * it flips to "done" as soon as the FIRST handler (pp-atif) finishes — even + * while pp-taxonomy is still computing observations. The "Enriched" badge (and + * the run-detail poller) must instead stay "Enriching…" until every handler in + * the DAG is terminal. + * + * Known topology: pp-atif always runs; pp-taxonomy is expected whenever the run + * has configured observations. We treat taxonomy as still-pending until + * pp-taxonomy reaches a terminal state, which also covers the brief window + * after pp-atif finishes but before the scheduler has dispatched pp-taxonomy + * (so it isn't yet present in `handlerStatus`). + * + * Falls back to the legacy `postProcessorStatus` scalar for runs that predate + * the handler DAG (no `handlerStatus` map). + */ +export function deriveEnrichmentStatus( + run: RunState | undefined, + hasConfiguredObservations: boolean, +): PostProcessorStatus | undefined { + if (!run) return undefined; + const handlerStatus = run.handlerStatus; + // Legacy runs predating the handler DAG only carry the scalar field. + if (!handlerStatus || Object.keys(handlerStatus).length === 0) { + return run.postProcessorStatus; + } + const statuses = Object.values(handlerStatus).map((h) => h?.status); + const taxonomyStatus = handlerStatus["pp-taxonomy"]?.status; + const taxonomyPending = + hasConfiguredObservations && taxonomyStatus !== "done" && taxonomyStatus !== "failed"; + if (taxonomyPending || statuses.some((s) => s === "queued" || s === "processing")) { + return "processing"; + } + if (statuses.some((s) => s === "failed")) return "failed"; + if (statuses.length > 0 && statuses.every((s) => s === "done")) return "done"; + return run.postProcessorStatus; +} diff --git a/apps/portal/src/pages/RunDetail.tsx b/apps/portal/src/pages/RunDetail.tsx index 74a1e9623..2b058d107 100644 --- a/apps/portal/src/pages/RunDetail.tsx +++ b/apps/portal/src/pages/RunDetail.tsx @@ -51,6 +51,7 @@ import { } from "@/types"; import { useShiftModifier } from "@/hooks/useShiftModifier"; import { getRetryButtonState } from "@/components/RetryButton"; +import { deriveEnrichmentStatus } from "@/lib/enrichment"; /** A compact labeled stat: a micro uppercase label above its value. */ function MetaItem({ label, value, title }: { label: string; value: ReactNode; title?: string }) { @@ -314,10 +315,10 @@ export function RunDetail() { refetchInterval: (query) => { const data = query.state.data; const status = data?.run?.status; - const ppStatus = data?.run?.postProcessorStatus; // Keep polling while run is in progress OR post-processing is pending/in-progress if (status !== "done") return 5_000; - if (ppStatus && ppStatus !== "done" && ppStatus !== "failed") return 5_000; + const enrichment = deriveEnrichmentStatus(data?.run, (data?.observations?.length ?? 0) > 0); + if (enrichment && enrichment !== "done" && enrichment !== "failed") return 5_000; return false; }, }); @@ -354,6 +355,16 @@ export function RunDetail() { }, [selectedRunId, run?.run, attempts]); const isViewingHistorical = !!selectedRunId && selectedRunId !== run?.run?._id; + // The "observations" tab was renamed to "taxonomy". Map the legacy slug to the + // new one for tab selection, and rewrite stale `/observations` URLs in place + // so deep-links and bookmarks keep working. + const normalizedTab = tab === "observations" ? "taxonomy" : tab; + useEffect(() => { + if (tab === "observations") { + navigate(`/runs/${id}/taxonomy${selectedRunId ? `?runId=${selectedRunId}` : ""}`, { replace: true }); + } + }, [tab, id, selectedRunId, navigate]); + const isActive = activeRun?.status === "pending" || activeRun?.status === "processing"; // Note: "done" is terminal — not active, no log streaming needed @@ -394,6 +405,12 @@ export function RunDetail() { const hasObservationResults = (activeRun?.turns ?? []).some((turn) => (turn.observationResults?.length ?? 0) > 0); const hasConfiguredObservations = (run?.observations?.length ?? 0) > 0; + // Aggregate enrichment status across the whole post-processing DAG so the + // "Enriched" badge waits for pp-taxonomy instead of flipping after pp-atif. + const enrichmentStatus = useMemo( + () => deriveEnrichmentStatus(activeRun, hasConfiguredObservations), + [activeRun, hasConfiguredObservations], + ); const { data: observationCriteria = [] } = useQuery({ queryKey: ["criteria", "observations", run?.observations], queryFn: () => api.listCriteria(undefined, run?.observations?.length ? { ids: run.observations } : undefined), @@ -673,7 +690,7 @@ export function RunDetail() { /> {activeRun?.status === "done" && } {activeRun?.status === "done" && ( - + )}
@@ -947,7 +964,7 @@ export function RunDetail() { {/* Tabs */} 0 ? "turns" : "logs")} + value={normalizedTab || (activeRun?.status === "done" && activeRun?.turns && activeRun.turns.length > 0 ? "turns" : "logs")} onValueChange={(value) => navigate(`/runs/${id}/${value}${selectedRunId ? `?runId=${selectedRunId}` : ""}`)} > @@ -961,7 +978,7 @@ export function RunDetail() { {hasHarData && Tool Calls} {hasVideoData && } {(hasConfiguredObservations || hasObservationResults) && ( - + Taxonomy {hasObservationResults ? `(${activeRun?.turns?.reduce((count, turn) => count + (turn.observationResults?.length ?? 0), 0) ?? 0})` : ""} )} @@ -1061,7 +1078,7 @@ export function RunDetail() { )} {(hasConfiguredObservations || hasObservationResults) && ( - +

Observations

@@ -1447,7 +1464,7 @@ export function RunDetail() {
Status:{" "} - +
{activeRun.postProcessorVersion !== undefined && (
diff --git a/apps/portal/src/types.ts b/apps/portal/src/types.ts index 079ef7b2d..a7a6b2ec2 100644 --- a/apps/portal/src/types.ts +++ b/apps/portal/src/types.ts @@ -114,6 +114,17 @@ export interface OsInfo { arch: string; } +/** + * Per-handler post-processing status in the DAG (issue #1147). Keys in + * `RunState.handlerStatus` are handler IDs (e.g. "pp-atif", "pp-taxonomy"). + */ +export interface HandlerRunStatus { + status: "queued" | "processing" | "done" | "failed"; + version?: number; + updatedAt?: string; + error?: string; +} + /** * Per-attempt mutable state (nested under `Run.run` in API responses since * migration 014). Fields here change as a single attempt progresses; fields @@ -148,6 +159,14 @@ export interface RunState { resumedAt?: string; postProcessorVersion?: number; postProcessorStatus?: "queued" | "processing" | "done" | "failed"; + /** + * Per-handler post-processing status keyed by handler ID (e.g. "pp-atif", + * "pp-taxonomy"). Drives the aggregate "Enriched" badge so it only flips to + * done once every handler in the DAG is terminal — not after the first + * handler (pp-atif) completes. The legacy `postProcessorStatus` scalar only + * tracks pp-atif and is kept for backward compatibility. + */ + handlerStatus?: Record; } export interface Run { From 84f6e7b5ba8da87f4caafa034ff603a5ccfcc268 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Mon, 29 Jun 2026 17:31:27 -0700 Subject: [PATCH 019/210] fix(judge): unify trajectory navigation into one source-agnostic tool set (#1156 P10) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes a non-deterministic false negative on trajectory observations (e.g. `dependency_added_then_removed`): pp-taxonomy fed the judge the entire ~86 KB ATIF as ONE opaque synthetic tool call, so `read_tool_outputs`' 2000-char preview only ever showed the ~26 KB system prompt and the mid-run npm calls were buried tens of KB deep — the LLM found them only by luck. Replace the opaque blob + the two legacy tools (`read_tool_outputs`/ `get_tool_output`) with ONE normalized `AgentTrajectory` model and a unified, source-agnostic tool set used by BOTH gates (HAR `ToolCall[]`) and observations (parsed ATIF): - new `agent-trajectory.ts`: `fromToolCalls`/`fromAtif` normalizers + five `defineTool`s — two symmetric pairs (definitions: `list_agent_tools`/ `get_agent_tools`; calls: `list_agent_tool_calls`/`get_agent_tool_calls`) plus `get_trajectory_overview`. Outputs larger than INLINE_LIMIT (16 KB) spill to a per-evaluation temp dir created OUTSIDE the workspace and are returned as an absolute `responseFile`/`descriptionFile` the judge reads with `read_file`. - `index.ts`: build the trajectory at the `/evaluate` boundary (ATIF wins as superset; tool-calls otherwise); non-fatal on load failure. - `judge-strategies.ts`: thread `trajectory` through both strategies; extend `createFileTools` with `extraReadRoots` (read_file/file_exists may read the out-of-workspace spill dir; list_directory/search_files stay workspace-only); create+cleanup the spill dir in `runCopilotSession`; swap TOOL_OUTPUTS_GUIDANCE → TRAJECTORY_GUIDANCE. Gate-parity guard preserved (`trajectory.calls.length > 0`). - `judge-agent.ts`: `EvaluationInput.toolCalls` → `trajectory?`. Tests: new `agent-trajectory.test.ts` (normalizers, 5 tools, out-of-workspace spill, strict-superset-over-HAR contract); `judge-strategies.test.ts` (isWithinAnyRoot + extraReadRoots + new guidance/tool names); `observation-trajectory.integration.test.ts` rewritten to pass `fromAtif(...)`; `judge-evaluation.integration.test.ts` extended with a gate clear-PASS/clear-FAIL regression guard built from `fromToolCalls(...)`. Verified live on the containerized stack: the same observation that flipped non-deterministically now resolves passed:true 5/5 WITH the ATIF and false 3/3 WITHOUT it, citing `npm install left-pad` / `npm uninstall left-pad`. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- apps/judge/src/agent-trajectory.test.ts | 446 ++++++++++++++ apps/judge/src/agent-trajectory.ts | 544 ++++++++++++++++++ apps/judge/src/index.ts | 53 +- apps/judge/src/judge-agent.ts | 10 +- .../src/judge-evaluation.integration.test.ts | 93 +++ apps/judge/src/judge-strategies.test.ts | 204 ++++--- apps/judge/src/judge-strategies.ts | 256 ++++----- ...observation-trajectory.integration.test.ts | 120 +++- 8 files changed, 1461 insertions(+), 265 deletions(-) create mode 100644 apps/judge/src/agent-trajectory.test.ts create mode 100644 apps/judge/src/agent-trajectory.ts diff --git a/apps/judge/src/agent-trajectory.test.ts b/apps/judge/src/agent-trajectory.test.ts new file mode 100644 index 000000000..78252d88f --- /dev/null +++ b/apps/judge/src/agent-trajectory.test.ts @@ -0,0 +1,446 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * Unit tests for the source-agnostic agent-trajectory model (issue #1156, P10). + * + * Covers both normalizers (`fromAtif` for the observation/ATIF path, `fromToolCalls` + * for the gate/HAR path), the five unified navigation tools, the out-of-workspace + * spill behaviour for oversized outputs, and the strict-superset contract that the + * new tools expose everything the removed `read_tool_outputs`/`get_tool_output` + * pair did. + */ +import { describe, it, expect, beforeAll, afterAll } from "vitest"; +import { mkdtempSync, mkdirSync, rmSync, existsSync, readFileSync } from "fs"; +import { tmpdir } from "os"; +import { join, sep } from "path"; +import type { ToolCall } from "shared"; +import { + fromAtif, + fromToolCalls, + createTrajectoryTools, + summarizeArgs, + safeId, + previewOf, + INLINE_LIMIT, + type AgentTrajectory, +} from "./agent-trajectory.js"; + +const stubInvocation = { + sessionId: "test-session", + toolCallId: "test-call", + toolName: "test-tool", + arguments: {}, +}; + +/** Invoke a trajectory tool's handler by name. */ +async function call( + tools: ReturnType, + name: string, + args: Record = {} +): Promise { + const tool = tools.find((t) => t.name === name); + if (!tool?.handler) throw new Error(`tool ${name} not found`); + return (tool.handler as (a: unknown, b: unknown) => unknown)(args, stubInvocation); +} + +/** + * Realistic ATIF blob: system + user step, then agent steps that install, + * use, and uninstall `left-pad`. Mirrors the real ATIF shape pp-taxonomy + * downloads (steps carry their own tool_calls AND the matching + * observation.results, paired by source_call_id === tool_call_id). + */ +const REALISTIC_ATIF = { + schema_version: "atif/1", + session_id: "fixture", + agent: { + name: "copilot", + version: "1.0.0", + model_name: "claude-opus-4.6", + tool_definitions: [ + { + type: "function", + function: { + name: "bash", + description: "Run a shell command.", + parameters: { type: "object", properties: { command: { type: "string" } } }, + }, + }, + { + type: "function", + function: { name: "view", description: "View a file.", parameters: { type: "object" } }, + }, + { + type: "function", + function: { name: "edit", description: "Edit a file." }, + }, + // Nameless definition — must be dropped. + { type: "function", function: { description: "no name" } }, + ], + }, + steps: [ + { step_id: 1, source: "system" }, + { step_id: 2, source: "user" }, + { + step_id: 3, + source: "agent", + model_name: "claude-opus-4.6", + reasoning_content: "Add left-pad.", + tool_calls: [{ tool_call_id: "call-1", function_name: "bash", arguments: { command: "npm install left-pad" } }], + observation: { results: [{ source_call_id: "call-1", content: "added 1 package\n+ left-pad@1.3.0" }] }, + }, + { + step_id: 4, + source: "agent", + tool_calls: [{ tool_call_id: "call-2", function_name: "edit", arguments: { path: "index.js" } }], + // ContentPart[] form of observation content. + observation: { + results: [ + { source_call_id: "call-2", content: [{ type: "text", text: "edited " }, { type: "text", text: "index.js" }] }, + ], + }, + }, + { + step_id: 5, + source: "agent", + reasoning_content: "Remove left-pad.", + tool_calls: [{ tool_call_id: "call-3", function_name: "bash", arguments: { command: "npm uninstall left-pad" } }], + observation: { results: [{ source_call_id: "call-3", content: "removed 1 package" }] }, + }, + ], + final_metrics: { steps: 5 }, +}; + +describe("fromAtif", () => { + const traj = fromAtif(REALISTIC_ATIF); + + it("flattens only agent tool calls, keyed by tool_call_id", () => { + expect(traj.source).toBe("atif"); + expect(traj.calls.map((c) => c.toolCallId)).toEqual(["call-1", "call-2", "call-3"]); + expect(traj.byId.get("call-1")!.name).toBe("bash"); + expect(traj.byId.get("call-1")!.summary).toBe("npm install left-pad"); + }); + + it("excludes system/user steps from calls but records them in steps overview", () => { + expect(traj.steps?.map((s) => s.source)).toEqual(["system", "user", "agent", "agent", "agent"]); + // No call carries the system prompt text. + expect(traj.calls.every((c) => c.step && c.step >= 3)).toBe(true); + }); + + it("matches each call's response from the same-step observation result", () => { + expect(traj.byId.get("call-1")!.response).toContain("left-pad@1.3.0"); + expect(traj.byId.get("call-3")!.response).toBe("removed 1 package"); + }); + + it("coerces ContentPart[] observation content into joined text", () => { + expect(traj.byId.get("call-2")!.response).toBe("edited index.js"); + }); + + it("captures per-step reasoning on the calls", () => { + expect(traj.byId.get("call-1")!.reasoning).toBe("Add left-pad."); + expect(traj.byId.get("call-3")!.reasoning).toBe("Remove left-pad."); + }); + + it("reads agent + model metadata", () => { + expect(traj.agent).toBe("copilot"); + expect(traj.model).toBe("claude-opus-4.6"); + expect(traj.finalMetrics).toEqual({ steps: 5 }); + }); + + it("populates tool definitions from agent.tool_definitions, dropping nameless ones", () => { + expect(traj.toolDefinitions.map((d) => d.name)).toEqual(["bash", "view", "edit"]); + expect(traj.toolDefsByName.get("bash")!.description).toBe("Run a shell command."); + }); + + it("parses a JSON string input", () => { + const fromString = fromAtif(JSON.stringify(REALISTIC_ATIF)); + expect(fromString.calls.map((c) => c.toolCallId)).toEqual(["call-1", "call-2", "call-3"]); + }); + + it("unwraps a { trajectory: … } wrapper", () => { + const wrapped = fromAtif({ trajectory: REALISTIC_ATIF }); + expect(wrapped.calls).toHaveLength(3); + }); + + it("returns an empty trajectory for garbage / empty input", () => { + expect(fromAtif("not json").calls).toEqual([]); + expect(fromAtif(null).calls).toEqual([]); + expect(fromAtif({}).calls).toEqual([]); + expect(fromAtif(42).calls).toEqual([]); + }); + + it("synthesizes an id for a tool call missing tool_call_id", () => { + const traj2 = fromAtif({ + steps: [ + { + step_id: 7, + source: "agent", + tool_calls: [{ function_name: "bash", arguments: { command: "ls" } }], + }, + ], + }); + expect(traj2.calls).toHaveLength(1); + expect(traj2.calls[0].toolCallId).toBe("atif-7-0"); + }); +}); + +describe("fromToolCalls (HAR / gate path)", () => { + const harCalls: ToolCall[] = [ + { id: "h1", name: "bash", arguments: { command: "npm run build" }, response: "build ok", timestamp: "" }, + { id: "h2", name: "view", arguments: { path: "server.js" }, response: "file contents", timestamp: "" }, + ]; + const traj = fromToolCalls(harCalls); + + it("maps each HAR ToolCall to an AgentToolCall keyed by id", () => { + expect(traj.source).toBe("tool-calls"); + expect(traj.calls.map((c) => c.toolCallId)).toEqual(["h1", "h2"]); + expect(traj.byId.get("h1")!.response).toBe("build ok"); + expect(traj.byId.get("h1")!.summary).toBe("npm run build"); + }); + + it("has no tool catalog (HAR carries no definitions)", () => { + expect(traj.toolDefinitions).toEqual([]); + expect(traj.steps).toBeUndefined(); + }); + + it("synthesizes positional ids when a HAR call has none", () => { + const t = fromToolCalls([{ id: "", name: "bash", arguments: {}, response: "x", timestamp: "" }]); + expect(t.calls[0].toolCallId).toBe("call-0"); + }); + + it("handles undefined input", () => { + expect(fromToolCalls(undefined).calls).toEqual([]); + }); +}); + +describe("createTrajectoryTools — calls pair (list/get)", () => { + let spillRoot: string; + const traj = fromAtif(REALISTIC_ATIF); + + beforeAll(() => { + spillRoot = mkdtempSync(join(tmpdir(), "traj-spill-")); + }); + afterAll(() => rmSync(spillRoot, { recursive: true, force: true })); + + it("list_agent_tool_calls returns a triage index of every call", async () => { + const tools = createTrajectoryTools(traj, spillRoot); + const res = await call(tools, "list_agent_tool_calls"); + expect(res.count).toBe(3); + expect(res.calls.map((c: any) => c.toolCallId)).toEqual(["call-1", "call-2", "call-3"]); + expect(res.calls[0]).toMatchObject({ name: "bash", step: 3, summary: "npm install left-pad" }); + expect(res.calls[0].responseLength).toBeGreaterThan(0); + }); + + it("get_agent_tool_calls returns full details for requested ids and reports notFound", async () => { + const tools = createTrajectoryTools(traj, spillRoot); + const res = await call(tools, "get_agent_tool_calls", { toolCallIds: ["call-1", "nope"] }); + expect(res.notFound).toEqual(["nope"]); + expect(res.calls).toHaveLength(1); + expect(res.calls[0]).toMatchObject({ + toolCallId: "call-1", + name: "bash", + arguments: { command: "npm install left-pad" }, + reasoning: "Add left-pad.", + }); + expect(res.calls[0].response).toContain("left-pad@1.3.0"); + }); + + it("empty trajectory → list returns count 0 with a message", async () => { + const tools = createTrajectoryTools(fromAtif({}), spillRoot); + const res = await call(tools, "list_agent_tool_calls"); + expect(res).toMatchObject({ count: 0, calls: [] }); + expect(res.message).toBeTruthy(); + }); +}); + +describe("createTrajectoryTools — oversized output spills OUTSIDE the workspace", () => { + let parent: string; + let workspace: string; + let spillDir: string; + const bigOutput = "X".repeat(INLINE_LIMIT + 5000); + + // A trajectory whose single call has an output larger than INLINE_LIMIT. + const bigTraj: AgentTrajectory = fromAtif({ + steps: [ + { + step_id: 3, + source: "agent", + tool_calls: [{ tool_call_id: "big-1", function_name: "bash", arguments: { command: "cat huge.log" } }], + observation: { results: [{ source_call_id: "big-1", content: bigOutput }] }, + }, + ], + }); + + beforeAll(() => { + parent = mkdtempSync(join(tmpdir(), "traj-ws-parent-")); + workspace = join(parent, "workspace"); + spillDir = join(parent, "spill"); + mkdirSync(workspace, { recursive: true }); + }); + afterAll(() => rmSync(parent, { recursive: true, force: true })); + + it("writes the full output to a spill file outside the workspace and omits the inline response", async () => { + const tools = createTrajectoryTools(bigTraj, spillDir); + const res = await call(tools, "get_agent_tool_calls", { toolCallIds: ["big-1"] }); + const one = res.calls[0]; + + // No inline blob — only a preview + a file pointer. + expect(one.response).toBeUndefined(); + expect(one.responsePreview).toBeTruthy(); + expect(one.responseLength).toBe(bigOutput.length); + + // The spill file is real, holds the FULL output, and lives OUTSIDE the workspace. + expect(typeof one.responseFile).toBe("string"); + expect(existsSync(one.responseFile)).toBe(true); + expect(readFileSync(one.responseFile, "utf-8")).toBe(bigOutput); + expect(one.responseFile.startsWith(workspace + sep)).toBe(false); + expect(one.responseFile.startsWith(spillDir)).toBe(true); + }); + + it("keeps a small output inline (no spill file)", async () => { + const smallTraj = fromAtif({ + steps: [ + { + step_id: 3, + source: "agent", + tool_calls: [{ tool_call_id: "s1", function_name: "bash", arguments: { command: "echo hi" } }], + observation: { results: [{ source_call_id: "s1", content: "hi" }] }, + }, + ], + }); + const tools = createTrajectoryTools(smallTraj, spillDir); + const res = await call(tools, "get_agent_tool_calls", { toolCallIds: ["s1"] }); + expect(res.calls[0].response).toBe("hi"); + expect(res.calls[0].responseFile).toBeUndefined(); + }); +}); + +describe("createTrajectoryTools — definitions pair (list/get)", () => { + let spillDir: string; + const traj = fromAtif(REALISTIC_ATIF); + + beforeAll(() => { + spillDir = mkdtempSync(join(tmpdir(), "traj-defs-")); + }); + afterAll(() => rmSync(spillDir, { recursive: true, force: true })); + + it("list_agent_tools returns the agent's tool catalog", async () => { + const tools = createTrajectoryTools(traj, spillDir); + const res = await call(tools, "list_agent_tools"); + expect(res.count).toBe(3); + expect(res.tools.map((t: any) => t.name)).toEqual(["bash", "view", "edit"]); + const bash = res.tools.find((t: any) => t.name === "bash"); + expect(bash).toMatchObject({ type: "function", hasParameters: true }); + expect(bash.descriptionLength).toBeGreaterThan(0); + }); + + it("get_agent_tools returns full definition + parameters and reports notFound", async () => { + const tools = createTrajectoryTools(traj, spillDir); + const res = await call(tools, "get_agent_tools", { toolNames: ["bash", "ghost"] }); + expect(res.notFound).toEqual(["ghost"]); + expect(res.tools).toHaveLength(1); + expect(res.tools[0]).toMatchObject({ + name: "bash", + type: "function", + description: "Run a shell command.", + }); + expect(res.tools[0].parameters).toMatchObject({ type: "object" }); + }); + + it("on the HAR/gate path the catalog is empty (count 0)", async () => { + const tools = createTrajectoryTools(fromToolCalls([]), spillDir); + const res = await call(tools, "list_agent_tools"); + expect(res).toMatchObject({ count: 0, tools: [] }); + }); + + it("spills a very long tool description to a descriptionFile outside the workspace", async () => { + const bigDesc = "D".repeat(INLINE_LIMIT + 1000); + const t = fromAtif({ + agent: { tool_definitions: [{ type: "function", function: { name: "huge", description: bigDesc } }] }, + steps: [], + }); + const tools = createTrajectoryTools(t, spillDir); + const res = await call(tools, "get_agent_tools", { toolNames: ["huge"] }); + const def = res.tools[0]; + expect(def.description).toBeUndefined(); + expect(def.descriptionPreview).toBeTruthy(); + expect(existsSync(def.descriptionFile)).toBe(true); + expect(readFileSync(def.descriptionFile, "utf-8")).toBe(bigDesc); + }); +}); + +describe("get_trajectory_overview", () => { + it("summarizes the run without the system-prompt blob", async () => { + const spillDir = mkdtempSync(join(tmpdir(), "traj-ov-")); + try { + const tools = createTrajectoryTools(fromAtif(REALISTIC_ATIF), spillDir); + const res = await call(tools, "get_trajectory_overview"); + expect(res).toMatchObject({ + source: "atif", + agent: "copilot", + model: "claude-opus-4.6", + totalTools: 3, + totalCalls: 3, + }); + expect(res.steps).toHaveLength(5); + } finally { + rmSync(spillDir, { recursive: true, force: true }); + } + }); +}); + +describe("strict-superset contract over the HAR path (replaces read_tool_outputs/get_tool_output)", () => { + // The new tools must expose everything the removed pair did: list every call, + // and return each call's FULL response — for large outputs via a spill file + // whose content equals the full response. + let spillDir: string; + const bigResponse = "Z".repeat(INLINE_LIMIT + 2000); + const harCalls: ToolCall[] = [ + { id: "g1", name: "bash", arguments: { command: "npm run build" }, response: "build succeeded", timestamp: "" }, + { id: "g2", name: "bash", arguments: { command: "npm test" }, response: bigResponse, timestamp: "" }, + ]; + + beforeAll(() => { + spillDir = mkdtempSync(join(tmpdir(), "traj-super-")); + }); + afterAll(() => rmSync(spillDir, { recursive: true, force: true })); + + it("list_agent_tool_calls lists every HAR call (same count + names as read_tool_outputs)", async () => { + const tools = createTrajectoryTools(fromToolCalls(harCalls), spillDir); + const res = await call(tools, "list_agent_tool_calls"); + expect(res.count).toBe(2); + expect(res.calls.map((c: any) => `${c.toolCallId}:${c.name}`)).toEqual(["g1:bash", "g2:bash"]); + }); + + it("get_agent_tool_calls returns the same full response get_tool_output would (small inline)", async () => { + const tools = createTrajectoryTools(fromToolCalls(harCalls), spillDir); + const res = await call(tools, "get_agent_tool_calls", { toolCallIds: ["g1"] }); + expect(res.calls[0].response).toBe("build succeeded"); + }); + + it("a large HAR response is spilled and the file content equals the full response", async () => { + const tools = createTrajectoryTools(fromToolCalls(harCalls), spillDir); + const res = await call(tools, "get_agent_tool_calls", { toolCallIds: ["g2"] }); + expect(res.calls[0].response).toBeUndefined(); + expect(readFileSync(res.calls[0].responseFile, "utf-8")).toBe(bigResponse); + }); +}); + +describe("helpers", () => { + it("summarizeArgs prefers command, then path/file, then pattern/url/summary, else JSON", () => { + expect(summarizeArgs("bash", { command: "ls -la" })).toBe("ls -la"); + expect(summarizeArgs("view", { path: "a/b.ts" })).toBe("a/b.ts"); + expect(summarizeArgs("search", { pattern: "TODO" })).toBe("pattern: TODO"); + expect(summarizeArgs("x", { foo: 1 })).toContain("foo"); + }); + + it("safeId slugifies the id and appends the index", () => { + expect(safeId("call/with:weird*chars", 3)).toBe("call_with_weird_chars-3"); + expect(safeId("", 0)).toBe("call-0"); + }); + + it("previewOf truncates with an ellipsis marker", () => { + expect(previewOf("abcdef", 3)).toBe("abc…"); + expect(previewOf("abc", 10)).toBe("abc"); + }); +}); diff --git a/apps/judge/src/agent-trajectory.ts b/apps/judge/src/agent-trajectory.ts new file mode 100644 index 000000000..29b20a469 --- /dev/null +++ b/apps/judge/src/agent-trajectory.ts @@ -0,0 +1,544 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * Source-agnostic model of the coding agent's captured trajectory, plus the + * read-only judge tools that expose it. Issue #1156 / scope #1125. + * + * The judge is fed the agent's work through one of two channels that are really + * the SAME thing captured at different fidelities: + * + * - GATES send the HAR-extracted `ToolCall[]` (build/test/run output) via + * `toolCallsUrl` → normalized here by {@link fromToolCalls}. + * - OBSERVATIONS (#1156) send the full ATIF trajectory via `atifUrl` → the + * normalized superset, parsed here by {@link fromAtif}. The ATIF additionally + * carries the agent's **tool definitions** (the catalog of tools it had + * available) and per-step reasoning. + * + * Both normalize into ONE in-memory {@link AgentTrajectory}, over which we expose + * ONE unified tool set ({@link createTrajectoryTools}) — two symmetric pairs: + * - DEFINITIONS — `list_agent_tools` / `get_agent_tools` (what tools existed). + * - CALLS — `list_agent_tool_calls` / `get_agent_tool_calls` (what the agent did). + * + * This REPLACES the previous opaque "stuff the 86 KB ATIF into one synthetic tool + * call" hack (apps/judge/src/index.ts) whose 2 000-char preview buried the actual + * tool calls under the ~26 KB system prompt, causing non-deterministic false + * negatives on trajectory-only observations (e.g. `dependency_added_then_removed`). + * + * Large outputs are spilled to a caller-provided directory OUTSIDE the workspace + * so they never pollute the codebase other criteria inspect; the judge reads them + * back with its existing `read_file` (which is granted that dir as an extra root). + */ +import { defineTool } from "@github/copilot-sdk"; +import { mkdirSync, writeFileSync } from "fs"; +import { join } from "path"; +import type { ToolCall } from "shared"; + +/** Max chars of a tool-call response (or tool-definition description) returned + * inline by `get_agent_tool_calls` / `get_agent_tools`. Above this the full text + * is written to the spill dir and returned as a file path instead. */ +export const INLINE_LIMIT = 16_000; + +/** Chars of the response/description retained as an at-a-glance preview. */ +export const PREVIEW_LIMIT = 500; + +/** Chars of the per-call preview surfaced by the list/triage tools. */ +export const LIST_PREVIEW_LIMIT = 200; + +/** One captured invocation the agent made (normalized across HAR and ATIF). */ +export interface AgentToolCall { + /** Stable id — the ATIF `tool_call_id` or HAR `ToolCall.id` (synthesized if absent). */ + toolCallId: string; + /** 1-based ATIF step the call was made in (undefined for the HAR/gate path). */ + step?: number; + /** Tool/function name (e.g. `bash`, `create`, `edit`). */ + name: string; + /** One-line digest of the arguments for triage. */ + summary: string; + /** Raw arguments the agent passed. */ + arguments: Record; + /** Captured output/result text. */ + response: string; + /** First {@link PREVIEW_LIMIT} chars of {@link response}. */ + responsePreview: string; + /** Full length of {@link response} in chars. */ + responseLength: number; + /** Step-level reasoning that preceded the call (ATIF only). */ + reasoning?: string; +} + +/** One entry from the agent's tool catalog (ATIF `agent.tool_definitions`). */ +export interface AgentToolDefinition { + /** Tool name — the identifier callers pass to `get_agent_tools`. */ + name: string; + /** Tool type (usually `"function"`). */ + type: string; + /** Human-readable description the agent was given. */ + description?: string; + /** JSON-schema of the tool's parameters. */ + parameters?: Record; +} + +/** Lightweight overview of one ATIF step (never the raw system-prompt text). */ +export interface StepOverview { + step: number; + source: string; + toolCallCount: number; + reasoningSummary?: string; +} + +/** Normalized, source-agnostic view of the agent's captured trajectory. */ +export interface AgentTrajectory { + source: "tool-calls" | "atif"; + agent?: string; + model?: string; + calls: AgentToolCall[]; + /** Index of {@link calls} by {@link AgentToolCall.toolCallId}. */ + byId: Map; + /** The agent's tool catalog (ATIF only; empty for the HAR/gate path). */ + toolDefinitions: AgentToolDefinition[]; + /** Index of {@link toolDefinitions} by {@link AgentToolDefinition.name}. */ + toolDefsByName: Map; + /** Per-step overview (ATIF only). */ + steps?: StepOverview[]; + /** ATIF `final_metrics`, passed through opaquely. */ + finalMetrics?: unknown; +} + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +/** First `limit` chars of `text`, with an ellipsis marker when truncated. */ +export function previewOf(text: string, limit: number = PREVIEW_LIMIT): string { + if (text.length <= limit) return text; + return text.slice(0, limit) + "…"; +} + +/** Coerce any value to a readable string (ATIF content can be string|object). */ +function asText(value: unknown): string { + if (value == null) return ""; + if (typeof value === "string") return value; + try { + return JSON.stringify(value); + } catch { + return String(value); + } +} + +/** + * Coerce ATIF observation/message content (string | ContentPart[]) into text. + * ContentPart is `{ type: "text"|"image", text?, source? }`; we keep the text + * parts and note image parts. + */ +function coerceContent(content: unknown): string { + if (content == null) return ""; + if (typeof content === "string") return content; + if (Array.isArray(content)) { + return content + .map((part) => { + if (part && typeof part === "object") { + const p = part as { type?: string; text?: string }; + if (typeof p.text === "string") return p.text; + if (p.type === "image") return "[image]"; + } + return asText(part); + }) + .join(""); + } + return asText(content); +} + +/** One-line digest of a call's arguments for triage in the list tools. */ +export function summarizeArgs(name: string, args: Record): string { + if (!args || typeof args !== "object") return ""; + const a = args as Record; + if (typeof a.command === "string") return a.command.slice(0, 200); + if (typeof a.path === "string") return a.path; + if (typeof a.file === "string") return a.file; + if (typeof a.pattern === "string") return `pattern: ${a.pattern}`; + if (typeof a.url === "string") return a.url; + if (typeof a.summary === "string") return a.summary.slice(0, 200); + const json = asText(a); + return json.length > 120 ? json.slice(0, 120) + "…" : json; +} + +/** Filesystem-safe spill filename derived from an id + its position. */ +export function safeId(id: string, index: number): string { + const slug = (id || "").replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 80); + return `${slug || "call"}-${index}`; +} + +function buildById(calls: AgentToolCall[]): Map { + const byId = new Map(); + for (const call of calls) { + // First write wins; later collisions are unreachable in practice because + // ids are unique (synthesized ids embed the position). + if (!byId.has(call.toolCallId)) byId.set(call.toolCallId, call); + } + return byId; +} + +// --------------------------------------------------------------------------- +// Normalizers +// --------------------------------------------------------------------------- + +/** + * Normalize the HAR-extracted tool calls (the gate path) into an + * {@link AgentTrajectory}. HAR carries no tool catalog or reasoning, so + * `toolDefinitions`/`steps` are empty. + */ +export function fromToolCalls(toolCalls: ToolCall[] | undefined): AgentTrajectory { + const list = Array.isArray(toolCalls) ? toolCalls : []; + const calls: AgentToolCall[] = list.map((tc, i) => { + const response = asText(tc.response ?? ""); + const args = (tc.arguments ?? {}) as Record; + const name = tc.name ?? "unknown"; + return { + toolCallId: tc.id || `call-${i}`, + name, + summary: summarizeArgs(name, args), + arguments: args, + response, + responsePreview: previewOf(response), + responseLength: response.length, + }; + }); + return { + source: "tool-calls", + calls, + byId: buildById(calls), + toolDefinitions: [], + toolDefsByName: new Map(), + }; +} + +interface AtifContentPart { + type?: string; + text?: string; +} +interface AtifToolCall { + tool_call_id?: string; + function_name?: string; + arguments?: Record; +} +interface AtifObservationResult { + source_call_id?: string; + content?: string | AtifContentPart[]; +} +interface AtifStep { + step_id?: number; + source?: string; + model_name?: string; + reasoning_content?: string; + tool_calls?: AtifToolCall[]; + observation?: { results?: AtifObservationResult[] }; +} +interface AtifToolDefinition { + type?: string; + function?: { name?: string; description?: string; parameters?: Record }; +} +interface AtifTrajectory { + agent?: { + name?: string; + version?: string; + model_name?: string; + tool_definitions?: AtifToolDefinition[]; + }; + steps?: AtifStep[]; + final_metrics?: unknown; +} + +/** Parse the raw ATIF blob defensively into an object (handles string input and + * an optional `{ trajectory: … }` wrapper). Returns `{}` on any failure. */ +function parseAtif(input: unknown): AtifTrajectory { + let obj: unknown = input; + if (typeof input === "string") { + try { + obj = JSON.parse(input); + } catch { + return {}; + } + } + if (!obj || typeof obj !== "object") return {}; + const maybeWrapped = obj as { trajectory?: unknown }; + if (maybeWrapped.trajectory && typeof maybeWrapped.trajectory === "object") { + return maybeWrapped.trajectory as AtifTrajectory; + } + return obj as AtifTrajectory; +} + +/** + * Normalize a parsed ATIF trajectory (the observation path) into an + * {@link AgentTrajectory}. Walks the steps: agent steps contribute their + * `tool_calls[]`, each paired with the matching same-step + * `observation.results[]` by `source_call_id === tool_call_id`. System and user + * steps are summarized in `steps` but never contribute calls (and their raw + * message text — including the large system prompt — is never surfaced). + */ +export function fromAtif(input: unknown): AgentTrajectory { + const traj = parseAtif(input); + const agent = traj.agent ?? {}; + const stepsArr = Array.isArray(traj.steps) ? traj.steps : []; + + const calls: AgentToolCall[] = []; + const steps: StepOverview[] = []; + let synth = 0; + let firstAgentModel: string | undefined; + + for (let i = 0; i < stepsArr.length; i++) { + const step = stepsArr[i] ?? {}; + const stepNum = typeof step.step_id === "number" ? step.step_id : i + 1; + const source = typeof step.source === "string" ? step.source : "unknown"; + const reasoning = + typeof step.reasoning_content === "string" && step.reasoning_content.length > 0 + ? step.reasoning_content + : undefined; + const stepCalls = Array.isArray(step.tool_calls) ? step.tool_calls : []; + + if (source === "agent" && !firstAgentModel && typeof step.model_name === "string") { + firstAgentModel = step.model_name; + } + + // Index this step's observation results by the call they answer. + const obsByCallId = new Map(); + const results = step.observation?.results; + if (Array.isArray(results)) { + for (const r of results) { + if (r && typeof r.source_call_id === "string") { + obsByCallId.set(r.source_call_id, coerceContent(r.content)); + } + } + } + + for (const tc of stepCalls) { + const name = typeof tc.function_name === "string" ? tc.function_name : "unknown"; + const args = (tc.arguments ?? {}) as Record; + const toolCallId = + typeof tc.tool_call_id === "string" && tc.tool_call_id.length > 0 + ? tc.tool_call_id + : `atif-${stepNum}-${synth++}`; + const response = obsByCallId.get(toolCallId) ?? ""; + calls.push({ + toolCallId, + step: stepNum, + name, + summary: summarizeArgs(name, args), + arguments: args, + response, + responsePreview: previewOf(response), + responseLength: response.length, + reasoning, + }); + } + + steps.push({ + step: stepNum, + source, + toolCallCount: stepCalls.length, + reasoningSummary: reasoning ? previewOf(reasoning, LIST_PREVIEW_LIMIT) : undefined, + }); + } + + const defs = Array.isArray(agent.tool_definitions) ? agent.tool_definitions : []; + const toolDefinitions: AgentToolDefinition[] = defs + .map((d) => ({ + name: d?.function?.name ?? "", + type: typeof d?.type === "string" ? d.type : "function", + description: d?.function?.description, + parameters: d?.function?.parameters, + })) + .filter((d) => d.name.length > 0); + const toolDefsByName = new Map(toolDefinitions.map((d) => [d.name, d])); + + return { + source: "atif", + agent: typeof agent.name === "string" ? agent.name : undefined, + model: agent.model_name ?? firstAgentModel, + calls, + byId: buildById(calls), + toolDefinitions, + toolDefsByName, + steps, + finalMetrics: traj.final_metrics, + }; +} + +// --------------------------------------------------------------------------- +// Tools +// --------------------------------------------------------------------------- + +function writeSpill(spillDir: string, filename: string, text: string): string { + mkdirSync(spillDir, { recursive: true }); + const file = join(spillDir, `${filename}.txt`); + writeFileSync(file, text, "utf-8"); + return file; +} + +/** + * Build the four read-only trajectory tools over a normalized + * {@link AgentTrajectory}. All are `skipPermission: true` because the judge runs + * headless (no TUI to answer permission prompts; see scope #1125). + * + * @param trajectory normalized agent trajectory + * @param spillDir directory OUTSIDE the workspace where oversized outputs are + * written so they never pollute the codebase under evaluation. The judge reads + * them back via `read_file` (which is granted this dir as an extra read root). + */ +export function createTrajectoryTools(trajectory: AgentTrajectory, spillDir: string) { + const listAgentTools = defineTool("list_agent_tools", { + description: + "List the tools the coding agent had available during this run (its tool catalog / definitions). Returns each tool's name, type, a short description preview and whether it takes parameters. Use get_agent_tools(toolNames) to fetch a tool's full description and parameter schema. Empty when no tool catalog was captured.", + skipPermission: true, + parameters: { type: "object", properties: {}, required: [] }, + handler: async () => { + const tools = trajectory.toolDefinitions.map((d) => { + const description = d.description ?? ""; + return { + name: d.name, + type: d.type, + descriptionPreview: previewOf(description, LIST_PREVIEW_LIMIT), + descriptionLength: description.length, + hasParameters: !!d.parameters && Object.keys(d.parameters).length > 0, + }; + }); + return { count: tools.length, tools }; + }, + }); + + const getAgentTools = defineTool("get_agent_tools", { + description: + "Return the full definition (type, description and parameter JSON-schema) of the named agent tools, as listed by list_agent_tools. Pass a list of tool names. A very long description is written to a file (descriptionFile) you can open with read_file; the parameter schema is always returned inline. Unknown names are returned in notFound.", + skipPermission: true, + parameters: { + type: "object", + properties: { + toolNames: { + type: "array", + items: { type: "string" }, + description: "Tool names to fetch (from list_agent_tools).", + }, + }, + required: ["toolNames"], + }, + handler: async (args: { toolNames?: string[] }) => { + const names = Array.isArray(args?.toolNames) ? args.toolNames : []; + const tools: Record[] = []; + const notFound: string[] = []; + for (let i = 0; i < names.length; i++) { + const name = names[i]; + const def = trajectory.toolDefsByName.get(name); + if (!def) { + notFound.push(name); + continue; + } + const description = def.description ?? ""; + const base: Record = { + name: def.name, + type: def.type, + parameters: def.parameters, + descriptionLength: description.length, + }; + if (description.length <= INLINE_LIMIT) { + base.description = description; + } else { + base.descriptionPreview = previewOf(description); + base.descriptionFile = writeSpill(spillDir, safeId(`tool-${def.name}`, i), description); + } + tools.push(base); + } + return { tools, notFound }; + }, + }); + + const listAgentToolCalls = defineTool("list_agent_tool_calls", { + description: + "List the tool calls the coding agent made during this run (its trajectory of invocations). Returns each call's toolCallId, step, name, a one-line argument summary, a short response preview and the full response length. Use get_agent_tool_calls(toolCallIds) to fetch full arguments and output for the calls you care about. Consult these to determine what the agent actually did and whether a command succeeded.", + skipPermission: true, + parameters: { type: "object", properties: {}, required: [] }, + handler: async () => { + if (trajectory.calls.length === 0) { + return { count: 0, calls: [], message: "No tool calls were captured for this run." }; + } + const calls = trajectory.calls.map((c) => ({ + toolCallId: c.toolCallId, + step: c.step, + name: c.name, + summary: c.summary, + responsePreview: c.responsePreview.slice(0, LIST_PREVIEW_LIMIT), + responseLength: c.responseLength, + })); + return { count: calls.length, calls }; + }, + }); + + const getAgentToolCalls = defineTool("get_agent_tool_calls", { + description: + "Return the full arguments and captured output for a list of tool calls, identified by their toolCallId (as listed by list_agent_tool_calls). A very long output is written to a file (responseFile) you can open with read_file; shorter outputs are returned inline. Unknown ids are returned in notFound.", + skipPermission: true, + parameters: { + type: "object", + properties: { + toolCallIds: { + type: "array", + items: { type: "string" }, + description: "Tool call ids to fetch (from list_agent_tool_calls).", + }, + }, + required: ["toolCallIds"], + }, + handler: async (args: { toolCallIds?: string[] }) => { + const ids = Array.isArray(args?.toolCallIds) ? args.toolCallIds : []; + const calls: Record[] = []; + const notFound: string[] = []; + for (const id of ids) { + const c = trajectory.byId.get(id); + if (!c) { + notFound.push(id); + continue; + } + const base: Record = { + toolCallId: c.toolCallId, + step: c.step, + name: c.name, + arguments: c.arguments, + reasoning: c.reasoning, + responseLength: c.responseLength, + }; + if (c.responseLength <= INLINE_LIMIT) { + base.response = c.response; + } else { + const pos = trajectory.calls.indexOf(c); + base.responsePreview = c.responsePreview; + base.responseFile = writeSpill(spillDir, safeId(c.toolCallId, pos), c.response); + } + calls.push(base); + } + return { calls, notFound }; + }, + }); + + const getTrajectoryOverview = defineTool("get_trajectory_overview", { + description: + "Return a high-level overview of the agent's run: source, agent, model, the number of available tools and tool calls, a per-step summary (without the raw system prompt) and final metrics. Use this to orient before drilling into specific tools or calls.", + skipPermission: true, + parameters: { type: "object", properties: {}, required: [] }, + handler: async () => ({ + source: trajectory.source, + agent: trajectory.agent, + model: trajectory.model, + totalTools: trajectory.toolDefinitions.length, + totalCalls: trajectory.calls.length, + steps: trajectory.steps, + finalMetrics: trajectory.finalMetrics, + }), + }); + + return [ + listAgentTools, + getAgentTools, + listAgentToolCalls, + getAgentToolCalls, + getTrajectoryOverview, + ]; +} diff --git a/apps/judge/src/index.ts b/apps/judge/src/index.ts index 0dea452cd..fd5a42e38 100644 --- a/apps/judge/src/index.ts +++ b/apps/judge/src/index.ts @@ -5,6 +5,7 @@ import express, { Request, Response, NextFunction } from "express"; import dotenv from "dotenv"; import { evaluateWorkspace } from "./judge-agent.js"; import { verifyCopilotProtocol } from "./protocol-check.js"; +import { type AgentTrajectory, fromAtif, fromToolCalls } from "./agent-trajectory.js"; import { BlobStorage, RedisLogPublisher } from "shared"; import { mkdtempSync, rmSync } from "fs"; import { tmpdir } from "os"; @@ -89,44 +90,38 @@ app.post( console.log(`[judge] Snapshot extracted to ${workDir}`); - // Download this iteration's captured tool calls/outputs (build/test/run - // output), if provided. Failures are non-fatal — the judge can still - // evaluate the workspace files. - let toolCalls: import("shared").ToolCall[] = []; - if (toolCallsUrl && typeof toolCallsUrl === "string") { + // Build the agent's captured trajectory from whichever channel was + // provided, normalized into ONE source-agnostic model the judge navigates + // with the unified trajectory tools (list/get_agent_tool_calls, + // list/get_agent_tools, get_trajectory_overview). Gates send the HAR + // ToolCall[] via toolCallsUrl; observations (#1156) send the full ATIF via + // atifUrl — the normalized superset that also carries the agent's tool + // catalog and per-step reasoning. ATIF wins if both ever arrive (superset). + // Failures are non-fatal — the judge can still evaluate the workspace + // files. See apps/judge/src/agent-trajectory.ts. + let trajectory: AgentTrajectory | undefined; + if (atifUrl && typeof atifUrl === "string") { try { - toolCalls = await blobStorage.getToolCalls(toolCallsUrl); + const atif = await blobStorage.downloadJson(atifUrl); + trajectory = fromAtif(atif); console.log( - `[judge] Loaded ${toolCalls.length} tool call(s) for gate '${gate ?? "select"}'`, + `[judge] Loaded ATIF trajectory from ${atifUrl}: ${trajectory.calls.length} call(s), ${trajectory.toolDefinitions.length} tool definition(s)`, ); } catch (err) { console.warn( - `[judge] Failed to load tool calls from ${toolCallsUrl}: ${err instanceof Error ? err.message : String(err)}`, + `[judge] Failed to load ATIF from ${atifUrl}: ${err instanceof Error ? err.message : String(err)}`, ); } - } - - // Load the ATIF trajectory (normalized superset of tool calls) when - // provided — used by pp-taxonomy to evaluate observations against the - // full agent trajectory, not just the end-state snapshot. Exposed to the - // judge as a synthetic tool output so trajectory-only observations (e.g. - // a dependency added then removed mid-run) are detectable. Issue #1156. - if (atifUrl && typeof atifUrl === "string") { + } else if (toolCallsUrl && typeof toolCallsUrl === "string") { try { - const atif = await blobStorage.downloadJson(atifUrl); - toolCalls = [ - ...toolCalls, - { - id: "atif-trajectory", - name: "agent_trajectory_atif", - arguments: {}, - response: typeof atif === "string" ? atif : JSON.stringify(atif), - }, - ]; - console.log(`[judge] Loaded ATIF trajectory from ${atifUrl}`); + const toolCalls = await blobStorage.getToolCalls(toolCallsUrl); + trajectory = fromToolCalls(toolCalls); + console.log( + `[judge] Loaded ${trajectory.calls.length} tool call(s) for gate '${gate ?? "select"}'`, + ); } catch (err) { console.warn( - `[judge] Failed to load ATIF from ${atifUrl}: ${err instanceof Error ? err.message : String(err)}`, + `[judge] Failed to load tool calls from ${toolCallsUrl}: ${err instanceof Error ? err.message : String(err)}`, ); } } @@ -153,7 +148,7 @@ app.post( personaInstructions, onProgress, gate, - toolCalls, + trajectory, }); const elapsed = Date.now() - startTime; diff --git a/apps/judge/src/judge-agent.ts b/apps/judge/src/judge-agent.ts index a6c3672c0..19d74abbc 100644 --- a/apps/judge/src/judge-agent.ts +++ b/apps/judge/src/judge-agent.ts @@ -8,10 +8,10 @@ import { DetailedEvaluationResult, DependencyGraph, GateId, - ToolCall, } from "shared"; import { getCriteriaProvider } from "shared/criteria-provider-factory"; import { createJudgeStrategy } from "./judge-strategies.js"; +import type { AgentTrajectory } from "./agent-trajectory.js"; import { FeedbackGenerator } from "./feedback-generator.js"; export interface EvaluationInput { @@ -23,8 +23,10 @@ export interface EvaluationInput { onProgress?: (result: CriterionResult) => void; /** Which gate is being evaluated. Defaults to select. */ gate?: GateId; - /** This iteration's captured tool calls/outputs, exposed to the judge via read_tool_outputs. */ - toolCalls?: ToolCall[]; + /** The coding agent's captured trajectory (normalized from the HAR tool calls + * for gates, or the ATIF for observations), exposed to the judge via the + * unified trajectory tools. */ + trajectory?: AgentTrajectory; } export interface EvaluationResult { @@ -102,7 +104,7 @@ export async function evaluateWorkspace( personaInstructions: input.personaInstructions, onProgress: input.onProgress, gate: input.gate, - toolCalls: input.toolCalls, + trajectory: input.trajectory, }); console.log( diff --git a/apps/judge/src/judge-evaluation.integration.test.ts b/apps/judge/src/judge-evaluation.integration.test.ts index af96b1e42..8b5f7237f 100644 --- a/apps/judge/src/judge-evaluation.integration.test.ts +++ b/apps/judge/src/judge-evaluation.integration.test.ts @@ -24,7 +24,9 @@ import { mkdtempSync, writeFileSync, rmSync, realpathSync } from "fs"; import { tmpdir } from "os"; import { join } from "path"; import { resetCriteriaProvider } from "shared/criteria-provider-factory"; +import type { ToolCall } from "shared"; import { evaluateWorkspace } from "./judge-agent.js"; +import { fromToolCalls } from "./agent-trajectory.js"; const hasToken = !!process.env.GITHUB_TOKEN; @@ -64,6 +66,26 @@ describe("judge end-to-end evaluation (integration)", () => { ].join("\n") ); + // Gate-regression criterion (issue #1156 / P10): its verdict is derivable + // ONLY from the agent's captured tool output, NOT from the workspace files, + // so the judge must navigate the trajectory (list_agent_tool_calls / + // get_agent_tool_calls over a `fromToolCalls`-derived trajectory — the gate + // path) to decide. Guards that normalizing the HAR ToolCall[] and exposing it + // through the new tools yields the same boolean verdict the legacy + // read_tool_outputs/get_tool_output pair would. + writeFileSync( + join(criteriaDir, "build_succeeded.yaml"), + [ + "id: build_succeeded", + "prompt: |", + " The agent ran the project's build command and it completed", + " successfully (exit code 0, no compiler errors). This is only derivable", + " from the agent's captured tool calls — inspect them to confirm the", + " build command's output reports success.", + "", + ].join("\n") + ); + setEnv("CRITERIA_DIR", criteriaDir); setEnv("JUDGE_STRATEGY", process.env.JUDGE_STRATEGY || "independent"); setEnv("JUDGE_MODEL", JUDGE_MODEL); @@ -120,6 +142,77 @@ describe("judge end-to-end evaluation (integration)", () => { } ); + it.skipIf(!hasToken)( + "gate regression: a clear-PASS build gate built from a tool-call trajectory passes", + { timeout: 300_000 }, + async () => { + // The gate path: normalize the HAR ToolCall[] via fromToolCalls and let the + // judge navigate it with the unified trajectory tools. The build output says + // success, so the gate must pass. Verdict comes from the trajectory, not the + // workspace (which has no build log). + const passTrajectory = fromToolCalls([ + { + id: "tc-build-pass", + name: "bash", + arguments: { command: "npm run build" }, + response: + "> demo@1.0.0 build\n> tsc\n\nBuild succeeded. 0 errors, 0 warnings.\nExit code: 0", + timestamp: "", + } as ToolCall, + ]); + + const result = await evaluateWorkspace({ + workspacePath: workspaceDir, + criteria: ["build_succeeded"], + conversationHistory: [], + trajectory: passTrajectory, + }); + + const gate = result.criteriaResults.find((r) => r.criterionId === "build_succeeded"); + expect(gate, "build_succeeded result missing").toBeTruthy(); + expect(gate!.evaluated).toBe(true); + expect( + gate!.passed, + `expected clear-PASS build gate to pass from tool output. Feedback: ${gate!.feedback}` + ).toBe(true); + } + ); + + it.skipIf(!hasToken)( + "gate regression: a clear-FAIL build gate built from a tool-call trajectory fails", + { timeout: 300_000 }, + async () => { + // Same gate, opposite evidence: the build output reports a compiler error and + // a non-zero exit, so the gate must fail. Proves the trajectory drives the + // boolean verdict in both directions (no false positives). + const failTrajectory = fromToolCalls([ + { + id: "tc-build-fail", + name: "bash", + arguments: { command: "npm run build" }, + response: + "> demo@1.0.0 build\n> tsc\n\nsrc/index.ts(3,7): error TS2304: Cannot find name 'foo'.\n\nBuild failed. 1 error.\nExit code: 1", + timestamp: "", + } as ToolCall, + ]); + + const result = await evaluateWorkspace({ + workspacePath: workspaceDir, + criteria: ["build_succeeded"], + conversationHistory: [], + trajectory: failTrajectory, + }); + + const gate = result.criteriaResults.find((r) => r.criterionId === "build_succeeded"); + expect(gate, "build_succeeded result missing").toBeTruthy(); + expect(gate!.evaluated).toBe(true); + expect( + gate!.passed, + `expected clear-FAIL build gate to fail from tool output. Feedback: ${gate!.feedback}` + ).toBe(false); + } + ); + it("logs a skip note when GITHUB_TOKEN is absent (no real evaluation possible)", () => { if (!hasToken) { console.warn( diff --git a/apps/judge/src/judge-strategies.test.ts b/apps/judge/src/judge-strategies.test.ts index 5cf0dfcdc..4162fa6ef 100644 --- a/apps/judge/src/judge-strategies.test.ts +++ b/apps/judge/src/judge-strategies.test.ts @@ -8,8 +8,9 @@ import { join } from "path"; import { IndependentStrategy, BundledStrategy, - TOOL_OUTPUTS_GUIDANCE, + TRAJECTORY_GUIDANCE, isWithinWorkspace, + isWithinAnyRoot, JUDGE_AVAILABLE_TOOLS, JUDGE_EXCLUDED_TOOLS, } from "./judge-strategies.js"; @@ -20,17 +21,17 @@ import { * Copilot session. */ class TestableStrategy extends IndependentStrategy { - publicCreateFileTools(workspacePath: string) { - return this.createFileTools(workspacePath); - } - publicCreateToolOutputTools(toolCalls: any[]) { - return this.createToolOutputTools(toolCalls); + publicCreateFileTools( + workspacePath: string, + opts?: { extraReadRoots?: string[] } + ) { + return this.createFileTools(workspacePath, opts); } publicBuildSessionConfig(tools: any[], systemPrompt: string) { return this.buildSessionConfig(tools, systemPrompt); } - publicBuildSystemPrompt(hasToolOutputs: boolean) { - return (this as any).buildSystemPrompt(undefined, hasToolOutputs); + publicBuildSystemPrompt(hasTrajectory: boolean) { + return (this as any).buildSystemPrompt(undefined, hasTrajectory); } publicBuildUserPrompt( criterion: { id: string; prompt: string }, @@ -40,9 +41,12 @@ class TestableStrategy extends IndependentStrategy { } } -function toolMap(workspacePath: string) { +function toolMap( + workspacePath: string, + opts?: { extraReadRoots?: string[] } +) { const strategy = new TestableStrategy("test-model"); - const tools = strategy.publicCreateFileTools(workspacePath); + const tools = strategy.publicCreateFileTools(workspacePath, opts); return new Map(tools.map((t) => [t.name, t])); } @@ -56,9 +60,10 @@ const stubInvocation = { async function callTool( workspacePath: string, name: string, - args: Record + args: Record, + opts?: { extraReadRoots?: string[] } ): Promise { - const tool = toolMap(workspacePath).get(name); + const tool = toolMap(workspacePath, opts).get(name); if (!tool?.handler) throw new Error(`tool ${name} has no handler`); return (tool.handler as (a: unknown, b: unknown) => unknown)(args, stubInvocation); } @@ -86,37 +91,6 @@ describe("judge file tools", () => { }); }); -describe("judge tool-output tools (issue #1125)", () => { - const strategy = new TestableStrategy("test-model"); - const toolCalls = [ - { - id: "1", - name: "bash", - arguments: { command: "npm run build" }, - response: "build ok", - timestamp: "", - }, - ]; - const tools = strategy.publicCreateToolOutputTools(toolCalls); - - it("exposes read_tool_outputs and get_tool_output", () => { - const names = tools.map((t) => t.name).sort(); - expect(names).toEqual(["get_tool_output", "read_tool_outputs"]); - }); - - // Regression guard for scope #1125: headless, any tool without skipPermission - // is denied at execution time ("could not request permission from user"). When - // this affected read_tool_outputs/get_tool_output, the judge could never see - // the coding agent's captured build/test output and wrongly demanded on-disk - // proof files, forcing the build gate to loop for many iterations. - it("marks every tool-output tool to skip the permission prompt", () => { - expect(tools.length).toBeGreaterThan(0); - for (const tool of tools) { - expect(tool.skipPermission, `${tool.name} must skip the permission prompt`).toBe(true); - } - }); -}); - describe("isWithinWorkspace", () => { it("accepts the root itself and nested paths", () => { expect(isWithinWorkspace("/tmp/ws", "/tmp/ws")).toBe(true); @@ -137,6 +111,21 @@ describe("isWithinWorkspace", () => { }); }); +describe("isWithinAnyRoot", () => { + it("accepts a path inside any of the roots", () => { + expect(isWithinAnyRoot(["/tmp/ws", "/tmp/spill"], "/tmp/ws/src/a.ts")).toBe(true); + expect(isWithinAnyRoot(["/tmp/ws", "/tmp/spill"], "/tmp/spill/out.txt")).toBe(true); + expect(isWithinAnyRoot(["/tmp/ws", "/tmp/spill"], "/tmp/spill")).toBe(true); + }); + + it("rejects a path outside every root (guard preserved per-root)", () => { + expect(isWithinAnyRoot(["/tmp/ws", "/tmp/spill"], "/tmp/ws2/secret")).toBe(false); + expect(isWithinAnyRoot(["/tmp/ws", "/tmp/spill"], "/etc/passwd")).toBe(false); + // sibling-prefix of an allowed root must not slip through + expect(isWithinAnyRoot(["/tmp/ws", "/tmp/spill"], "/tmp/spill2/x")).toBe(false); + }); +}); + describe("judge file tool handlers (workspace scoping)", () => { let parent: string; let workspace: string; @@ -201,6 +190,85 @@ describe("judge file tool handlers (workspace scoping)", () => { }); }); +describe("judge file tools — extraReadRoots (P10 trajectory spill dir)", () => { + // The trajectory tools spill oversized outputs to a dir OUTSIDE the workspace + // and return its absolute path; read_file/file_exists must be able to open it + // (via extraReadRoots) WITHOUT widening list_directory/search_files, so the + // codebase view other criteria inspect is never polluted by spill files. + let parent: string; + let workspace: string; + let spill: string; + + beforeAll(() => { + parent = mkdtempSync(join(tmpdir(), "judge-spill-")); + workspace = join(parent, "ws"); + spill = join(parent, "spill"); + mkdirSync(workspace, { recursive: true }); + mkdirSync(spill, { recursive: true }); + writeFileSync(join(workspace, "inside.txt"), "in-workspace"); + writeFileSync(join(spill, "big-output.txt"), "SPILLED OUTPUT"); + }); + + afterAll(() => { + rmSync(parent, { recursive: true, force: true }); + }); + + it("read_file opens an absolute path under an extra read root", async () => { + const result = (await callTool( + workspace, + "read_file", + { path: join(spill, "big-output.txt") }, + { extraReadRoots: [spill] } + )) as { content?: string; error?: string }; + expect(result.error).toBeUndefined(); + expect(result.content).toBe("SPILLED OUTPUT"); + }); + + it("file_exists confirms a file under an extra read root", async () => { + const result = (await callTool( + workspace, + "file_exists", + { path: join(spill, "big-output.txt") }, + { extraReadRoots: [spill] } + )) as { exists?: boolean; error?: string }; + expect(result.error).toBeUndefined(); + expect(result.exists).toBe(true); + }); + + it("read_file still rejects an absolute path outside the workspace AND the extra roots", async () => { + const outside = join(parent, "other", "secret.txt"); + mkdirSync(join(parent, "other"), { recursive: true }); + writeFileSync(outside, "SECRET"); + const result = (await callTool( + workspace, + "read_file", + { path: outside }, + { extraReadRoots: [spill] } + )) as { content?: string; error?: string }; + expect(result.error).toBe("Path traversal not allowed"); + expect(result.content).toBeUndefined(); + }); + + it("read_file without extraReadRoots rejects the spill path (default behaviour unchanged)", async () => { + const result = (await callTool(workspace, "read_file", { + path: join(spill, "big-output.txt"), + })) as { content?: string; error?: string }; + expect(result.error).toBe("Path traversal not allowed"); + }); + + it("list_directory stays workspace-only — it cannot reveal an extra read root's contents", async () => { + const result = (await callTool( + workspace, + "list_directory", + { path: spill }, + { extraReadRoots: [spill] } + )) as { entries?: { name: string }[]; error?: string }; + // Whether it errors or resolves the absolute path back under the workspace, + // it must never surface the spilled file — list_directory ignores extraReadRoots. + expect(result.entries?.some((e) => e.name === "big-output.txt") ?? false).toBe(false); + }); +}); + describe("judge session tool restriction (scope #1117)", () => { const strategy = new TestableStrategy("test-model"); const config = strategy.publicBuildSessionConfig([], "system prompt"); @@ -243,8 +311,8 @@ describe("judge session tool restriction (scope #1117)", () => { * without running a real Copilot session. */ class TestableBundledStrategy extends BundledStrategy { - publicBuildSystemPrompt(hasToolOutputs: boolean) { - return (this as any).buildSystemPrompt(undefined, hasToolOutputs); + publicBuildSystemPrompt(hasTrajectory: boolean) { + return (this as any).buildSystemPrompt(undefined, hasTrajectory); } publicBuildUserPrompt( criteria: { id: string; prompt: string }[] = [ @@ -256,51 +324,59 @@ class TestableBundledStrategy extends BundledStrategy { } } -describe("judge tool-outputs guidance (issue #1125)", () => { +describe("judge trajectory guidance (issue #1125 / #1156)", () => { // The headless judge cannot run commands; it must decide from the codebase - // plus the coding agent's captured tool outputs. The guidance must be generic + // plus the coding agent's captured trajectory. The guidance must be generic // (not build/test specific) and must tell the judge to treat captured output // as authoritative instead of demanding the agent redo or re-prove the work. it("is generic, not tied to any one command type", () => { - const g = TOOL_OUTPUTS_GUIDANCE.toLowerCase(); + const g = TRAJECTORY_GUIDANCE.toLowerCase(); expect(g).not.toMatch(/build\.log|build_proof|\bnpm run build\b/); }); it("tells the judge it cannot run commands itself", () => { - expect(TOOL_OUTPUTS_GUIDANCE.toLowerCase()).toContain("cannot run any commands"); + expect(TRAJECTORY_GUIDANCE.toLowerCase()).toContain("cannot run any commands"); + }); + + it("names the judge's own read-only tools and the unified trajectory tools", () => { + expect(TRAJECTORY_GUIDANCE).toContain("## Your Tools"); + expect(TRAJECTORY_GUIDANCE).toContain("read_file"); + expect(TRAJECTORY_GUIDANCE).toContain("list_agent_tool_calls"); + expect(TRAJECTORY_GUIDANCE).toContain("get_agent_tool_calls"); + expect(TRAJECTORY_GUIDANCE).toContain("list_agent_tools"); + expect(TRAJECTORY_GUIDANCE).toContain("get_agent_tools"); + expect(TRAJECTORY_GUIDANCE.toLowerCase()).toContain("codebase"); }); - it("names the judge's own read-only tools and disambiguates them from the agent's", () => { - expect(TOOL_OUTPUTS_GUIDANCE).toContain("## Your Tools"); - expect(TOOL_OUTPUTS_GUIDANCE).toContain("read_file"); - expect(TOOL_OUTPUTS_GUIDANCE).toContain("read_tool_outputs"); - expect(TOOL_OUTPUTS_GUIDANCE).toContain("get_tool_output"); - expect(TOOL_OUTPUTS_GUIDANCE.toLowerCase()).toContain("codebase"); + it("tells the judge to open spilled outputs (responseFile/descriptionFile) with read_file", () => { + expect(TRAJECTORY_GUIDANCE).toContain("responseFile"); + expect(TRAJECTORY_GUIDANCE).toContain("descriptionFile"); + expect(TRAJECTORY_GUIDANCE.toLowerCase()).toMatch(/open .*with read_file|read_file/); }); - it("frames the codebase and captured outputs as equally authoritative and to be examined together", () => { - expect(TOOL_OUTPUTS_GUIDANCE).toContain("## How to Judge"); - const g = TOOL_OUTPUTS_GUIDANCE.toLowerCase(); + it("frames the codebase and captured trajectory as equally authoritative and to be examined together", () => { + expect(TRAJECTORY_GUIDANCE).toContain("## How to Judge"); + const g = TRAJECTORY_GUIDANCE.toLowerCase(); expect(g).toContain("equally authoritative"); expect(g).toContain("examine both"); }); it("treats captured output as the record of what happened and forbids redundant re-proving", () => { - const g = TOOL_OUTPUTS_GUIDANCE.toLowerCase(); + const g = TRAJECTORY_GUIDANCE.toLowerCase(); expect(g).toContain("record of what happened"); expect(g).toMatch(/redo or re-prove/); }); it("overrides criteria wording that asks the judge to run commands", () => { - const g = TOOL_OUTPUTS_GUIDANCE.toLowerCase(); + const g = TRAJECTORY_GUIDANCE.toLowerCase(); expect(g).toContain("criterion"); expect(g).toMatch(/run, execute, or re-run/); expect(g).toContain("ignore that instruction"); }); - it("includes the guidance in the system prompt when tool outputs are present", () => { + it("includes the guidance in the system prompt when a trajectory is present", () => { const prompt = new TestableBundledStrategy("test-model").publicBuildSystemPrompt(true); - expect(prompt).toContain(TOOL_OUTPUTS_GUIDANCE); + expect(prompt).toContain(TRAJECTORY_GUIDANCE); }); it("frames What to Evaluate around the agent's work and points at the user message", () => { @@ -310,9 +386,9 @@ describe("judge tool-outputs guidance (issue #1125)", () => { expect(prompt).toMatch(/each criterion provided in the user message/); }); - it("omits the guidance when no tool outputs were captured", () => { + it("omits the guidance when no trajectory was captured", () => { const prompt = new TestableBundledStrategy("test-model").publicBuildSystemPrompt(false); - expect(prompt).not.toContain(TOOL_OUTPUTS_GUIDANCE); + expect(prompt).not.toContain(TRAJECTORY_GUIDANCE); }); }); diff --git a/apps/judge/src/judge-strategies.ts b/apps/judge/src/judge-strategies.ts index 19705be5e..dfa6c2ef2 100644 --- a/apps/judge/src/judge-strategies.ts +++ b/apps/judge/src/judge-strategies.ts @@ -2,8 +2,9 @@ // Licensed under the MIT License. import { CopilotClient, defineTool, SessionEvent } from "@github/copilot-sdk"; -import { readFileSync, readdirSync, statSync, existsSync } from "fs"; -import { join, resolve, sep } from "path"; +import { readFileSync, readdirSync, statSync, existsSync, mkdtempSync, rmSync } from "fs"; +import { tmpdir } from "os"; +import { isAbsolute, join, resolve, sep } from "path"; import { execFileSync } from "child_process"; import { CriteriaConfig, @@ -12,10 +13,13 @@ import { ConversationTurn, DependencyGraph, GateId, - ToolCall, TokenManagerClient, withRetry, } from "shared"; +import { + type AgentTrajectory, + createTrajectoryTools, +} from "./agent-trajectory.js"; export interface JudgeStrategyContext { workspacePath: string; @@ -28,8 +32,9 @@ export interface JudgeStrategyContext { onProgress?: (result: CriterionResult) => void; /** Which gate is being evaluated. Defaults to select. */ gate?: GateId; - /** This iteration's captured tool calls/outputs (build/test/run output). */ - toolCalls?: ToolCall[]; + /** The coding agent's captured trajectory (normalized from the HAR tool calls + * for gates, or the ATIF for observations). */ + trajectory?: AgentTrajectory; } /** @@ -54,11 +59,16 @@ const DEFAULT_JUDGE_RETRIES = 3; * its decision on actual evidence instead of demanding the agent re-prove work * it has already done. It is intentionally generic across all criteria. */ -export const TOOL_OUTPUTS_GUIDANCE = `## Your Tools -You have read-only tools to gather evidence: read_file, list_directory, search_files and file_exists to inspect the workspace, and read_tool_outputs / get_tool_output to review the tool calls the coding agent ran while doing the task. You yourself cannot run any commands or coding-agent tools — you can only read what the agent already did. +export const TRAJECTORY_GUIDANCE = `## Your Tools +You have read-only tools to gather evidence — you cannot run any commands or coding-agent tools yourself, you can only read what the agent already did: +- Inspect the resulting codebase: read_file, list_directory, search_files, file_exists. +- See what tools the agent HAD available (its catalog): list_agent_tools, then get_agent_tools(toolNames) for a tool's full description and parameter schema. +- See what the agent DID: list_agent_tool_calls to triage its invocations (id, name, a short summary and a preview of each output), then get_agent_tool_calls(toolCallIds) for the full arguments and captured output of the calls you care about. +- get_trajectory_overview gives a high-level orientation (agent, model, steps) without the raw system prompt. +When get_agent_tool_calls or get_agent_tools returns a responseFile or descriptionFile (large outputs are spilled to a file instead of inlined), open that path with read_file. ## How to Judge -The codebase and the agent's captured tool outputs are two complementary, equally authoritative sources of evidence — examine both. The files show the resulting state of the code; the captured outputs (logs, results, exit status) show what actually happened when the agent ran a command, which the files alone may not reveal. When a criterion concerns something the agent did or ran, take the agent's captured output and exit status as the record of what happened, rather than asking the agent to redo or re-prove work the evidence already shows. If a criterion's wording tells you to run, execute, or re-run a command, ignore that instruction and judge the outcome from the captured outputs together with the codebase.`; +The resulting codebase and the agent's captured trajectory are two complementary, equally authoritative sources of evidence — examine both. The files show the resulting state of the code; the captured tool calls and their outputs show what actually happened while the agent worked, including intermediate actions the final files no longer reveal (for example a dependency added and then later removed within the run). Start with list_agent_tool_calls to see what the agent did, then drill into the relevant calls with get_agent_tool_calls. When a criterion concerns something the agent did or ran, take the agent's captured output and exit status as the record of what happened, rather than asking the agent to redo or re-prove work the evidence already shows. If a criterion's wording tells you to run, execute, or re-run a command, ignore that instruction and judge the outcome from the captured trajectory together with the codebase.`; /** * Tool filter applied to every judge session. @@ -66,11 +76,11 @@ The codebase and the agent's captured tool outputs are two complementary, equall * The Copilot SDK's `CopilotClient` defaults to `mode: "copilot-cli"`, which * injects the full set of built-in CLI tools (bash, edit, view, ...) into the * session alongside the read-only `custom:*` tools we register in - * `createFileTools`/`createToolOutputTools`. Those built-ins are NOT + * `createFileTools`/`createTrajectoryTools`. Those built-ins are NOT * `skipPermission`, and the judge runs headless (no TUI to answer prompts). * * The failure mode this guards against: instead of reading the coder's captured - * output via `read_tool_outputs`/`get_tool_output`, the judge model decides to + * output via `list_agent_tool_calls`/`get_agent_tool_calls`, the judge model decides to * "verify" a build/test by running the command itself through the built-in * `bash` tool. Headless, that call is denied with "could not request permission * from user". The judge then mis-reports this as the coder's result ("execution @@ -103,6 +113,17 @@ export function isWithinWorkspace(root: string, target: string): boolean { ); } +/** + * Returns true if `target` resolves inside (or equal to) ANY of `roots`. Used so + * read_file/file_exists may read both the workspace and a judge-created spill dir + * (created OUTSIDE the workspace for oversized trajectory tool outputs) without + * weakening the per-root traversal guard — each root is still checked with the + * exact-or-separator-boundary rule of `isWithinWorkspace`. + */ +export function isWithinAnyRoot(roots: string[], target: string): boolean { + return roots.some((root) => isWithinWorkspace(root, target)); +} + export abstract class JudgeStrategy { protected model: string; protected timeout: number; @@ -126,11 +147,21 @@ export abstract class JudgeStrategy { /** * Create filesystem inspection tools scoped to the workspace */ - protected createFileTools(workspacePath: string) { + protected createFileTools( + workspacePath: string, + opts?: { extraReadRoots?: string[] }, + ) { const workspaceRoot = resolve(workspacePath); + // Additional roots (OUTSIDE the workspace) that read_file/file_exists may + // read by ABSOLUTE path — used for the trajectory spill dir so the judge can + // open oversized tool outputs returned as responseFile/descriptionFile. + // list_directory/search_files stay workspace-only so the codebase view the + // judge inspects is never polluted by spill files. + const extraReadRoots = (opts?.extraReadRoots ?? []).map((r) => resolve(r)); + const readRoots = [workspaceRoot, ...extraReadRoots]; const readFile = defineTool("read_file", { description: - "Read the contents of a file in the workspace. Returns the full text content. Use relative paths from the workspace root.", + "Read the contents of a file. Returns the full text content. Use a relative path from the workspace root, or an absolute path returned as responseFile/descriptionFile by the agent-trajectory tools.", // Read-only, workspace-scoped, traversal-guarded tools must run without a // permission prompt: the judge is headless (no TUI), so the v3 runtime // would otherwise deny every call with "could not request permission from @@ -147,8 +178,10 @@ export abstract class JudgeStrategy { required: ["path"], }, handler: async (args: { path: string }) => { - const fullPath = join(workspaceRoot, args.path); - if (!isWithinWorkspace(workspaceRoot, fullPath)) { + const fullPath = isAbsolute(args.path) + ? resolve(args.path) + : join(workspaceRoot, args.path); + if (!isWithinAnyRoot(readRoots, fullPath)) { return { error: "Path traversal not allowed" }; } if (!existsSync(fullPath)) { @@ -318,8 +351,10 @@ export abstract class JudgeStrategy { required: ["path"], }, handler: async (args: { path: string }) => { - const fullPath = join(workspaceRoot, args.path); - if (!isWithinWorkspace(workspaceRoot, fullPath)) { + const fullPath = isAbsolute(args.path) + ? resolve(args.path) + : join(workspaceRoot, args.path); + if (!isWithinAnyRoot(readRoots, fullPath)) { return { error: "Path traversal not allowed" }; } const exists = existsSync(fullPath); @@ -335,129 +370,68 @@ export abstract class JudgeStrategy { return [readFile, listDirectory, searchFiles, fileExists]; } - /** - * Create tools that expose the tool calls/outputs captured during the gate - * iteration being judged (e.g. a build/test command's stdout/stderr/exit - * code). `read_tool_outputs` lists calls with truncated previews; - * `get_tool_output` returns the full output for a given index on demand. - */ - protected createToolOutputTools(toolCalls: ToolCall[]) { - const PREVIEW_LIMIT = 2_000; - const FULL_LIMIT = 100_000; - - const readToolOutputs = defineTool("read_tool_outputs", { - description: - "List the tool calls the coding agent made during this iteration (e.g. shell/bash commands and their output). Returns each call's index, name, arguments and a truncated response preview. Use get_tool_output(index) to fetch the full output of a specific call. Consult these to decide whether a command (build, test, run) actually succeeded.", - // Read-only in-memory inspection of already-captured tool calls. Like the - // file tools above, this MUST run without a permission prompt: the judge is - // headless (no TUI), so the v3 runtime would otherwise deny every call with - // "could not request permission from user" — which silently blocks the judge - // from ever seeing the coding agent's build/test output and forces it to - // demand on-disk proof files instead. See scope #1125. - skipPermission: true, - parameters: { - type: "object", - properties: {}, - required: [], - }, - handler: async () => { - if (toolCalls.length === 0) { - return { count: 0, calls: [], message: "No tool calls were captured for this iteration." }; - } - const calls = toolCalls.map((tc, index) => { - const response = tc.response ?? ""; - return { - index, - name: tc.name, - arguments: tc.arguments, - responsePreview: - response.length > PREVIEW_LIMIT - ? response.substring(0, PREVIEW_LIMIT) + "\n…(truncated, use get_tool_output)" - : response, - responseTruncated: response.length > PREVIEW_LIMIT, - responseLength: response.length, - }; - }); - return { count: calls.length, calls }; - }, - }); - - const getToolOutput = defineTool("get_tool_output", { - description: - "Return the full captured output (response) of a single tool call by its index, as listed by read_tool_outputs.", - // Read-only; same headless permission rationale as read_tool_outputs. See scope #1125. - skipPermission: true, - parameters: { - type: "object", - properties: { - index: { - type: "number", - description: "Zero-based index of the tool call from read_tool_outputs", - }, - }, - required: ["index"], - }, - handler: async (args: { index: number }) => { - const tc = toolCalls[args.index]; - if (!tc) { - return { error: `No tool call at index ${args.index} (have ${toolCalls.length})` }; - } - const response = tc.response ?? ""; - if (response.length > FULL_LIMIT) { - return { - index: args.index, - name: tc.name, - arguments: tc.arguments, - response: response.substring(0, FULL_LIMIT), - truncated: true, - totalLength: response.length, - }; - } - return { index: args.index, name: tc.name, arguments: tc.arguments, response }; - }, - }); - - return [readToolOutputs, getToolOutput]; - } - /** * Run a Copilot session with given prompt and tools, retrying on timeout. + * + * When a trajectory with at least one captured call is supplied, the unified + * trajectory navigation tools are registered (mirroring the previous + * `toolCalls.length > 0` gate) and a per-evaluation spill dir is created + * OUTSIDE the workspace for oversized tool outputs; read_file is granted that + * dir as an extra read root so the judge can open spilled files. The spill dir + * is best-effort removed when the session finishes. */ protected async runCopilotSession( workspacePath: string, systemPrompt: string, userPrompt: string, - toolCalls?: ToolCall[] + trajectory?: AgentTrajectory ): Promise { + const hasTrajectory = !!trajectory && trajectory.calls.length > 0; + const spillDir = hasTrajectory + ? mkdtempSync(join(tmpdir(), "judge-trajectory-")) + : undefined; const tools = [ - ...this.createFileTools(workspacePath), - ...(toolCalls && toolCalls.length > 0 ? this.createToolOutputTools(toolCalls) : []), + ...this.createFileTools( + workspacePath, + spillDir ? { extraReadRoots: [spillDir] } : undefined, + ), + ...(hasTrajectory ? createTrajectoryTools(trajectory!, spillDir!) : []), ]; - return withRetry( - () => this.doRunCopilotSession(tools, systemPrompt, userPrompt), - { - maxRetries: this.maxRetries, - baseDelayMs: 10_000, - maxDelayMs: 30_000, - isRetryable: (error) => { - const msg = error instanceof Error ? error.message : String(error); - return ( - msg.includes("timeout") || - msg.includes("Timeout") || - msg.includes("aborted") || - msg.includes("ECONNRESET") || - msg.includes("socket hang up") - ); - }, - onRetry: (error, attempt) => { - const msg = error instanceof Error ? error.message : String(error); - console.warn( - `[judge-strategy] sendAndWait attempt ${attempt} failed (retrying in ≤30s): ${msg.substring(0, 200)}` - ); - }, + try { + return await withRetry( + () => this.doRunCopilotSession(tools, systemPrompt, userPrompt), + { + maxRetries: this.maxRetries, + baseDelayMs: 10_000, + maxDelayMs: 30_000, + isRetryable: (error) => { + const msg = error instanceof Error ? error.message : String(error); + return ( + msg.includes("timeout") || + msg.includes("Timeout") || + msg.includes("aborted") || + msg.includes("ECONNRESET") || + msg.includes("socket hang up") + ); + }, + onRetry: (error, attempt) => { + const msg = error instanceof Error ? error.message : String(error); + console.warn( + `[judge-strategy] sendAndWait attempt ${attempt} failed (retrying in ≤30s): ${msg.substring(0, 200)}` + ); + }, + } + ); + } finally { + if (spillDir) { + try { + rmSync(spillDir, { recursive: true, force: true }); + } catch { + // best-effort cleanup of the out-of-workspace spill dir + } } - ); + } } /** @@ -526,12 +500,12 @@ export class BundledStrategy extends JudgeStrategy { criteria, conversationHistory, personaInstructions, - toolCalls, + trajectory, } = context; const systemPrompt = this.buildSystemPrompt( personaInstructions, - toolCalls && toolCalls.length > 0 + !!trajectory && trajectory.calls.length > 0 ); const userPrompt = this.buildUserPrompt(criteria, conversationHistory); @@ -540,7 +514,7 @@ export class BundledStrategy extends JudgeStrategy { workspacePath, systemPrompt, userPrompt, - toolCalls + trajectory ); return this.parseJsonResponse(response, criteria, context.onProgress); @@ -555,14 +529,14 @@ export class BundledStrategy extends JudgeStrategy { */ private buildSystemPrompt( personaInstructions?: string, - hasToolOutputs?: boolean + hasTrajectory?: boolean ): string { const personaSection = personaInstructions ? `\n## Persona\n${personaInstructions}\n` : ""; - const toolOutputsSection = hasToolOutputs - ? `\n${TOOL_OUTPUTS_GUIDANCE}\n` + const toolOutputsSection = hasTrajectory + ? `\n${TRAJECTORY_GUIDANCE}\n` : ""; return `You are an expert code reviewer evaluating the tool calls, logs and generated code produced by a coding agent. @@ -729,7 +703,7 @@ export class IndependentStrategy extends JudgeStrategy { personaInstructions, onProgress, gate, - toolCalls, + trajectory, } = context; // Get topological order @@ -795,7 +769,7 @@ export class IndependentStrategy extends JudgeStrategy { personaInstructions, evalIndex++, gate, - toolCalls + trajectory ) ); @@ -836,11 +810,11 @@ export class IndependentStrategy extends JudgeStrategy { personaInstructions: string | undefined, index: number, gate?: GateId, - toolCalls?: ToolCall[] + trajectory?: AgentTrajectory ): Promise { const systemPrompt = this.buildSystemPrompt( personaInstructions, - toolCalls && toolCalls.length > 0 + !!trajectory && trajectory.calls.length > 0 ); const userPrompt = this.buildUserPrompt(criterion, conversationHistory); @@ -850,7 +824,7 @@ export class IndependentStrategy extends JudgeStrategy { workspacePath, systemPrompt, userPrompt, - toolCalls + trajectory ); const passed = this.detectPassFail(response); @@ -884,14 +858,14 @@ export class IndependentStrategy extends JudgeStrategy { */ protected buildSystemPrompt( personaInstructions?: string, - hasToolOutputs?: boolean + hasTrajectory?: boolean ): string { const personaSection = personaInstructions ? `\n## Persona\n${personaInstructions}\n` : ""; - const toolOutputsSection = hasToolOutputs - ? `\n${TOOL_OUTPUTS_GUIDANCE}\n` + const toolOutputsSection = hasTrajectory + ? `\n${TRAJECTORY_GUIDANCE}\n` : ""; return `You are an expert code reviewer evaluating the tool calls, logs and generated code produced by a coding agent against ONE specific criterion. diff --git a/apps/judge/src/observation-trajectory.integration.test.ts b/apps/judge/src/observation-trajectory.integration.test.ts index c8b31030b..185a6b54b 100644 --- a/apps/judge/src/observation-trajectory.integration.test.ts +++ b/apps/judge/src/observation-trajectory.integration.test.ts @@ -6,14 +6,15 @@ * * Proves the judge resolves a trajectory-only observation — one whose answer is * NOT derivable from the final workspace snapshot — by consuming the agent's - * ATIF trajectory that pp-taxonomy forwards as a synthetic `agent_trajectory_atif` - * tool call (see apps/judge/src/index.ts). The canonical case is - * `dependency_added_then_removed`: a package is installed then uninstalled mid-run, - * so it is invisible in the end-state snapshot and only the trajectory reveals it. + * ATIF trajectory normalized into an {@link AgentTrajectory} and navigated via + * the unified trajectory tools (list_agent_tool_calls / get_agent_tool_calls). + * The canonical case is `dependency_added_then_removed`: a package is installed + * then uninstalled mid-run, so it is invisible in the end-state snapshot and + * only the trajectory reveals it. * * Two assertions form the acceptance: - * 1. WITH the trajectory tool call → criterion resolves passed:true (the judge - * actually consumed the ATIF). + * 1. WITH the trajectory → criterion resolves passed:true (the judge actually + * consumed the ATIF via the navigation tools). * 2. WITHOUT the trajectory (snapshot only) → the same criterion flips to * passed:false, proving the verdict comes from the trajectory, not the files. * @@ -26,33 +27,97 @@ import { mkdtempSync, writeFileSync, rmSync, realpathSync } from "fs"; import { tmpdir } from "os"; import { join } from "path"; import { resetCriteriaProvider } from "shared/criteria-provider-factory"; -import type { ToolCall } from "shared"; +import { fromAtif } from "./agent-trajectory.js"; import { evaluateWorkspace } from "./judge-agent.js"; const hasToken = !!process.env.GITHUB_TOKEN; const JUDGE_MODEL = process.env.JUDGE_MODEL || "gpt-5.4-mini"; /** - * Synthetic ATIF trajectory mirroring what pp-taxonomy forwards: the agent - * installs `left-pad`, uses it, then uninstalls it before finishing. The final - * package.json (below) therefore does NOT list left-pad. + * Realistic ATIF trajectory (the exact shape pp-taxonomy downloads and forwards + * via `fromAtif`): a system + user step, then agent steps that install + * `left-pad`, use it, and uninstall it before finishing. Each agent step pairs + * its `tool_calls[]` with the matching same-step `observation.results[]` by + * `source_call_id === tool_call_id`. The final package.json (below) therefore + * does NOT list left-pad — the add-then-remove is only in the trajectory. */ -const ATIF_TRAJECTORY = { - schema: "atif/1", +const REALISTIC_ATIF = { + schema_version: "atif/1", + session_id: "atif-trajectory-test", + agent: { + name: "copilot", + version: "1.0.0", + model_name: "claude-opus-4.6", + tool_definitions: [ + { + type: "function", + function: { + name: "bash", + description: "Run a shell command in the workspace.", + parameters: { + type: "object", + properties: { command: { type: "string" } }, + required: ["command"], + }, + }, + }, + { + type: "function", + function: { + name: "edit", + description: "Edit a file in the workspace.", + parameters: { + type: "object", + properties: { path: { type: "string" } }, + required: ["path"], + }, + }, + }, + ], + }, steps: [ - { type: "tool_call", name: "run_in_terminal", arguments: { command: "npm install left-pad" }, response: "+ left-pad@1.3.0\nadded 1 package" }, - { type: "tool_call", name: "edit_file", arguments: { path: "index.js" }, response: "require('left-pad')" }, - { type: "tool_call", name: "run_in_terminal", arguments: { command: "npm uninstall left-pad" }, response: "removed 1 package" }, + { step_id: 1, source: "system" }, + { step_id: 2, source: "user" }, + { + step_id: 3, + source: "agent", + model_name: "claude-opus-4.6", + reasoning_content: "I'll add left-pad to pad the output.", + tool_calls: [ + { tool_call_id: "call-1", function_name: "bash", arguments: { command: "npm install left-pad" } }, + ], + observation: { + results: [ + { source_call_id: "call-1", content: "added 1 package\n+ left-pad@1.3.0\nfound 0 vulnerabilities" }, + ], + }, + }, + { + step_id: 4, + source: "agent", + model_name: "claude-opus-4.6", + tool_calls: [ + { tool_call_id: "call-2", function_name: "edit", arguments: { path: "index.js" } }, + ], + observation: { + results: [{ source_call_id: "call-2", content: "File index.js edited: now requires('left-pad')" }], + }, + }, + { + step_id: 5, + source: "agent", + model_name: "claude-opus-4.6", + reasoning_content: "On reflection I don't need left-pad; removing it.", + tool_calls: [ + { tool_call_id: "call-3", function_name: "bash", arguments: { command: "npm uninstall left-pad" } }, + ], + observation: { + results: [{ source_call_id: "call-3", content: "removed 1 package\nfound 0 vulnerabilities" }], + }, + }, ], }; -const TRAJECTORY_TOOL_CALL: ToolCall = { - id: "atif-trajectory", - name: "agent_trajectory_atif", - arguments: {}, - response: JSON.stringify(ATIF_TRAJECTORY), -}; - describe("judge ATIF-trajectory observation (integration)", () => { let workspaceDir: string; let criteriaDir: string; @@ -87,8 +152,9 @@ describe("judge ATIF-trajectory observation (integration)", () => { " removed it before finishing (e.g. added left-pad then removed it). This", " is only derivable from the agent's trajectory (mid-run tool calls), not", " from the final codebase snapshot, because the dependency is absent in the", - " end state. Inspect the agent_trajectory_atif tool output to detect a", - " transient add-then-remove.", + " end state. Use list_agent_tool_calls to scan the agent's tool calls and", + " get_agent_tool_calls to inspect the relevant ones, detecting a transient", + " add-then-remove of a dependency.", "", ].join("\n"), ); @@ -114,13 +180,13 @@ describe("judge ATIF-trajectory observation (integration)", () => { "resolves a trajectory-only observation true WITH the ATIF, false WITHOUT it", { timeout: 600_000 }, async () => { - // (1) WITH the ATIF trajectory tool call → the agent's add-then-remove is - // visible, so the observation must resolve true. + // (1) WITH the ATIF trajectory → the agent's add-then-remove is visible via + // the navigation tools, so the observation must resolve true. const withAtif = await evaluateWorkspace({ workspacePath: workspaceDir, criteria: ["dependency_added_then_removed"], conversationHistory: [], - toolCalls: [TRAJECTORY_TOOL_CALL], + trajectory: fromAtif(REALISTIC_ATIF), }); const obsWith = withAtif.criteriaResults.find( From 4c1785fd14707959847dc94ba08179e689728329 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Mon, 29 Jun 2026 19:17:14 -0700 Subject: [PATCH 020/210] feat(shared): add criterion subject (run|iteration) + run-level observationResults (#1156) Introduce a kind-dependent `subject` discriminator on criteria so observation criteria can be evaluated either per-iteration (today) or once over the whole run. Gate criteria are always `iteration`. Adds: - CriterionSubject type + CRITERION_SUBJECTS + isCriterionSubject guard - subject on CriteriaConfig; run-level observationResults on RunState - zod schemas (optional, no flat default); kind-dependent default applied in the store (observation -> run, gate/legacy -> iteration) - subject threaded through criteria-store create/update/find + both providers - atifUrls[] on JudgeEvaluateRequest for merged whole-run trajectory - migration 022 backfills subject kind-aware (gate/legacy -> iteration, observation -> run) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../022-backfill-criteria-subject.ts | 76 +++++++++++++++++++ .../db-migrations/src/required-migrations.ts | 1 + .../src/criteria/criteria-provider-api.ts | 2 + .../src/criteria/criteria-provider-fs.ts | 8 ++ .../src/criteria/criteria-store.test.ts | 62 +++++++++++++++ .../shared/src/criteria/criteria-store.ts | 34 ++++++++- packages/shared/src/judge/judge-client.ts | 5 ++ packages/shared/src/schemas/criteria.ts | 7 +- packages/shared/src/schemas/request.ts | 4 + packages/shared/src/types/types.ts | 33 ++++++++ 10 files changed, 228 insertions(+), 4 deletions(-) create mode 100644 packages/db-migrations/src/migrations/022-backfill-criteria-subject.ts diff --git a/packages/db-migrations/src/migrations/022-backfill-criteria-subject.ts b/packages/db-migrations/src/migrations/022-backfill-criteria-subject.ts new file mode 100644 index 000000000..b3efd41c6 --- /dev/null +++ b/packages/db-migrations/src/migrations/022-backfill-criteria-subject.ts @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * Migration: Backfill criteria subject. + * + * The criterion `subject` field (issue #1156) controls the granularity at which + * an observation criterion is evaluated: `"iteration"` (per-turn) or `"run"` + * (once over the whole run). Gate criteria are always `"iteration"`. + * + * The backfill is kind-aware to match the new store defaults: + * - gate / legacy (kind absent) → "iteration" + * - observation → "run" + * + * Backfilling existing observations to "run" also corrects the + * `dependency_added_then_removed` false-negative that arose when whole-run + * observations were forced through per-iteration evaluation. Blast radius is + * negligible — #1156 is unmerged, so there are no production observation + * criteria yet. Mirrors 021-backfill-criteria-kind.ts. + * + * down() unsets `subject` on rows whose value is "run" or "iteration", + * restoring the pre-migration state. + */ + +import type { Db } from "mongodb"; +import type { MigrationInterface } from "mongo-migrate-ts"; +import { batchUpdate } from "../batch-update.js"; + +export class BackfillCriteriaSubject implements MigrationInterface { + async up(db: Db): Promise { + const criteria = db.collection("criteria"); + + // Gate + legacy (kind absent/null) → "iteration". + const gateCount = await batchUpdate( + criteria, + { + $and: [ + { $or: [{ subject: { $exists: false } }, { subject: null }] }, + { $or: [{ kind: "gate" }, { kind: { $exists: false } }, { kind: null }] }, + ], + }, + { $set: { subject: "iteration" } }, + "[022] backfill criteria.subject=iteration (gate/legacy)", + ); + + // Observation → "run". + const obsCount = await batchUpdate( + criteria, + { + $and: [ + { $or: [{ subject: { $exists: false } }, { subject: null }] }, + { kind: "observation" }, + ], + }, + { $set: { subject: "run" } }, + "[022] backfill criteria.subject=run (observation)", + ); + + console.log( + `[022] Backfilled subject: iteration on ${gateCount} gate/legacy criteria, run on ${obsCount} observation criteria`, + ); + } + + async down(db: Db): Promise { + const criteria = db.collection("criteria"); + + const count = await batchUpdate( + criteria, + { subject: { $in: ["run", "iteration"] } }, + { $unset: { subject: "" } }, + "[022-down] unset criteria.subject", + ); + + console.log(`[022-down] Unset subject on ${count} criteria`); + } +} diff --git a/packages/db-migrations/src/required-migrations.ts b/packages/db-migrations/src/required-migrations.ts index f5742e603..cf21cf82d 100644 --- a/packages/db-migrations/src/required-migrations.ts +++ b/packages/db-migrations/src/required-migrations.ts @@ -37,4 +37,5 @@ export const REQUIRED_MIGRATIONS: readonly string[] = [ "020-backfill-handler-status.ts", "020-create-codebase-indexes.ts", "021-backfill-criteria-kind.ts", + "022-backfill-criteria-subject.ts", ]; diff --git a/packages/shared/src/criteria/criteria-provider-api.ts b/packages/shared/src/criteria/criteria-provider-api.ts index 080dd1c9e..5ff916a6e 100644 --- a/packages/shared/src/criteria/criteria-provider-api.ts +++ b/packages/shared/src/criteria/criteria-provider-api.ts @@ -205,6 +205,7 @@ function mapToCriteriaConfig(data: Record): CriteriaConfig { const gates = data.gates as CriteriaConfig["gates"] | undefined; const kind = data.kind as CriteriaConfig["kind"] | undefined; const taxonomyElementId = data.taxonomyElementId as CriteriaConfig["taxonomyElementId"] | undefined; + const subject = data.subject as CriteriaConfig["subject"] | undefined; return { id: String(data.id), prompt: String(data.prompt), @@ -212,5 +213,6 @@ function mapToCriteriaConfig(data: Record): CriteriaConfig { ...(gates && gates.length > 0 ? { gates } : {}), ...(kind ? { kind } : {}), ...(taxonomyElementId ? { taxonomyElementId } : {}), + ...(subject ? { subject } : {}), }; } diff --git a/packages/shared/src/criteria/criteria-provider-fs.ts b/packages/shared/src/criteria/criteria-provider-fs.ts index 9c5042700..56fe94657 100644 --- a/packages/shared/src/criteria/criteria-provider-fs.ts +++ b/packages/shared/src/criteria/criteria-provider-fs.ts @@ -81,6 +81,14 @@ export class FileSystemCriteriaProvider implements CriteriaProvider { criteria.taxonomyElementId = String(taxonomyElementId).trim() as CriteriaConfig["taxonomyElementId"]; } + const subject = data.subject; + if (subject !== undefined) { + if (subject !== "run" && subject !== "iteration") { + throw new Error(`'subject' must be 'run' or 'iteration' in ${file}`); + } + criteria.subject = subject; + } + if (this.registry.has(criteria.id)) { throw new Error(`Duplicate criteria id '${criteria.id}' found in ${file}`); } diff --git a/packages/shared/src/criteria/criteria-store.test.ts b/packages/shared/src/criteria/criteria-store.test.ts index 07908886e..36342b74b 100644 --- a/packages/shared/src/criteria/criteria-store.test.ts +++ b/packages/shared/src/criteria/criteria-store.test.ts @@ -370,3 +370,65 @@ describe("CriteriaStore kind + taxonomy (issue #1156)", () => { await expect(store.resolveObservations(["gate"])).rejects.toThrow(CriteriaValidationError); }); }); + +describe("CriteriaStore subject (run | iteration)", () => { + it("defaults an observation's subject to 'run' when absent", async () => { + const store = new CriteriaStore(fakeCollection()); + const created = await store.create({ id: "obs_run", prompt: "p", kind: "observation" }); + expect(created.subject).toBe("run"); + }); + + it("defaults a gate's subject to 'iteration' when absent", async () => { + const store = new CriteriaStore(fakeCollection()); + const created = await store.create({ id: "g_iter", prompt: "p", kind: "gate" }); + expect(created.subject).toBe("iteration"); + }); + + it("defaults a legacy (kind-absent) criterion's subject to 'iteration'", async () => { + const store = new CriteriaStore(fakeCollection()); + const created = await store.create({ id: "legacy", prompt: "p" }); + expect(created.subject).toBe("iteration"); + }); + + it("persists an explicit subject:'iteration' override on an observation", async () => { + const store = new CriteriaStore(fakeCollection()); + const created = await store.create({ + id: "obs_iter", + prompt: "p", + kind: "observation", + subject: "iteration", + }); + expect(created.subject).toBe("iteration"); + }); + + it("rejects subject:'run' on a gate criterion", async () => { + const store = new CriteriaStore(fakeCollection()); + await expect( + store.create({ id: "g_run", prompt: "p", kind: "gate", subject: "run" }), + ).rejects.toThrow(CriteriaValidationError); + }); + + it("rejects subject:'run' on a legacy (kind-absent) criterion", async () => { + const store = new CriteriaStore(fakeCollection()); + await expect( + store.create({ id: "legacy_run", prompt: "p", subject: "run" }), + ).rejects.toThrow(CriteriaValidationError); + }); + + it("rejects flipping an observation to a gate while keeping subject:'run' on update", async () => { + const col = fakeCollection([ + { id: "obs_x", prompt: "p", dependsOn: [], kind: "observation", subject: "run", createdAt: new Date() }, + ]); + const store = new CriteriaStore(col); + await expect(store.update("obs_x", { kind: "gate" })).rejects.toThrow(CriteriaValidationError); + }); + + it("allows updating an observation's subject to 'iteration'", async () => { + const col = fakeCollection([ + { id: "obs_y", prompt: "p", dependsOn: [], kind: "observation", subject: "run", createdAt: new Date() }, + ]); + const store = new CriteriaStore(col); + const updated = await store.update("obs_y", { subject: "iteration" }); + expect(updated.subject).toBe("iteration"); + }); +}); diff --git a/packages/shared/src/criteria/criteria-store.ts b/packages/shared/src/criteria/criteria-store.ts index de51748df..2fd5dba8b 100644 --- a/packages/shared/src/criteria/criteria-store.ts +++ b/packages/shared/src/criteria/criteria-store.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. import { Collection } from 'mongodb'; -import { CriteriaConfig, CriteriaDocument, CriterionKind, GateId, TaxonomyElementId } from '../types/types.js'; +import { CriteriaConfig, CriteriaDocument, CriterionKind, CriterionSubject, GateId, TaxonomyElementId } from '../types/types.js'; import { DependencyGraph } from '../graph/dependency-graph.js'; import { gatesSatisfyInvariant } from '../gates/gates.js'; import { @@ -42,9 +42,13 @@ export class CriteriaStore { gates?: GateId[]; kind?: CriterionKind; taxonomyElementId?: TaxonomyElementId; + subject?: CriterionSubject; }): Promise { const { id, prompt, dependsOn = [], gates, taxonomyElementId } = input; const kind: CriterionKind = input.kind ?? 'gate'; + // Kind-dependent default: observation ⇒ "run" (whole-run), gate/legacy ⇒ + // "iteration". Applied here (where kind is known) — not a flat schema default. + const subject: CriterionSubject = input.subject ?? (kind === 'observation' ? 'run' : 'iteration'); // Validate ID format if (!/^[a-z][a-z0-9_]*$/.test(id)) { @@ -60,6 +64,14 @@ export class CriteriaStore { ); } + // subject "run" is only valid for observation criteria — gate criteria are + // always evaluated per iteration (their pass/fail feeds the per-turn loop). + if (subject !== 'iteration' && kind !== 'observation') { + throw new CriteriaValidationError( + `subject '${subject}' is not allowed for ${kind} criteria; gate criteria are always evaluated per iteration` + ); + } + // Check for duplicates among *active* criteria. const existing = await this.collection.findOne({ id, deletedAt: { $exists: false } }); if (existing) { @@ -97,6 +109,7 @@ export class CriteriaStore { ...(gates !== undefined && { gates }), kind, ...(taxonomyElementId !== undefined && { taxonomyElementId }), + subject, createdAt: new Date(), }; @@ -138,7 +151,7 @@ export class CriteriaStore { /** Update a criterion's prompt, dependencies and/or gate compatibility */ async update( id: string, - patch: { prompt?: string; dependsOn?: string[]; gates?: GateId[]; kind?: CriterionKind; taxonomyElementId?: TaxonomyElementId } + patch: { prompt?: string; dependsOn?: string[]; gates?: GateId[]; kind?: CriterionKind; taxonomyElementId?: TaxonomyElementId; subject?: CriterionSubject } ): Promise { const existing = await this.get(id); if (!existing) { @@ -180,12 +193,23 @@ export class CriteriaStore { ); } + // subject "run" is only valid for observation criteria. Resolve the effective + // subject (kind-dependent default when neither patch nor existing set it). + const effectiveSubject: CriterionSubject = + patch.subject ?? existing.subject ?? (effectiveKind === 'observation' ? 'run' : 'iteration'); + if (effectiveSubject !== 'iteration' && effectiveKind !== 'observation') { + throw new CriteriaValidationError( + `subject '${effectiveSubject}' is not allowed for ${effectiveKind} criteria; gate criteria are always evaluated per iteration` + ); + } + const update: Record = { updatedAt: new Date() }; if (patch.prompt !== undefined) update.prompt = patch.prompt.trim(); if (patch.dependsOn !== undefined) update.dependsOn = patch.dependsOn; if (patch.gates !== undefined) update.gates = patch.gates; if (patch.kind !== undefined) update.kind = patch.kind; if (patch.taxonomyElementId !== undefined) update.taxonomyElementId = patch.taxonomyElementId; + if (patch.subject !== undefined) update.subject = patch.subject; await this.collection.updateOne( { id, deletedAt: { $exists: false } }, @@ -255,6 +279,7 @@ export class CriteriaStore { ...(doc.gates !== undefined && { gates: doc.gates }), ...(doc.kind !== undefined && { kind: doc.kind }), ...(doc.taxonomyElementId !== undefined && { taxonomyElementId: doc.taxonomyElementId }), + ...(doc.subject !== undefined && { subject: doc.subject }), }); if (doc.dependsOn) { @@ -284,6 +309,7 @@ export class CriteriaStore { ...(c.gates !== undefined && { gates: c.gates }), ...(c.kind !== undefined && { kind: c.kind }), ...(c.taxonomyElementId !== undefined && { taxonomyElementId: c.taxonomyElementId }), + ...(c.subject !== undefined && { subject: c.subject }), })); const edges: { from: string; to: string }[] = []; @@ -307,13 +333,15 @@ export class CriteriaStore { for (const config of configs) { const existing = await this.collection.findOne({ id: config.id }); if (!existing) { + const seedKind: CriterionKind = config.kind ?? 'gate'; await this.collection.insertOne({ id: config.id, prompt: config.prompt, dependsOn: config.dependsOn || [], ...(config.gates !== undefined && { gates: config.gates }), - kind: config.kind ?? 'gate', + kind: seedKind, ...(config.taxonomyElementId !== undefined && { taxonomyElementId: config.taxonomyElementId }), + subject: config.subject ?? (seedKind === 'observation' ? 'run' : 'iteration'), createdAt: new Date(), } as any); inserted++; diff --git a/packages/shared/src/judge/judge-client.ts b/packages/shared/src/judge/judge-client.ts index c07cfa82f..336404f66 100644 --- a/packages/shared/src/judge/judge-client.ts +++ b/packages/shared/src/judge/judge-client.ts @@ -21,6 +21,11 @@ export interface JudgeEvaluateRequest { * tool calls; sent by pp-taxonomy in place of toolCallsUrl so observations * can be evaluated against the full agent trajectory. See issue #1156. */ atifUrl?: string; + /** Blob URLs of EVERY iteration's ATIF trajectory JSON, in iteration order. + * Sent by pp-taxonomy for `subject:"run"` observations so the judge merges + * them into one whole-run trajectory (cross-iteration behavior is visible in a + * single evaluation). Takes precedence over `atifUrl`. See issue #1156. */ + atifUrls?: string[]; } /** diff --git a/packages/shared/src/schemas/criteria.ts b/packages/shared/src/schemas/criteria.ts index efe0761c1..71715eefd 100644 --- a/packages/shared/src/schemas/criteria.ts +++ b/packages/shared/src/schemas/criteria.ts @@ -3,12 +3,13 @@ import { z } from "zod"; import { extendZodWithOpenApi } from "@asteasolutions/zod-to-openapi"; -import { GATES, CRITERION_KINDS, TAXONOMY_ELEMENT_IDS } from "../types/types.js"; +import { GATES, CRITERION_KINDS, CRITERION_SUBJECTS, TAXONOMY_ELEMENT_IDS } from "../types/types.js"; extendZodWithOpenApi(z); export const GateIdSchema = z.enum(GATES); export const CriterionKindSchema = z.enum(CRITERION_KINDS); +export const CriterionSubjectSchema = z.enum(CRITERION_SUBJECTS); export const TaxonomyElementIdSchema = z.enum(TAXONOMY_ELEMENT_IDS); export const CreateCriteriaInputSchema = z @@ -19,6 +20,7 @@ export const CreateCriteriaInputSchema = z gates: z.array(GateIdSchema).optional(), kind: CriterionKindSchema.default("gate"), taxonomyElementId: TaxonomyElementIdSchema.optional(), + subject: CriterionSubjectSchema.optional(), }) .openapi("CreateCriteriaInput"); @@ -29,6 +31,7 @@ export const UpdateCriteriaInputSchema = z gates: z.array(GateIdSchema).optional(), kind: CriterionKindSchema.optional(), taxonomyElementId: TaxonomyElementIdSchema.optional(), + subject: CriterionSubjectSchema.optional(), }) .openapi("UpdateCriteriaInput"); @@ -40,6 +43,7 @@ export const CriteriaResponseSchema = z gates: z.array(GateIdSchema).optional(), kind: CriterionKindSchema.optional(), taxonomyElementId: TaxonomyElementIdSchema.optional(), + subject: CriterionSubjectSchema.optional(), createdAt: z.coerce.date(), updatedAt: z.coerce.date().optional(), deletedAt: z.coerce.date().optional(), @@ -54,6 +58,7 @@ export const CriteriaGraphNodeSchema = z gates: z.array(GateIdSchema).optional(), kind: CriterionKindSchema.optional(), taxonomyElementId: TaxonomyElementIdSchema.optional(), + subject: CriterionSubjectSchema.optional(), }) .openapi("CriteriaGraphNode"); diff --git a/packages/shared/src/schemas/request.ts b/packages/shared/src/schemas/request.ts index 1abc04062..48f77e9eb 100644 --- a/packages/shared/src/schemas/request.ts +++ b/packages/shared/src/schemas/request.ts @@ -216,6 +216,10 @@ export const RunStateSchema = z rawChatFormat: z.string().optional(), pausedAt: z.coerce.date().optional(), resumedAt: z.coerce.date().optional(), + /** Whole-run observation results (one per selected subject:"run" observation + * criterion), evaluated once against the merged trajectory. Per-iteration + * observation results live on each turn's `observationResults`. #1156. */ + observationResults: z.array(CriterionResultSchema).optional(), }) .openapi("RunState"); diff --git a/packages/shared/src/types/types.ts b/packages/shared/src/types/types.ts index 34e708e16..5e5bd320b 100644 --- a/packages/shared/src/types/types.ts +++ b/packages/shared/src/types/types.ts @@ -78,6 +78,27 @@ export function isCriterionKind(value: unknown): value is CriterionKind { return typeof value === "string" && (CRITERION_KINDS as readonly string[]).includes(value); } +/** + * Granularity at which an observation criterion is evaluated. `"iteration"` + * evaluates each `run.turns[]` in isolation (result → `turn.observationResults`); + * `"run"` evaluates **once** over the whole run — the final snapshot + the merged + * trajectory across all iterations (result → run-level `run.observationResults`). + * + * Honored **only** by the observation/taxonomy pipeline. Gate criteria are always + * `"iteration"` (the API rejects `"run"` for gates). The kind-dependent default + * (observation ⇒ `"run"`, gate/legacy ⇒ `"iteration"`) is applied in the criteria + * store, not as a flat schema default. See issue #1156. + */ +export type CriterionSubject = "run" | "iteration"; + +/** The hard-coded set of criterion subjects. */ +export const CRITERION_SUBJECTS = ["run", "iteration"] as const; + +/** True when `value` is a valid criterion subject. */ +export function isCriterionSubject(value: unknown): value is CriterionSubject { + return typeof value === "string" && (CRITERION_SUBJECTS as readonly string[]).includes(value); +} + /** * Hard-coded taxonomy elements for observation criteria — the three quality * dimensions from the R&A Readout design. Gates (select/build/test/run/deploy) @@ -445,6 +466,12 @@ export interface RunState { rawChatFormat?: string; /** Per-handler post-processing status. Keys are handler IDs (e.g. "pp-atif"). */ handlerStatus?: Record; + /** Whole-run observation results — one entry per selected `subject:"run"` + * observation criterion, evaluated once against the final snapshot + the + * merged trajectory across all iterations by pp-taxonomy. Per-iteration + * (`subject:"iteration"`) observations live on `turn.observationResults` + * instead. Empty/absent when no run-subject observations were selected. #1156. */ + observationResults?: CriterionResult[]; /** Set once the scheduler has triggered report generation for this run after * the handler DAG drained (every handler reached a terminal state). Acts as * an exactly-once guard so the scheduler POSTs /api/v1/reports/trigger at @@ -651,6 +678,12 @@ export interface CriteriaConfig { /** Design-time classification under a hard-coded taxonomy element. Only set * on observation criteria. Static — never stored per run. See issue #1156. */ taxonomyElementId?: TaxonomyElementId; + /** Evaluation granularity for observation criteria. `"iteration"` (per-turn, + * → `turn.observationResults`) or `"run"` (once over the whole run, → + * `run.observationResults`). Honored only for observations; gates are always + * `"iteration"`. Kind-dependent default applied in the store (observation ⇒ + * "run", gate/legacy ⇒ "iteration"). See issue #1156. */ + subject?: CriterionSubject; } // Per-criterion result from judge evaluation From 01ec0a71653d93f2f0396ccf7ae5609b62bda24a Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Mon, 29 Jun 2026 19:17:54 -0700 Subject: [PATCH 021/210] feat(api): validate criterion subject + AI auto-detect (#1156) - routes/criteria: reject subject:run for gate criteria (400); allow run| iteration for observations on create + update - llm: authoring assistant returns suggestedSubject; heuristic maps cross- iteration phrasing -> run, end-state/per-step -> iteration; defaults run for observations when the model is unavailable - endpoints test: subject create + run-subject-gate rejection - regenerated OpenAPI snapshot (subject enum + run-level observationResults) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../openapi-snapshot.test.ts.snap | 34 +++++++++++++++++++ apps/api/src/endpoints.test.ts | 32 +++++++++++++++++ apps/api/src/llm.ts | 23 +++++++++++-- apps/api/src/routes/criteria.ts | 8 ++--- 4 files changed, 90 insertions(+), 7 deletions(-) diff --git a/apps/api/src/__snapshots__/openapi-snapshot.test.ts.snap b/apps/api/src/__snapshots__/openapi-snapshot.test.ts.snap index 3d5d038c9..7c09fa8b5 100644 --- a/apps/api/src/__snapshots__/openapi-snapshot.test.ts.snap +++ b/apps/api/src/__snapshots__/openapi-snapshot.test.ts.snap @@ -670,6 +670,13 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "prompt": { "type": "string", }, + "subject": { + "enum": [ + "run", + "iteration", + ], + "type": "string", + }, "taxonomyElementId": { "enum": [ "dimension:idiomatic-use", @@ -1058,6 +1065,13 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "prompt": { "type": "string", }, + "subject": { + "enum": [ + "run", + "iteration", + ], + "type": "string", + }, "taxonomyElementId": { "enum": [ "dimension:idiomatic-use", @@ -1121,6 +1135,13 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "prompt": { "type": "string", }, + "subject": { + "enum": [ + "run", + "iteration", + ], + "type": "string", + }, "taxonomyElementId": { "enum": [ "dimension:idiomatic-use", @@ -2626,6 +2647,12 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "logsUrl": { "type": "string", }, + "observationResults": { + "items": { + "$ref": "#/components/schemas/CriterionResult", + }, + "type": "array", + }, "os": { "properties": { "arch": { @@ -3161,6 +3188,13 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "prompt": { "type": "string", }, + "subject": { + "enum": [ + "run", + "iteration", + ], + "type": "string", + }, "taxonomyElementId": { "enum": [ "dimension:idiomatic-use", diff --git a/apps/api/src/endpoints.test.ts b/apps/api/src/endpoints.test.ts index 34a89df39..bfca5e19c 100644 --- a/apps/api/src/endpoints.test.ts +++ b/apps/api/src/endpoints.test.ts @@ -220,6 +220,38 @@ describe("API Endpoints", () => { expect(res.status).toBe(400); }); + + it("defaults an observation's subject to 'run'", async () => { + (mocks.criteriaCollection.findOne as any).mockResolvedValue(null); + + const res = await request(app) + .post("/api/v1/criteria") + .send({ id: "obs_subj", prompt: "Did the agent add then remove a dep?", dependsOn: [], kind: "observation" }); + + expect(res.status).toBe(201); + expect(res.body).toHaveProperty("subject", "run"); + }); + + it("creates an observation with an explicit subject:'iteration' override", async () => { + (mocks.criteriaCollection.findOne as any).mockResolvedValue(null); + + const res = await request(app) + .post("/api/v1/criteria") + .send({ id: "obs_iter", prompt: "x", dependsOn: [], kind: "observation", subject: "iteration" }); + + expect(res.status).toBe(201); + expect(res.body).toHaveProperty("subject", "iteration"); + }); + + it("rejects subject:'run' on a gate criterion", async () => { + (mocks.criteriaCollection.findOne as any).mockResolvedValue(null); + + const res = await request(app) + .post("/api/v1/criteria") + .send({ id: "gate_run", prompt: "x", dependsOn: [], kind: "gate", subject: "run" }); + + expect(res.status).toBe(400); + }); }); describe("POST /api/v1/criteria/seed", () => { diff --git a/apps/api/src/llm.ts b/apps/api/src/llm.ts index 7c4cd9328..bda126d6b 100644 --- a/apps/api/src/llm.ts +++ b/apps/api/src/llm.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. import { isUnexpected } from "@azure-rest/ai-inference"; -import { gatesSatisfyInvariant, type GateId } from "shared"; +import { gatesSatisfyInvariant, type GateId, type CriterionSubject } from "shared"; import { acquireInferenceClient, isLlmAvailable as inferenceAvailable } from "./llm-token.js"; export type SuggestDirection = "parents" | "children"; @@ -23,13 +23,18 @@ Given a natural-language description of a behavior or pattern to detect in a cod - Contain only lowercase letters, digits, and underscores - Be concise but descriptive (e.g., has_unit_tests, uses_typescript, has_docker_config) +3. Classify the evaluation SUBJECT — whether the behavior must be judged across the WHOLE run or within a SINGLE iteration in isolation: + - "run": the behavior spans multiple steps/iterations or describes a transition over the course of the session — phrasing like "at any point", "ever", "then later", "added then removed", "during the run", or anything only confirmable by viewing the entire run together. + - "iteration": the behavior is a single end-state fact or a per-step property judgeable from one iteration alone (e.g., "uses TypeScript", "has a Dockerfile", "ran the test suite this turn"). + When unsure, prefer "run". + Here are examples of good criteria prompts: - "The project uses Azure Bicep for infrastructure as code. Look for *.bicep files, bicepconfig.json, or main.bicep entry points." - "The project uses React framework. Look for react dependency in package.json, .jsx or .tsx files with React components." - "The project uses Node.js as its runtime environment. Look for package.json file or Node.js-specific configuration files." Respond with ONLY a JSON object in this exact format (no markdown, no code fences): -{"prompt": "your evaluation prompt here", "suggestedId": "your_suggested_id"}`; +{"prompt": "your evaluation prompt here", "suggestedId": "your_suggested_id", "suggestedSubject": "run"}`; interface SuggestDirectionCopy { /** One-line definition of the relationship being asked for. */ @@ -103,6 +108,10 @@ export interface GenerateResult { suggestedId: string; suggestedParents: string[]; suggestedChildren: string[]; + /** Suggested evaluation granularity for observation criteria. Defaults to + * "run"; "iteration" only when the model clearly detects an end-state / + * per-step property. Ignored by gate criteria (always per-iteration). #1156. */ + suggestedSubject: CriterionSubject; } export function isLlmAvailable(): boolean { @@ -122,6 +131,12 @@ function sanitizeId(suggestedId: unknown): string { return sanitized || "new_criterion"; } +/** Coerce a model-suggested subject. Defaults to "run" — "iteration" is only + * honored when the model returns it exactly (matching "prefer run when unsure"). */ +function sanitizeSubject(value: unknown): CriterionSubject { + return value === "iteration" ? "iteration" : "run"; +} + function parseJson(content: string): any { const cleaned = content.replace(/```json\s*|```\s*/g, "").trim(); try { @@ -169,7 +184,7 @@ async function author( llm: ChatClient, model: string, behavior: string, -): Promise<{ prompt: string; suggestedId: string }> { +): Promise<{ prompt: string; suggestedId: string; suggestedSubject: CriterionSubject }> { const content = await chat(llm, model, SYSTEM_PROMPT_AUTHOR, `NEW CRITERION TO CREATE:\n${behavior}`); const parsed = parseJson(content); if (!parsed.prompt) { @@ -178,6 +193,7 @@ async function author( return { prompt: String(parsed.prompt).trim(), suggestedId: sanitizeId(parsed.suggestedId), + suggestedSubject: sanitizeSubject(parsed.suggestedSubject), }; } @@ -274,5 +290,6 @@ export async function generateCriteriaPrompt( suggestedId: authored.suggestedId, suggestedParents, suggestedChildren, + suggestedSubject: authored.suggestedSubject, }; } diff --git a/apps/api/src/routes/criteria.ts b/apps/api/src/routes/criteria.ts index 40aee5d0c..7be113e11 100644 --- a/apps/api/src/routes/criteria.ts +++ b/apps/api/src/routes/criteria.ts @@ -427,9 +427,9 @@ apiRoute(ctx.app, ctx.registry, { 409: { description: "Criterion already exists" }, }, handler: async (req, res) => { - const { id, prompt, dependsOn = [], gates, kind, taxonomyElementId } = req.body; + const { id, prompt, dependsOn = [], gates, kind, taxonomyElementId, subject } = req.body; try { - const doc = await getCriteriaStore().create({ id, prompt, dependsOn, gates, kind, taxonomyElementId }); + const doc = await getCriteriaStore().create({ id, prompt, dependsOn, gates, kind, taxonomyElementId, subject }); res.status(201).json(doc); } catch (err) { if (!sendStoreError(res, err)) throw err; @@ -452,9 +452,9 @@ apiRoute(ctx.app, ctx.registry, { }, handler: async (req, res) => { const { id } = req.params; - const { prompt, dependsOn, gates, kind, taxonomyElementId } = req.body; + const { prompt, dependsOn, gates, kind, taxonomyElementId, subject } = req.body; try { - const updated = await getCriteriaStore().update(id, { prompt, dependsOn, gates, kind, taxonomyElementId }); + const updated = await getCriteriaStore().update(id, { prompt, dependsOn, gates, kind, taxonomyElementId, subject }); res.json(updated); } catch (err) { if (!sendStoreError(res, err)) throw err; From aa92dbe43484c8085dfc15740017d6b1098f4996 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Mon, 29 Jun 2026 19:18:49 -0700 Subject: [PATCH 022/210] feat(judge): merge whole-run trajectory from atifUrls[] (#1156) - agent-trajectory: mergeTrajectories(list) concatenates calls in iteration order and unions tool definitions by id; fromAtifList helper - index: accept atifUrls[]; download all + merge into the single AgentTrajectory (single atifUrl path unchanged) - integration test: run-subject dependency_added_then_removed is false per iteration but true on the merged trajectory (GITHUB_TOKEN-gated) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- apps/judge/src/agent-trajectory.test.ts | 82 +++++++++++++++++ apps/judge/src/agent-trajectory.ts | 83 +++++++++++++++++ apps/judge/src/index.ts | 22 ++++- ...observation-trajectory.integration.test.ts | 92 ++++++++++++++++++- 4 files changed, 275 insertions(+), 4 deletions(-) diff --git a/apps/judge/src/agent-trajectory.test.ts b/apps/judge/src/agent-trajectory.test.ts index 78252d88f..8bb870184 100644 --- a/apps/judge/src/agent-trajectory.test.ts +++ b/apps/judge/src/agent-trajectory.test.ts @@ -17,7 +17,9 @@ import { join, sep } from "path"; import type { ToolCall } from "shared"; import { fromAtif, + fromAtifList, fromToolCalls, + mergeTrajectories, createTrajectoryTools, summarizeArgs, safeId, @@ -444,3 +446,83 @@ describe("helpers", () => { expect(previewOf("abc", 10)).toBe("abc"); }); }); + +describe("mergeTrajectories / fromAtifList (run-subject whole-run path #1156)", () => { + it("returns an empty trajectory for an empty list", () => { + const merged = mergeTrajectories([]); + expect(merged.calls).toEqual([]); + expect(merged.toolDefinitions).toEqual([]); + expect(merged.byId.size).toBe(0); + }); + + it("returns the single trajectory unchanged for a length-1 list", () => { + const only = fromAtif(REALISTIC_ATIF); + expect(mergeTrajectories([only])).toBe(only); + }); + + it("concatenates calls in iteration order and preserves both iterations' work", () => { + const it1 = fromToolCalls([ + { id: "a", name: "bash", arguments: { command: "npm install left-pad" }, response: "added 1 package", timestamp: "" }, + ]); + const it2 = fromToolCalls([ + { id: "b", name: "bash", arguments: { command: "npm uninstall left-pad" }, response: "removed 1 package", timestamp: "" }, + ]); + const merged = mergeTrajectories([it1, it2]); + expect(merged.calls.map((c) => c.toolCallId)).toEqual(["a", "b"]); + expect(merged.calls[0].response).toContain("added"); + expect(merged.calls[1].response).toContain("removed"); + // Both addressable by id. + expect(merged.byId.get("a")?.summary).toBe("npm install left-pad"); + expect(merged.byId.get("b")?.summary).toBe("npm uninstall left-pad"); + }); + + it("re-keys colliding tool-call ids so every call stays addressable", () => { + const it1 = fromToolCalls([{ id: "dup", name: "bash", arguments: { command: "first" }, response: "r1", timestamp: "" }]); + const it2 = fromToolCalls([{ id: "dup", name: "bash", arguments: { command: "second" }, response: "r2", timestamp: "" }]); + const merged = mergeTrajectories([it1, it2]); + expect(merged.calls).toHaveLength(2); + const ids = merged.calls.map((c) => c.toolCallId); + expect(ids[0]).toBe("dup"); + expect(ids[1]).toBe("it2:dup"); + expect(new Set(ids).size).toBe(2); + expect(merged.byId.get("dup")?.summary).toBe("first"); + expect(merged.byId.get("it2:dup")?.summary).toBe("second"); + }); + + it("unions tool definitions by name (first wins)", () => { + const a = fromAtif(REALISTIC_ATIF); // has a populated catalog + const b = fromAtif(REALISTIC_ATIF); + const merged = mergeTrajectories([a, b]); + // Deduplicated, not doubled. + expect(merged.toolDefinitions.length).toBe(a.toolDefinitions.length); + expect(merged.toolDefsByName.size).toBe(a.toolDefsByName.size); + }); + + it("tags merged step overviews with their source iteration", () => { + const merged = mergeTrajectories([fromAtif(REALISTIC_ATIF), fromAtif(REALISTIC_ATIF)]); + expect(merged.steps?.some((s) => s.source.startsWith("it1:"))).toBe(true); + expect(merged.steps?.some((s) => s.source.startsWith("it2:"))).toBe(true); + }); + + it("fromAtifList normalizes + merges raw ATIF payloads", () => { + const merged = fromAtifList([REALISTIC_ATIF, REALISTIC_ATIF]); + expect(merged.source).toBe("atif"); + // Twice the agent calls of a single ATIF. + const single = fromAtif(REALISTIC_ATIF); + expect(merged.calls.length).toBe(single.calls.length * 2); + }); + + it("merged trajectory is navigable via createTrajectoryTools across iterations", async () => { + const it1 = fromToolCalls([{ id: "x", name: "bash", arguments: { command: "npm install left-pad" }, response: "added", timestamp: "" }]); + const it2 = fromToolCalls([{ id: "y", name: "bash", arguments: { command: "npm uninstall left-pad" }, response: "removed", timestamp: "" }]); + const spillDir = mkdtempSync(join(tmpdir(), "judge-merge-spill-")); + try { + const tools = createTrajectoryTools(mergeTrajectories([it1, it2]), spillDir); + const res = await call(tools, "list_agent_tool_calls"); + expect(res.count).toBe(2); + expect(res.calls.map((c: any) => c.toolCallId)).toEqual(["x", "y"]); + } finally { + rmSync(spillDir, { recursive: true, force: true }); + } + }); +}); diff --git a/apps/judge/src/agent-trajectory.ts b/apps/judge/src/agent-trajectory.ts index 29b20a469..fe1ae85cb 100644 --- a/apps/judge/src/agent-trajectory.ts +++ b/apps/judge/src/agent-trajectory.ts @@ -364,6 +364,89 @@ export function fromAtif(input: unknown): AgentTrajectory { }; } +/** + * Merge several {@link AgentTrajectory}s (e.g. one per iteration) into a single + * whole-run trajectory for `subject:"run"` observation evaluation (#1156). + * + * - `calls` are concatenated in iteration order. Colliding `toolCallId`s (the + * ATIF synthesizes step-local ids like `atif-3-0` that restart each iteration) + * are re-keyed `it:` so every call stays addressable via + * `get_agent_tool_calls`. + * - `toolDefinitions` are unioned by name (first wins). + * - `steps` are concatenated, each tagged with its source iteration. + * + * A list of length 0 yields an empty trajectory; length 1 is returned as-is. + */ +export function mergeTrajectories(list: AgentTrajectory[]): AgentTrajectory { + const items = (list ?? []).filter((t): t is AgentTrajectory => Boolean(t)); + if (items.length === 0) { + return { + source: "atif", + calls: [], + byId: new Map(), + toolDefinitions: [], + toolDefsByName: new Map(), + }; + } + if (items.length === 1) return items[0]; + + const calls: AgentToolCall[] = []; + const seen = new Set(); + items.forEach((traj, t) => { + for (const call of traj.calls) { + let uid = call.toolCallId; + if (seen.has(uid)) { + uid = `it${t + 1}:${call.toolCallId}`; + let k = 1; + while (seen.has(uid)) uid = `it${t + 1}:${call.toolCallId}-${k++}`; + } + seen.add(uid); + calls.push(uid === call.toolCallId ? call : { ...call, toolCallId: uid }); + } + }); + + const toolDefinitions: AgentToolDefinition[] = []; + const toolDefsByName = new Map(); + for (const traj of items) { + for (const def of traj.toolDefinitions) { + if (!toolDefsByName.has(def.name)) { + toolDefsByName.set(def.name, def); + toolDefinitions.push(def); + } + } + } + + const steps: StepOverview[] = []; + items.forEach((traj, t) => { + for (const s of traj.steps ?? []) { + steps.push({ ...s, source: `it${t + 1}:${s.source}` }); + } + }); + + const first = items[0]; + const anyAtif = items.some((x) => x.source === "atif"); + return { + source: anyAtif ? "atif" : "tool-calls", + agent: first.agent, + model: first.model, + calls, + byId: buildById(calls), + toolDefinitions, + toolDefsByName, + steps: steps.length > 0 ? steps : undefined, + finalMetrics: items[items.length - 1]?.finalMetrics, + }; +} + +/** + * Normalize a list of raw ATIF payloads (one per iteration) into a single + * merged whole-run {@link AgentTrajectory}. Convenience over + * {@link mergeTrajectories} ∘ {@link fromAtif}. + */ +export function fromAtifList(inputs: unknown[]): AgentTrajectory { + return mergeTrajectories((inputs ?? []).map((x) => fromAtif(x))); +} + // --------------------------------------------------------------------------- // Tools // --------------------------------------------------------------------------- diff --git a/apps/judge/src/index.ts b/apps/judge/src/index.ts index fd5a42e38..7702b381c 100644 --- a/apps/judge/src/index.ts +++ b/apps/judge/src/index.ts @@ -5,7 +5,7 @@ import express, { Request, Response, NextFunction } from "express"; import dotenv from "dotenv"; import { evaluateWorkspace } from "./judge-agent.js"; import { verifyCopilotProtocol } from "./protocol-check.js"; -import { type AgentTrajectory, fromAtif, fromToolCalls } from "./agent-trajectory.js"; +import { type AgentTrajectory, fromAtif, fromAtifList, fromToolCalls } from "./agent-trajectory.js"; import { BlobStorage, RedisLogPublisher } from "shared"; import { mkdtempSync, rmSync } from "fs"; import { tmpdir } from "os"; @@ -53,7 +53,7 @@ app.post( const startTime = Date.now(); try { - const { snapshotUrl, criteria, conversationHistory, personaInstructions, requestId, gate, toolCallsUrl, atifUrl } = req.body; + const { snapshotUrl, criteria, conversationHistory, personaInstructions, requestId, gate, toolCallsUrl, atifUrl, atifUrls } = req.body; // Validate required fields if (!snapshotUrl || typeof snapshotUrl !== "string") { @@ -100,7 +100,23 @@ app.post( // Failures are non-fatal — the judge can still evaluate the workspace // files. See apps/judge/src/agent-trajectory.ts. let trajectory: AgentTrajectory | undefined; - if (atifUrl && typeof atifUrl === "string") { + if (Array.isArray(atifUrls) && atifUrls.length > 0) { + // Run-subject observations (#1156): merge every iteration's ATIF into + // one whole-run trajectory so cross-iteration behavior (e.g. a dep added + // in one turn and removed in another) is visible in a single evaluation. + const urls = atifUrls.filter((u: unknown): u is string => typeof u === "string"); + try { + const atifs = await Promise.all(urls.map((u) => blobStorage.downloadJson(u))); + trajectory = fromAtifList(atifs); + console.log( + `[judge] Loaded merged ATIF trajectory from ${urls.length} iteration(s): ${trajectory.calls.length} call(s), ${trajectory.toolDefinitions.length} tool definition(s)`, + ); + } catch (err) { + console.warn( + `[judge] Failed to load merged ATIF from ${urls.length} url(s): ${err instanceof Error ? err.message : String(err)}`, + ); + } + } else if (atifUrl && typeof atifUrl === "string") { try { const atif = await blobStorage.downloadJson(atifUrl); trajectory = fromAtif(atif); diff --git a/apps/judge/src/observation-trajectory.integration.test.ts b/apps/judge/src/observation-trajectory.integration.test.ts index 185a6b54b..066c40da3 100644 --- a/apps/judge/src/observation-trajectory.integration.test.ts +++ b/apps/judge/src/observation-trajectory.integration.test.ts @@ -27,7 +27,7 @@ import { mkdtempSync, writeFileSync, rmSync, realpathSync } from "fs"; import { tmpdir } from "os"; import { join } from "path"; import { resetCriteriaProvider } from "shared/criteria-provider-factory"; -import { fromAtif } from "./agent-trajectory.js"; +import { fromAtif, fromAtifList } from "./agent-trajectory.js"; import { evaluateWorkspace } from "./judge-agent.js"; const hasToken = !!process.env.GITHUB_TOKEN; @@ -228,4 +228,94 @@ describe("judge ATIF-trajectory observation (integration)", () => { } expect(true).toBe(true); }); + + // The run-subject "killer" test (#1156): the add-then-remove is split ACROSS + // iterations — iteration 1 installs left-pad, iteration 2 uninstalls it. Each + // per-iteration ATIF alone is `false` (one only adds, the other only removes), + // but the MERGED whole-run trajectory reveals the add-then-remove → `true`. + // This is exactly the cross-iteration property the `subject:"run"` path exists + // to evaluate, and the false-negative the user flagged. + const ATIF_INSTALL = { + schema_version: "atif/1", + session_id: "atif-it1-install", + agent: { name: "copilot", version: "1.0.0", model_name: "claude-opus-4.6", tool_definitions: [] }, + steps: [ + { step_id: 1, source: "system" }, + { + step_id: 2, + source: "agent", + model_name: "claude-opus-4.6", + reasoning_content: "Add left-pad to pad output.", + tool_calls: [{ tool_call_id: "i1-c1", function_name: "bash", arguments: { command: "npm install left-pad" } }], + observation: { results: [{ source_call_id: "i1-c1", content: "added 1 package\n+ left-pad@1.3.0" }] }, + }, + ], + }; + + const ATIF_UNINSTALL = { + schema_version: "atif/1", + session_id: "atif-it2-uninstall", + agent: { name: "copilot", version: "1.0.0", model_name: "claude-opus-4.6", tool_definitions: [] }, + steps: [ + { step_id: 1, source: "system" }, + { + step_id: 2, + source: "agent", + model_name: "claude-opus-4.6", + reasoning_content: "Remove left-pad; not needed.", + tool_calls: [{ tool_call_id: "i2-c1", function_name: "bash", arguments: { command: "npm uninstall left-pad" } }], + observation: { results: [{ source_call_id: "i2-c1", content: "removed 1 package\nfound 0 vulnerabilities" }] }, + }, + ], + }; + + it.skipIf(!hasToken)( + "run-subject: false per-iteration but true on the MERGED whole-run trajectory", + { timeout: 600_000 }, + async () => { + // (1) Iteration 1 alone (install only) → no add-then-remove → false. + const it1 = await evaluateWorkspace({ + workspacePath: workspaceDir, + criteria: ["dependency_added_then_removed"], + conversationHistory: [], + trajectory: fromAtif(ATIF_INSTALL), + }); + const it1Obs = it1.criteriaResults.find((r) => r.criterionId === "dependency_added_then_removed"); + expect(it1Obs!.evaluated).toBe(true); + expect( + it1Obs!.passed, + `iteration 1 (install only) should be false. Feedback: ${it1Obs!.feedback}`, + ).toBe(false); + + // (2) Iteration 2 alone (uninstall only) → no add-then-remove → false. + const it2 = await evaluateWorkspace({ + workspacePath: workspaceDir, + criteria: ["dependency_added_then_removed"], + conversationHistory: [], + trajectory: fromAtif(ATIF_UNINSTALL), + }); + const it2Obs = it2.criteriaResults.find((r) => r.criterionId === "dependency_added_then_removed"); + expect(it2Obs!.evaluated).toBe(true); + expect( + it2Obs!.passed, + `iteration 2 (uninstall only) should be false. Feedback: ${it2Obs!.feedback}`, + ).toBe(false); + + // (3) MERGED whole-run trajectory (install in it1 + uninstall in it2) → + // the add-then-remove is now visible → true. This is what subject:"run" + // sends the judge as `atifUrls` and is the false-negative the feature fixes. + const merged = await evaluateWorkspace({ + workspacePath: workspaceDir, + criteria: ["dependency_added_then_removed"], + conversationHistory: [], + trajectory: fromAtifList([ATIF_INSTALL, ATIF_UNINSTALL]), + }); + const mergedObs = merged.criteriaResults.find((r) => r.criterionId === "dependency_added_then_removed"); + expect(mergedObs!.evaluated).toBe(true); + expect( + mergedObs!.passed, + `merged whole-run trajectory should be true (add in it1, remove in it2). Feedback: ${mergedObs!.feedback}`, + ).toBe(true); + }, + ); }); From 4fc56b5c8fa1051be7737b846438355056935733 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Mon, 29 Jun 2026 19:19:19 -0700 Subject: [PATCH 023/210] =?UTF-8?q?feat(pp-taxonomy):=20honor=20criterion?= =?UTF-8?q?=20subject=20=E2=80=94=20whole-run=20vs=20per-iteration=20(#115?= =?UTF-8?q?6)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - taxonomy-handler: resolve selected observations with their subject; split into iteration vs run buckets. Iteration-subject -> per-turn observationResults (unchanged). Run-subject -> evaluate once (final snapshot + every turn's atifUrl merged + full conversationHistory) -> run-level run.observationResults. Runs once because the handler runs once per run (the scheduler never sets message.iteration), so no idempotency guard needed. - HandlerContext gains criteriaCollection so handlers can resolve criterion metadata by id; wired in post-processor + atif-handler test contexts Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../src/handlers/atif-handler.test.ts | 1 + .../handlers/atif-handler.websocket.test.ts | 1 + .../src/handlers/taxonomy-handler.test.ts | 198 +++++++++++++++--- .../src/handlers/taxonomy-handler.ts | 126 ++++++++++- .../post-processor/src/post-processor.ts | 1 + apps/workers/post-processor/src/types.ts | 3 + 6 files changed, 287 insertions(+), 43 deletions(-) diff --git a/apps/workers/post-processor/src/handlers/atif-handler.test.ts b/apps/workers/post-processor/src/handlers/atif-handler.test.ts index bda415ad1..41e5520be 100644 --- a/apps/workers/post-processor/src/handlers/atif-handler.test.ts +++ b/apps/workers/post-processor/src/handlers/atif-handler.test.ts @@ -49,6 +49,7 @@ describe("AtifHandler", () => { }), updateOne: vi.fn().mockResolvedValue({ modifiedCount: 1 }), } as any, + criteriaCollection: {} as any, log: vi.fn().mockResolvedValue(undefined), }; }); diff --git a/apps/workers/post-processor/src/handlers/atif-handler.websocket.test.ts b/apps/workers/post-processor/src/handlers/atif-handler.websocket.test.ts index 19c1df8e2..fbe9daffd 100644 --- a/apps/workers/post-processor/src/handlers/atif-handler.websocket.test.ts +++ b/apps/workers/post-processor/src/handlers/atif-handler.websocket.test.ts @@ -53,6 +53,7 @@ describe("AtifHandler WebSocket HAR extraction (real atifact)", () => { }), updateOne: async () => ({ modifiedCount: 1 }), } as any, + criteriaCollection: {} as any, log: async () => undefined, }; }); diff --git a/apps/workers/post-processor/src/handlers/taxonomy-handler.test.ts b/apps/workers/post-processor/src/handlers/taxonomy-handler.test.ts index 4b328b8e6..0a17a7fe5 100644 --- a/apps/workers/post-processor/src/handlers/taxonomy-handler.test.ts +++ b/apps/workers/post-processor/src/handlers/taxonomy-handler.test.ts @@ -6,13 +6,24 @@ import { JudgeInfrastructureError, type JudgeClient } from "shared"; import { TaxonomyHandler } from "./taxonomy-handler.js"; import type { HandlerContext, PostProcessorMessage } from "../types.js"; -function makeCtx(doc: unknown): HandlerContext & { collection: { updateOne: ReturnType } } { +interface CriterionMeta { + id: string; + subject?: "run" | "iteration"; +} + +function makeCtx( + doc: unknown, + metas: CriterionMeta[] = [], +): HandlerContext & { collection: { updateOne: ReturnType } } { return { blobStorage: {} as any, collection: { findOne: vi.fn().mockResolvedValue(doc), updateOne: vi.fn().mockResolvedValue({ modifiedCount: 1 }), } as any, + criteriaCollection: { + find: vi.fn().mockReturnValue({ toArray: vi.fn().mockResolvedValue(metas) }), + } as any, log: vi.fn().mockResolvedValue(undefined), } as any; } @@ -51,44 +62,165 @@ describe("TaxonomyHandler", () => { expect(ctx.collection.updateOne).not.toHaveBeenCalled(); }); - it("writes judge criteriaResults to each turn's observationResults and sends atifUrl", async () => { - judge.evaluate.mockResolvedValue({ - passed: true, - feedback: "ok", - criteriaResults: [{ criterionId: "dep_removed", passed: true, feedback: "left-pad removed", evaluated: true }], - }); - const ctx = makeCtx({ - _id: "req-1", - observations: ["dep_removed"], - run: { - turns: [{ iteration: 1, snapshotUrl: "s://1", atifUrl: "a://1" }], - }, + describe("subject:iteration", () => { + it("writes judge criteriaResults to each turn's observationResults and sends atifUrl", async () => { + judge.evaluate.mockResolvedValue({ + passed: true, + feedback: "ok", + criteriaResults: [{ criterionId: "uses_ts", passed: true, feedback: "tsconfig present", evaluated: true }], + }); + const ctx = makeCtx( + { + _id: "req-1", + observations: ["uses_ts"], + run: { turns: [{ iteration: 1, snapshotUrl: "s://1", atifUrl: "a://1" }] }, + }, + [{ id: "uses_ts", subject: "iteration" }], + ); + + await new TaxonomyHandler(judge as unknown as JudgeClient).process(msg, ctx); + + expect(judge.evaluate).toHaveBeenCalledWith( + expect.objectContaining({ snapshotUrl: "s://1", criteria: ["uses_ts"], atifUrl: "a://1" }), + ); + const call = judge.evaluate.mock.calls[0][0]; + expect(call.gate).toBeUndefined(); + expect(call.toolCallsUrl).toBeUndefined(); + expect(call.atifUrls).toBeUndefined(); + expect(ctx.collection.updateOne).toHaveBeenCalledWith( + { _id: "req-1", "run.turns.iteration": 1 }, + { $set: { "run.turns.$.observationResults": [{ criterionId: "uses_ts", passed: true, feedback: "tsconfig present", evaluated: true }] } }, + ); }); - await new TaxonomyHandler(judge as unknown as JudgeClient).process(msg, ctx); + it("skips iterations without a snapshotUrl", async () => { + judge.evaluate.mockResolvedValue({ passed: true, feedback: "", criteriaResults: [] }); + const ctx = makeCtx( + { _id: "req-1", observations: ["c1"], run: { turns: [{ iteration: 1 }] } }, + [{ id: "c1", subject: "iteration" }], + ); + await new TaxonomyHandler(judge as unknown as JudgeClient).process(msg, ctx); + expect(judge.evaluate).not.toHaveBeenCalled(); + }); - expect(judge.evaluate).toHaveBeenCalledWith( - expect.objectContaining({ snapshotUrl: "s://1", criteria: ["dep_removed"], atifUrl: "a://1" }), - ); - const call = judge.evaluate.mock.calls[0][0]; - expect(call.gate).toBeUndefined(); - expect(call.toolCallsUrl).toBeUndefined(); - expect(ctx.collection.updateOne).toHaveBeenCalledWith( - { _id: "req-1", "run.turns.iteration": 1 }, - { $set: { "run.turns.$.observationResults": [{ criterionId: "dep_removed", passed: true, feedback: "left-pad removed", evaluated: true }] } }, - ); + it("throws on judge infrastructure error so the handler is marked failed", async () => { + judge.evaluate.mockRejectedValue(new JudgeInfrastructureError("down", { httpStatus: 503 })); + const ctx = makeCtx( + { _id: "req-1", observations: ["c1"], run: { turns: [{ iteration: 1, snapshotUrl: "s://1" }] } }, + [{ id: "c1", subject: "iteration" }], + ); + await expect(new TaxonomyHandler(judge as unknown as JudgeClient).process(msg, ctx)).rejects.toThrow("down"); + }); }); - it("skips iterations without a snapshotUrl", async () => { - judge.evaluate.mockResolvedValue({ passed: true, feedback: "", criteriaResults: [] }); - const ctx = makeCtx({ _id: "req-1", observations: ["c1"], run: { turns: [{ iteration: 1 }] } }); - await new TaxonomyHandler(judge as unknown as JudgeClient).process(msg, ctx); - expect(judge.evaluate).not.toHaveBeenCalled(); + describe("subject:run", () => { + it("evaluates ONCE over the merged trajectory and writes run-level observationResults", async () => { + judge.evaluate.mockResolvedValue({ + passed: true, + feedback: "ok", + criteriaResults: [ + { criterionId: "dep_added_then_removed", passed: true, feedback: "left-pad added then removed", evaluated: true }, + ], + }); + const ctx = makeCtx( + { + _id: "req-1", + observations: ["dep_added_then_removed"], + run: { + turns: [ + { iteration: 1, snapshotUrl: "s://1", atifUrl: "a://1" }, + { iteration: 2, snapshotUrl: "s://2", atifUrl: "a://2" }, + ], + }, + }, + [{ id: "dep_added_then_removed", subject: "run" }], + ); + + await new TaxonomyHandler(judge as unknown as JudgeClient).process(msg, ctx); + + // One judge call, using the FINAL snapshot + EVERY iteration's atif merged. + expect(judge.evaluate).toHaveBeenCalledTimes(1); + expect(judge.evaluate).toHaveBeenCalledWith( + expect.objectContaining({ + snapshotUrl: "s://2", + criteria: ["dep_added_then_removed"], + atifUrls: ["a://1", "a://2"], + }), + ); + const call = judge.evaluate.mock.calls[0][0]; + expect(call.atifUrl).toBeUndefined(); + // Written at the RUN level, not on any turn. + expect(ctx.collection.updateOne).toHaveBeenCalledWith( + { _id: "req-1" }, + { $set: { "run.observationResults": [{ criterionId: "dep_added_then_removed", passed: true, feedback: "left-pad added then removed", evaluated: true }] } }, + ); + }); + + it("defaults a subject-less observation to run (whole-run evaluation)", async () => { + judge.evaluate.mockResolvedValue({ passed: false, feedback: "no", criteriaResults: [] }); + const ctx = makeCtx( + { + _id: "req-1", + observations: ["legacy_obs"], + run: { turns: [{ iteration: 1, snapshotUrl: "s://1", atifUrl: "a://1" }] }, + }, + [{ id: "legacy_obs" }], // no subject → defaults to run + ); + + await new TaxonomyHandler(judge as unknown as JudgeClient).process(msg, ctx); + + expect(judge.evaluate).toHaveBeenCalledTimes(1); + const call = judge.evaluate.mock.calls[0][0]; + expect(call.atifUrls).toEqual(["a://1"]); + expect(ctx.collection.updateOne).toHaveBeenCalledWith( + { _id: "req-1" }, + expect.objectContaining({ $set: expect.objectContaining({ "run.observationResults": [] }) }), + ); + }); + + it("throws on judge infrastructure error during the run-subject evaluation", async () => { + judge.evaluate.mockRejectedValue(new JudgeInfrastructureError("down", { httpStatus: 503 })); + const ctx = makeCtx( + { _id: "req-1", observations: ["r1"], run: { turns: [{ iteration: 1, snapshotUrl: "s://1", atifUrl: "a://1" }] } }, + [{ id: "r1", subject: "run" }], + ); + await expect(new TaxonomyHandler(judge as unknown as JudgeClient).process(msg, ctx)).rejects.toThrow("down"); + }); }); - it("throws on judge infrastructure error so the handler is marked failed", async () => { - judge.evaluate.mockRejectedValue(new JudgeInfrastructureError("down", { httpStatus: 503 })); - const ctx = makeCtx({ _id: "req-1", observations: ["c1"], run: { turns: [{ iteration: 1, snapshotUrl: "s://1" }] } }); - await expect(new TaxonomyHandler(judge as unknown as JudgeClient).process(msg, ctx)).rejects.toThrow("down"); + describe("mixed subjects", () => { + it("routes iteration and run observations to their respective evaluations", async () => { + judge.evaluate.mockResolvedValue({ passed: true, feedback: "ok", criteriaResults: [] }); + const ctx = makeCtx( + { + _id: "req-1", + observations: ["iter_obs", "run_obs"], + run: { + turns: [ + { iteration: 1, snapshotUrl: "s://1", atifUrl: "a://1" }, + { iteration: 2, snapshotUrl: "s://2", atifUrl: "a://2" }, + ], + }, + }, + [ + { id: "iter_obs", subject: "iteration" }, + { id: "run_obs", subject: "run" }, + ], + ); + + await new TaxonomyHandler(judge as unknown as JudgeClient).process(msg, ctx); + + // 2 iteration calls (one per turn) + 1 run call = 3 total. + expect(judge.evaluate).toHaveBeenCalledTimes(3); + const iterationCalls = judge.evaluate.mock.calls.filter((c) => c[0].criteria.includes("iter_obs")); + const runCalls = judge.evaluate.mock.calls.filter((c) => c[0].criteria.includes("run_obs")); + expect(iterationCalls).toHaveLength(2); + expect(runCalls).toHaveLength(1); + // The iteration eval only carries the iteration-subject criterion. + expect(iterationCalls[0][0].criteria).toEqual(["iter_obs"]); + // The run eval only carries the run-subject criterion, merged trajectory. + expect(runCalls[0][0].criteria).toEqual(["run_obs"]); + expect(runCalls[0][0].atifUrls).toEqual(["a://1", "a://2"]); + }); }); }); diff --git a/apps/workers/post-processor/src/handlers/taxonomy-handler.ts b/apps/workers/post-processor/src/handlers/taxonomy-handler.ts index 571320317..252be22a3 100644 --- a/apps/workers/post-processor/src/handlers/taxonomy-handler.ts +++ b/apps/workers/post-processor/src/handlers/taxonomy-handler.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. import { JudgeClient, isRetryableJudgeError } from "shared"; -import type { ConversationTurn, CriterionResult } from "shared"; +import type { ConversationTurn, CriterionResult, CriterionSubject } from "shared"; import type { PostProcessHandler, PostProcessorMessage, HandlerContext } from "../types.js"; /** Minimal shape of the request document fields this handler reads/writes. */ @@ -17,15 +17,30 @@ interface RequestDoc { }; } +/** Minimal projection of a criterion needed to route by evaluation granularity. */ +interface CriterionMeta { + id: string; + subject?: CriterionSubject; +} + /** - * Taxonomy Handler (pp-taxonomy): records per-iteration boolean observations. + * Taxonomy Handler (pp-taxonomy): records boolean observations. + * + * Each selected observation criterion is routed by its `subject` (#1156): * - * For each iteration turn with a `snapshotUrl`, reuses the judge service to - * evaluate the run's selected observation criteria (top-level - * `request.observations`) against the codebase snapshot AND the agent - * trajectory (ATIF) — sending `atifUrl` in place of `toolCallsUrl`. Results are - * written to `turn.observationResults`, mirroring gate `criteriaResults`. Never - * gates, never steers the agent. Empty/absent `observations` → no-op. #1156. + * - **`subject:"iteration"`** — evaluated on each iteration in isolation against + * that turn's snapshot + ATIF; written to `turn.observationResults` (mirrors + * gate `criteriaResults`). + * - **`subject:"run"`** (the observation default) — evaluated ONCE against the + * whole run: the final iteration's snapshot + the MERGED trajectory of every + * iteration's ATIF (`atifUrls`) + the full conversation history; written to the + * run-level `run.observationResults`. This is what makes cross-iteration + * behavior (e.g. a dependency added in one turn and removed in another) visible. + * + * Reuses the judge service; never gates, never steers the agent. Empty/absent + * `observations` → no-op. pp-taxonomy is dispatched exactly once per run (the + * scheduler never sets `message.iteration`), so the run-subject branch runs once + * with no idempotency guard. */ export class TaxonomyHandler implements PostProcessHandler { readonly type = "taxonomy"; @@ -51,6 +66,30 @@ export class TaxonomyHandler implements PostProcessHandler { return; } + // Resolve each selected observation's evaluation granularity. A missing/unknown + // subject defaults to "run" (the observation default), so legacy criteria authored + // before the `subject` field get whole-run evaluation. + const metas = (await ctx.criteriaCollection + .find({ id: { $in: observations } }, { projection: { id: 1, subject: 1 } } as any) + .toArray()) as unknown as CriterionMeta[]; + const subjectById = new Map(metas.map((m) => [m.id, m.subject])); + const iterationObs = observations.filter((id) => subjectById.get(id) === "iteration"); + const runObs = observations.filter((id) => subjectById.get(id) !== "iteration"); + + await this.evaluateIterationObservations(iterationObs, turns, iteration, requestId, ctx); + await this.evaluateRunObservations(runObs, turns, iteration, requestId, ctx); + } + + /** Per-iteration observations → `turn.observationResults` (one judge call per turn). */ + private async evaluateIterationObservations( + iterationObs: string[], + turns: ConversationTurn[], + iteration: number | undefined, + requestId: string, + ctx: HandlerContext, + ): Promise { + if (iterationObs.length === 0) return; + const turnsToProcess = iteration ? turns.filter((t) => t.iteration === iteration) : turns; let processedCount = 0; @@ -63,7 +102,7 @@ export class TaxonomyHandler implements PostProcessHandler { try { const result = await this.judge.evaluate({ snapshotUrl: turn.snapshotUrl, - criteria: observations, + criteria: iterationObs, conversationHistory: turns, ...(turn.atifUrl ? { atifUrl: turn.atifUrl } : {}), requestId, @@ -88,6 +127,73 @@ export class TaxonomyHandler implements PostProcessHandler { } } - await ctx.log("info", `Taxonomy evaluation complete: ${processedCount}/${turnsToProcess.length} iterations processed`); + await ctx.log( + "info", + `Iteration-subject evaluation complete: ${processedCount}/${turnsToProcess.length} iterations processed`, + ); + } + + /** + * Whole-run observations → `run.observationResults` (one judge call over the + * merged trajectory). Skipped when a single-iteration dispatch is requested + * (forward-compat: a whole-run eval needs every turn). Today `message.iteration` + * is never set, so this runs once per run. + */ + private async evaluateRunObservations( + runObs: string[], + turns: ConversationTurn[], + iteration: number | undefined, + requestId: string, + ctx: HandlerContext, + ): Promise { + if (runObs.length === 0) return; + if (iteration) { + await ctx.log( + "info", + `Skipping ${runObs.length} run-subject observation(s): single-iteration dispatch cannot evaluate the whole run`, + ); + return; + } + + const turnsWithSnapshot = turns.filter((t) => t.snapshotUrl); + const finalTurn = turnsWithSnapshot[turnsWithSnapshot.length - 1]; + if (!finalTurn?.snapshotUrl) { + await ctx.log("info", "No turn with a snapshot, skipping run-subject observations"); + return; + } + + // Merge every iteration's ATIF into one whole-run trajectory. + const atifUrls = turns + .map((t) => t.atifUrl) + .filter((u): u is string => typeof u === "string" && u.length > 0); + + try { + const result = await this.judge.evaluate({ + snapshotUrl: finalTurn.snapshotUrl, + criteria: runObs, + conversationHistory: turns, + ...(atifUrls.length > 0 ? { atifUrls } : {}), + requestId, + }); + + const runObservationResults: CriterionResult[] = result.criteriaResults ?? []; + + await ctx.collection.updateOne( + { _id: requestId } as any, + { $set: { "run.observationResults": runObservationResults } } as any, + ); + + await ctx.log( + "info", + `Run-subject evaluation complete: ${runObservationResults.length} whole-run observation(s) recorded over ${atifUrls.length} merged trajectory(ies)`, + ); + } catch (err) { + const errMsg = err instanceof Error ? err.message : String(err); + if (isRetryableJudgeError(err)) { + await ctx.log("error", `Run-subject: judge infrastructure error, failing handler: ${errMsg}`); + throw err; + } + await ctx.log("warn", `Run-subject observation evaluation failed: ${errMsg}`); + } } } diff --git a/apps/workers/post-processor/src/post-processor.ts b/apps/workers/post-processor/src/post-processor.ts index 4b1b6e847..e6b10614a 100644 --- a/apps/workers/post-processor/src/post-processor.ts +++ b/apps/workers/post-processor/src/post-processor.ts @@ -81,6 +81,7 @@ export class PostProcessor extends BaseQueueProcessor { const ctx: HandlerContext = { blobStorage: this.blobStorage, collection: this.collection as any, + criteriaCollection: this.db.collection("criteria"), log, }; diff --git a/apps/workers/post-processor/src/types.ts b/apps/workers/post-processor/src/types.ts index 8765dd926..20e1397d0 100644 --- a/apps/workers/post-processor/src/types.ts +++ b/apps/workers/post-processor/src/types.ts @@ -16,6 +16,9 @@ export interface PostProcessorMessage { export interface HandlerContext { blobStorage: BlobStorage; collection: Collection; + /** The `criteria` collection — lets handlers resolve criterion metadata + * (e.g. observation `subject`/`taxonomyElementId`) by id. #1156. */ + criteriaCollection: Collection; log: (level: LogEvent["level"], msg: string, data?: Record) => Promise; } From 1daf022db138e51a8baec3bbe05fcf830a83e834 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Mon, 29 Jun 2026 19:20:12 -0700 Subject: [PATCH 024/210] feat(portal): subject toggle + whole-run observations + steering copy (#1156) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - wizard: Run/Iteration toggle (shown for observations, prefilled from AI suggestedSubject, user-overridable); subject in create payload + reset - kind copy reworded to convey STEERING vs record-only: gate steers the agent (pass/fail feedback shapes its next iteration), observation records evidence never shown to the agent — in both the wizard and the inline editor - RunDetail Taxonomy tab: new Whole-run observations subsection (from run.observationResults) above the per-iteration matrix, grouped by dimension - CriteriaSubjectBadge on list + detail; subject in types + api payloads - Storybook: subject-badge story Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../src/components/CriteriaBadge.stories.tsx | 16 +++- apps/portal/src/components/CriteriaBadge.tsx | 27 +++++- .../src/components/CriteriaWizardStep1.tsx | 43 ++++++++-- apps/portal/src/hooks/useCriteriaWizard.ts | 19 ++++- apps/portal/src/lib/api.ts | 6 +- apps/portal/src/pages/CriteriaList.tsx | 11 ++- apps/portal/src/pages/CriterionDetail.tsx | 53 ++++++++---- apps/portal/src/pages/RunDetail.tsx | 83 ++++++++++++++++++- apps/portal/src/types.ts | 22 ++++- 9 files changed, 241 insertions(+), 39 deletions(-) diff --git a/apps/portal/src/components/CriteriaBadge.stories.tsx b/apps/portal/src/components/CriteriaBadge.stories.tsx index e851b3aec..bb3c1f8cb 100644 --- a/apps/portal/src/components/CriteriaBadge.stories.tsx +++ b/apps/portal/src/components/CriteriaBadge.stories.tsx @@ -2,7 +2,7 @@ // Licensed under the MIT License. import type { Meta, StoryObj } from "@storybook/react-vite"; -import { CriteriaBadge, CriteriaKindBadge } from "./CriteriaBadge"; +import { CriteriaBadge, CriteriaKindBadge, CriteriaSubjectBadge } from "./CriteriaBadge"; const meta = { title: "Components/CriteriaBadge", @@ -47,3 +47,17 @@ export const KindBadges: Story = {
), }; + +export const SubjectBadges: Story = { + args: { + criterionId: "has_unit_tests", + link: false, + }, + render: () => ( +
+ + + +
+ ), +}; diff --git a/apps/portal/src/components/CriteriaBadge.tsx b/apps/portal/src/components/CriteriaBadge.tsx index d1cc1bbc3..e5536e2bd 100644 --- a/apps/portal/src/components/CriteriaBadge.tsx +++ b/apps/portal/src/components/CriteriaBadge.tsx @@ -5,7 +5,7 @@ import { Link } from "react-router-dom"; import { Badge } from "@/components/ui/badge"; import { cn } from "@/lib/utils"; import { criterionResultStyle, type CriterionResultState } from "@/lib/criteria-result"; -import type { CriterionKind } from "@/types"; +import type { CriterionKind, CriterionSubject } from "@/types"; interface CriteriaBadgeProps { criterionId: string; @@ -75,3 +75,28 @@ export function CriteriaKindBadge({ kind, className }: { kind?: CriterionKind; c ); } + +/** + * Small badge showing an observation's evaluation subject (#1156): + * "Whole run" (subject:"run") vs "Per iteration" (subject:"iteration"). + * Defaults to "run" when unset (the observation default). Intended for + * observation criteria; subject is inert for gates. + */ +export function CriteriaSubjectBadge({ subject, className }: { subject?: CriterionSubject; className?: string }) { + const normalized = subject ?? "run"; + return ( + + {normalized === "run" ? "Whole run" : "Per iteration"} + + ); +} diff --git a/apps/portal/src/components/CriteriaWizardStep1.tsx b/apps/portal/src/components/CriteriaWizardStep1.tsx index c6a182b36..3cda0d8e3 100644 --- a/apps/portal/src/components/CriteriaWizardStep1.tsx +++ b/apps/portal/src/components/CriteriaWizardStep1.tsx @@ -32,6 +32,8 @@ export function CriteriaWizardStep1({ wizard, idPrefix = "" }: CriteriaWizardSte setKind, taxonomyElementId, setTaxonomyElementId, + subject, + setSubject, } = wizard; return ( @@ -105,12 +107,14 @@ export function CriteriaWizardStep1({ wizard, idPrefix = "" }: CriteriaWizardSte - Gate — controls pass/fail iteration flow - Observation — records per-iteration evidence + Gate — steers the agent (pass/fail feedback shapes its next iteration) + Observation — records evidence; never shown to the agent

- Gate criteria drive judge feedback. Observations are recorded after each iteration and never gate the agent. + Gate criteria steer the agent — their pass/fail verdict is fed back into the coding + session and shapes what it does next. Observations are recorded for analysis only: + never shown to the agent and never change its behavior.

@@ -125,11 +129,34 @@ export function CriteriaWizardStep1({ wizard, idPrefix = "" }: CriteriaWizardSte

) : ( - + <> + + + {/* Evaluation subject (observations only) */} +
+ + +

+ Whole-run observations span iterations (e.g. a dependency added then later removed), + evaluated once against the final snapshot plus the merged trajectory. Per-iteration + observations are judged independently on each iteration. +

+
+ )}
); diff --git a/apps/portal/src/hooks/useCriteriaWizard.ts b/apps/portal/src/hooks/useCriteriaWizard.ts index 3033c2d49..4115684c3 100644 --- a/apps/portal/src/hooks/useCriteriaWizard.ts +++ b/apps/portal/src/hooks/useCriteriaWizard.ts @@ -7,7 +7,7 @@ import { api } from "@/lib/api"; import { slugify } from "@/lib/utils"; import { toast } from "sonner"; import { gatesSatisfyInvariant, type GateId } from "@/lib/gates"; -import type { CriterionKind, TaxonomyElementId } from "@/types"; +import type { CriterionKind, CriterionSubject, TaxonomyElementId } from "@/types"; export interface UseCriteriaWizardOptions { /** Pre-populated parent dependency IDs */ @@ -18,6 +18,8 @@ export interface UseCriteriaWizardOptions { lockedGates?: GateId[]; initialKind?: CriterionKind; initialTaxonomyElementId?: TaxonomyElementId; + /** Pre-populated evaluation subject (observations default to "run"). */ + initialSubject?: CriterionSubject; /** Called with the new criterion ID after successful creation */ onSuccess: (id: string) => void; } @@ -28,6 +30,7 @@ export function useCriteriaWizard({ lockedGates, initialKind = "gate", initialTaxonomyElementId, + initialSubject = "run", onSuccess, }: UseCriteriaWizardOptions) { const queryClient = useQueryClient(); @@ -43,6 +46,7 @@ export function useCriteriaWizard({ const [gates, setGates] = useState(initialGates ?? ["select"]); const [kind, setKind] = useState(initialKind); const [taxonomyElementId, setTaxonomyElementId] = useState(initialTaxonomyElementId); + const [subject, setSubject] = useState(initialSubject); // Step 2 fields const [prompt, setPrompt] = useState(""); @@ -143,6 +147,11 @@ export function useCriteriaWizard({ setSuggestedChildren([]); setAcceptedChildren([]); } + // Prefill the evaluation subject from the AI suggestion (observations + // only; the toggle is hidden for gates). User can still override it. + if (data.suggestedSubject) { + setSubject(data.suggestedSubject); + } }, onError: () => { // LLM unavailable — proceed with empty prompt for manual entry @@ -197,8 +206,9 @@ export function useCriteriaWizard({ ...(kind === "gate" ? { gates } : {}), kind, ...(kind === "observation" && taxonomyElementId ? { taxonomyElementId } : {}), + ...(kind === "observation" ? { subject } : {}), }); - }, [id, prompt, dependsOn, gates, kind, taxonomyElementId, createMutation]); + }, [id, prompt, dependsOn, gates, kind, taxonomyElementId, subject, createMutation]); // Regenerate prompt const handleRegenerate = useCallback(() => { @@ -218,12 +228,13 @@ export function useCriteriaWizard({ setGates(initialGates ?? ["select"]); setKind(initialKind); setTaxonomyElementId(initialTaxonomyElementId); + setSubject(initialSubject); setPrompt(""); setAiGenerated(false); setSuggestedParents([]); setSuggestedChildren([]); setAcceptedChildren([]); - }, [initialDependsOn, initialGates, initialKind, initialTaxonomyElementId]); + }, [initialDependsOn, initialGates, initialKind, initialTaxonomyElementId, initialSubject]); return { // State @@ -243,6 +254,8 @@ export function useCriteriaWizard({ setKind, taxonomyElementId, setTaxonomyElementId, + subject, + setSubject, prompt, setPrompt, aiGenerated, diff --git a/apps/portal/src/lib/api.ts b/apps/portal/src/lib/api.ts index 281fad7dd..1cef41b3e 100644 --- a/apps/portal/src/lib/api.ts +++ b/apps/portal/src/lib/api.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import type { Run, RunState, CriteriaDocument, CriteriaGraphData, GeneratePromptResponse, AnalysisResponse, PromptFeatureDocument, Report, BulkReportStatus, BulkReportSummary, ReportTemplate, ReportTrigger, ReportTemplateSystemPrompt, KeyDocument, KeyValidationResult, CreateKeyRequest, UpdateKeyRequest, CodingAgent, AgentVersion, McpServerDocument, CreateMcpServerRequest, UpdateMcpServerRequest, BulkResubmitOverrides, Insight, InsightWithReference, TaskPrompt, TaskPromptFeatureExtractionResult, Model, FeatureFlag, SkillDocument, SkillSearchResult, SkillDiscoveryResult, SkillRevisionDocument, CodebaseDocument, CodebaseRevisionDocument, CodebaseSourceType, ExtensionDocument, ExtensionSearchResult, ExtensionVersionInfo, MdpResponse, AccountDocument, CreateAccountRequest, UpdateAccountRequest, ProfileWithVersion, ProfileVersionDocument, ProfileDocument, RunGroup, CursorPaginatedResponse, IterationOp, GateConfig, GateId, PromptType, CriterionKind, TaxonomyElementId } from "@/types"; +import type { Run, RunState, CriteriaDocument, CriteriaGraphData, GeneratePromptResponse, AnalysisResponse, PromptFeatureDocument, Report, BulkReportStatus, BulkReportSummary, ReportTemplate, ReportTrigger, ReportTemplateSystemPrompt, KeyDocument, KeyValidationResult, CreateKeyRequest, UpdateKeyRequest, CodingAgent, AgentVersion, McpServerDocument, CreateMcpServerRequest, UpdateMcpServerRequest, BulkResubmitOverrides, Insight, InsightWithReference, TaskPrompt, TaskPromptFeatureExtractionResult, Model, FeatureFlag, SkillDocument, SkillSearchResult, SkillDiscoveryResult, SkillRevisionDocument, CodebaseDocument, CodebaseRevisionDocument, CodebaseSourceType, ExtensionDocument, ExtensionSearchResult, ExtensionVersionInfo, MdpResponse, AccountDocument, CreateAccountRequest, UpdateAccountRequest, ProfileWithVersion, ProfileVersionDocument, ProfileDocument, RunGroup, CursorPaginatedResponse, IterationOp, GateConfig, GateId, PromptType, CriterionKind, TaxonomyElementId, CriterionSubject } from "@/types"; import { qs } from "./url"; import { recordServerDate } from "./serverClock"; @@ -318,7 +318,7 @@ export const api = { }, /** Create a new criterion */ - createCriterion: (body: { id: string; prompt: string; dependsOn?: string[]; gates?: GateId[]; kind?: CriterionKind; taxonomyElementId?: TaxonomyElementId }): Promise => { + createCriterion: (body: { id: string; prompt: string; dependsOn?: string[]; gates?: GateId[]; kind?: CriterionKind; taxonomyElementId?: TaxonomyElementId; subject?: CriterionSubject }): Promise => { return request("/criteria", { method: "POST", body: JSON.stringify(body), @@ -326,7 +326,7 @@ export const api = { }, /** Update an existing criterion */ - updateCriterion: (id: string, body: { prompt?: string; dependsOn?: string[]; gates?: GateId[]; kind?: CriterionKind; taxonomyElementId?: TaxonomyElementId }): Promise => { + updateCriterion: (id: string, body: { prompt?: string; dependsOn?: string[]; gates?: GateId[]; kind?: CriterionKind; taxonomyElementId?: TaxonomyElementId; subject?: CriterionSubject }): Promise => { return request(`/criteria/${id}`, { method: "PUT", body: JSON.stringify(body), diff --git a/apps/portal/src/pages/CriteriaList.tsx b/apps/portal/src/pages/CriteriaList.tsx index 3c07c9800..1425ff064 100644 --- a/apps/portal/src/pages/CriteriaList.tsx +++ b/apps/portal/src/pages/CriteriaList.tsx @@ -35,7 +35,7 @@ import { type CustomizeColumnsOption, } from "@/components/list-layout"; import { HelpTooltip } from "@/components/HelpTooltip"; -import { CriteriaKindBadge } from "@/components/CriteriaBadge"; +import { CriteriaKindBadge, CriteriaSubjectBadge } from "@/components/CriteriaBadge"; import { TAXONOMY_ELEMENT_METADATA } from "@/types"; const FILTER_KEYS = ["gate", "kind"] as const; @@ -179,9 +179,14 @@ export function CriteriaList() { { id: "kind", header: "Kind", - width: "130px", + width: "180px", hidden: visibility.isHidden("kind"), - cell: (c) => , + cell: (c) => ( +
+ + {c.kind === "observation" && } +
+ ), }, { id: "taxonomy", diff --git a/apps/portal/src/pages/CriterionDetail.tsx b/apps/portal/src/pages/CriterionDetail.tsx index 51ec8b358..274637abe 100644 --- a/apps/portal/src/pages/CriterionDetail.tsx +++ b/apps/portal/src/pages/CriterionDetail.tsx @@ -20,7 +20,7 @@ import { import { Skeleton } from "@/components/ui/skeleton"; import { ArrowLeft, Save, Trash2, Loader2, Sparkles, Check, X, Plus, Download } from "lucide-react"; import { CriteriaPicker } from "@/components/CriteriaPicker"; -import { CriteriaKindBadge } from "@/components/CriteriaBadge"; +import { CriteriaKindBadge, CriteriaSubjectBadge } from "@/components/CriteriaBadge"; import { GateCompatibilityPicker } from "@/components/GateCompatibilityPicker"; import { ObservationTaxonomySelect } from "@/components/ObservationTaxonomySelect"; import { formatDate } from "@/lib/utils"; @@ -33,7 +33,7 @@ import { useCommandEnter } from "@/hooks/useCommandEnter"; import { KbdBadge } from "@/components/KbdBadge"; import { criteriaToExportYaml, downloadAsFile } from "@/lib/criteria-export"; import { toast } from "sonner"; -import { TAXONOMY_ELEMENT_METADATA, type CriterionKind, type TaxonomyElementId } from "@/types"; +import { TAXONOMY_ELEMENT_METADATA, type CriterionKind, type CriterionSubject, type TaxonomyElementId } from "@/types"; export function CriterionDetail() { const { id } = useParams<{ id: string }>(); @@ -55,6 +55,7 @@ export function CriterionDetail() { const [editGates, setEditGates] = useState(undefined); const [editKind, setEditKind] = useState("gate"); const [editTaxonomyElementId, setEditTaxonomyElementId] = useState(undefined); + const [editSubject, setEditSubject] = useState("run"); // AI Suggest state const [aiSuggestOpen, setAiSuggestOpen] = useState(false); @@ -70,7 +71,7 @@ export function CriterionDetail() { }); const updateMutation = useMutation({ - mutationFn: (body: { prompt?: string; dependsOn?: string[]; gates?: GateId[]; kind?: CriterionKind; taxonomyElementId?: TaxonomyElementId }) => + mutationFn: (body: { prompt?: string; dependsOn?: string[]; gates?: GateId[]; kind?: CriterionKind; taxonomyElementId?: TaxonomyElementId; subject?: CriterionSubject }) => api.updateCriterion(id!, body), onSuccess: async () => { // Update accepted children to depend on this criterion @@ -133,6 +134,7 @@ export function CriterionDetail() { setEditGates(criterion.gates && criterion.gates.length > 0 ? criterion.gates : ["select"]); setEditKind(criterion.kind ?? "gate"); setEditTaxonomyElementId(criterion.taxonomyElementId); + setEditSubject(criterion.subject ?? ((criterion.kind ?? "gate") === "observation" ? "run" : "iteration")); setAiSuggestOpen(false); setBehaviorInput(""); setSuggestedPrompt(null); @@ -153,6 +155,8 @@ export function CriterionDetail() { ...(editKind === "gate" ? { gates: editGates } : {}), kind: editKind, taxonomyElementId: editKind === "observation" ? editTaxonomyElementId : undefined, + // Subject only applies to observations; gates are always per-iteration. + subject: editKind === "observation" ? editSubject : "iteration", }); }; @@ -466,7 +470,7 @@ export function CriterionDetail() { Kind - Whether this criterion gates iteration flow or records observation evidence. + Gate criteria steer the agent (pass/fail feedback shapes its next iteration); observations only record evidence and are never shown to the agent. @@ -479,28 +483,45 @@ export function CriterionDetail() { - Gate — controls pass/fail iteration flow - Observation — records per-iteration evidence + Gate — steers the agent (pass/fail feedback shapes its next iteration) + Observation — records evidence; never shown to the agent {editKind === "observation" && ( - + <> + +
+ + +
+ )} ) : (
{(criterion.kind ?? "gate") === "observation" && ( - - {criterion.taxonomyElementId - ? TAXONOMY_ELEMENT_METADATA[criterion.taxonomyElementId].label - : "Unclassified"} - + <> + + {criterion.taxonomyElementId + ? TAXONOMY_ELEMENT_METADATA[criterion.taxonomyElementId].label + : "Unclassified"} + + + )}
)} diff --git a/apps/portal/src/pages/RunDetail.tsx b/apps/portal/src/pages/RunDetail.tsx index 2b058d107..235a78866 100644 --- a/apps/portal/src/pages/RunDetail.tsx +++ b/apps/portal/src/pages/RunDetail.tsx @@ -295,6 +295,80 @@ function ObservationResultsPanel({ ); } +/** + * Whole-run observation results (#1156, `subject:"run"`). Each criterion is + * evaluated ONCE against the final snapshot + the merged trajectory across all + * iterations, so these live at run level (`run.observationResults`) rather than + * per turn. Rendered as a subsection above the per-iteration matrix, grouped by + * taxonomy dimension like the matrix. + */ +function WholeRunObservationsPanel({ + results, + criteria, +}: { + results: CriterionResult[] | undefined; + criteria: CriteriaDocument[]; +}) { + const criteriaById = useMemo(() => new Map(criteria.map((criterion) => [criterion.id, criterion])), [criteria]); + const groups = useMemo(() => { + const byDimension = new Map>(); + for (const result of results ?? []) { + const criterion = criteriaById.get(result.criterionId); + const key: ObservationDimensionKey = criterion?.taxonomyElementId ?? "unclassified"; + const existing = byDimension.get(key) ?? []; + existing.push({ result, criterion }); + byDimension.set(key, existing); + } + return Array.from(byDimension.entries()).sort(([a], [b]) => observationDimensionLabel(a).localeCompare(observationDimensionLabel(b))); + }, [results, criteriaById]); + + if (groups.length === 0) return null; + + return ( +
+ {groups.map(([dimension, items]) => ( + + + + + Whole run + + {observationDimensionLabel(dimension)} + + + + {items.map(({ result, criterion }) => ( +
+
+ {result.criterionId} + + {result.evaluated ? ( + result.passed ? : + ) : ( + + )} + {result.evaluated ? (result.passed ? "True" : "False") : "Not evaluated"} + +
+ {criterion?.prompt && ( +

{criterion.prompt}

+ )} +
+

Evidence

+

{result.feedback || "No evidence provided."}

+
+
+ ))} +
+
+ ))} +
+ ); +} + export function RunDetail() { const { id, tab } = useParams<{ id: string; tab?: string }>(); const navigate = useNavigate(); @@ -403,7 +477,9 @@ export function RunDetail() { enabled: !!taskPromptId, }); - const hasObservationResults = (activeRun?.turns ?? []).some((turn) => (turn.observationResults?.length ?? 0) > 0); + const hasObservationResults = + (activeRun?.turns ?? []).some((turn) => (turn.observationResults?.length ?? 0) > 0) || + (activeRun?.observationResults?.length ?? 0) > 0; const hasConfiguredObservations = (run?.observations?.length ?? 0) > 0; // Aggregate enrichment status across the whole post-processing DAG so the // "Enriched" badge waits for pp-taxonomy instead of flipping after pp-atif. @@ -979,7 +1055,7 @@ export function RunDetail() { {hasVideoData && } {(hasConfiguredObservations || hasObservationResults) && ( - Taxonomy {hasObservationResults ? `(${activeRun?.turns?.reduce((count, turn) => count + (turn.observationResults?.length ?? 0), 0) ?? 0})` : ""} + Taxonomy {hasObservationResults ? `(${((activeRun?.turns?.reduce((count, turn) => count + (turn.observationResults?.length ?? 0), 0) ?? 0) + (activeRun?.observationResults?.length ?? 0))})` : ""} )} Logs @@ -1083,9 +1159,10 @@ export function RunDetail() {

Observations

- Per-iteration boolean observations recorded over the codebase and agent trajectory, grouped by taxonomy dimension. Non-gating — they never steer the agent. + Boolean observations recorded over the codebase and agent trajectory, grouped by taxonomy dimension. Non-gating — they never steer the agent.

+ diff --git a/apps/portal/src/types.ts b/apps/portal/src/types.ts index a7a6b2ec2..5460b6408 100644 --- a/apps/portal/src/types.ts +++ b/apps/portal/src/types.ts @@ -29,6 +29,16 @@ export interface ToolCall { export type CriterionKind = "gate" | "observation"; +/** + * Evaluation granularity for a criterion (#1156). + * - `iteration` — evaluated on each iteration in isolation (gates are always this). + * - `run` — evaluated once against the whole run (final snapshot + merged + * trajectory). The default for observations; rejected for gates. + */ +export type CriterionSubject = "run" | "iteration"; + +export const CRITERION_SUBJECTS: readonly CriterionSubject[] = ["run", "iteration"]; + export const TAXONOMY_ELEMENT_IDS = [ "dimension:idiomatic-use", "dimension:dependency-currency", @@ -167,6 +177,14 @@ export interface RunState { * tracks pp-atif and is kept for backward compatibility. */ handlerStatus?: Record; + /** + * Whole-run observation results — one entry per selected `subject:"run"` + * observation criterion, evaluated once against the final snapshot + the + * merged trajectory across all iterations (#1156). Per-iteration + * (`subject:"iteration"`) observations live on `turn.observationResults` + * instead. Empty/absent when no run-subject observations were selected. + */ + observationResults?: CriterionResult[]; } export interface Run { @@ -263,6 +281,7 @@ export interface CriteriaConfig { gates?: GateId[]; kind?: CriterionKind; taxonomyElementId?: TaxonomyElementId; + subject?: CriterionSubject; } export interface CriteriaDocument extends CriteriaConfig { @@ -272,7 +291,7 @@ export interface CriteriaDocument extends CriteriaConfig { } export interface CriteriaGraphData { - nodes: Array<{ id: string; prompt: string; dependsOn: string[]; gates?: GateId[]; kind?: CriterionKind; taxonomyElementId?: TaxonomyElementId }>; + nodes: Array<{ id: string; prompt: string; dependsOn: string[]; gates?: GateId[]; kind?: CriterionKind; taxonomyElementId?: TaxonomyElementId; subject?: CriterionSubject }>; edges: Array<{ source: string; target: string }>; } @@ -281,6 +300,7 @@ export interface GeneratePromptResponse { suggestedId: string; suggestedParents: string[]; suggestedChildren: string[]; + suggestedSubject?: CriterionSubject; } // Prompt Feature types From f1b24e9fe8aa4c593bb2379d1e89e74914928ff1 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Mon, 29 Jun 2026 19:20:32 -0700 Subject: [PATCH 025/210] =?UTF-8?q?feat(cli):=20subject=20parity=20?= =?UTF-8?q?=E2=80=94=20--subject=20flag=20+=20whole-run=20observations=20(?= =?UTF-8?q?#1156)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - yaml-mappers: round-trip subject - criteria command: --subject on create/update; show subject in list/get/export/import - run-get-action: render whole-run run.observationResults block alongside the per-iteration ones - updated cli-commands snapshot for --subject Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../__snapshots__/cli-commands.test.ts.snap | 2 + apps/cli/src/commands/criteria.ts | 24 ++++-- apps/cli/src/run-get-action.ts | 75 +++++++++++++------ apps/cli/src/utils/yaml-mappers.ts | 5 +- 4 files changed, 76 insertions(+), 30 deletions(-) diff --git a/apps/cli/src/__snapshots__/cli-commands.test.ts.snap b/apps/cli/src/__snapshots__/cli-commands.test.ts.snap index f22265fbc..d16e5ad90 100644 --- a/apps/cli/src/__snapshots__/cli-commands.test.ts.snap +++ b/apps/cli/src/__snapshots__/cli-commands.test.ts.snap @@ -133,6 +133,7 @@ exports[`CLI command registration > full command tree matches snapshot 1`] = ` "--id", "--kind", "--prompt", + "--subject", "--taxonomy", "--url", ], @@ -183,6 +184,7 @@ exports[`CLI command registration > full command tree matches snapshot 1`] = ` "--id", "--kind", "--prompt", + "--subject", "--taxonomy", "--url", ], diff --git a/apps/cli/src/commands/criteria.ts b/apps/cli/src/commands/criteria.ts index 7e890f9ac..807b83dcf 100644 --- a/apps/cli/src/commands/criteria.ts +++ b/apps/cli/src/commands/criteria.ts @@ -46,7 +46,7 @@ criteria process.exit(1); } - const items = await response.json() as Array<{ id: string; prompt: string; dependsOn?: string[]; gates?: GateId[]; kind?: string; taxonomyElementId?: string }>; + const items = await response.json() as Array<{ id: string; prompt: string; dependsOn?: string[]; gates?: GateId[]; kind?: string; taxonomyElementId?: string; subject?: string }>; if (items.length === 0) { if (!isMachineReadable(format)) console.log(warnBanner("No criteria found.")); return; @@ -61,6 +61,7 @@ criteria tableFormatter: (c: any) => value(c.id), }, { key: 'kind', label: 'Kind', formatter: (c: any) => c.kind ?? 'gate' }, + { key: 'subject', label: 'Subject', formatter: (c: any) => c.kind === 'observation' ? (c.subject ?? 'run') : '—' }, { key: 'dependsOn', label: 'Deps', formatter: (c: any) => String((c.dependsOn ?? []).length) }, { key: 'gates', label: 'Gates', formatter: (c: any) => formatGateList(c.gates) }, { key: 'prompt', label: 'Prompt', tableFormatter: (c: any) => { @@ -97,7 +98,7 @@ criteria const c = await response.json() as { id: string; prompt: string; dependsOn?: string[]; gates?: GateId[]; - kind?: string; taxonomyElementId?: string; + kind?: string; taxonomyElementId?: string; subject?: string; dependents: string[]; createdAt: string; updatedAt?: string; }; @@ -106,6 +107,7 @@ criteria { key: 'id', label: 'ID' }, { key: 'prompt', label: 'Prompt' }, { key: 'kind', label: 'Kind', formatter: (item: any) => item.kind ?? 'gate' }, + { key: 'subject', label: 'Subject', formatter: (item: any) => item.kind === 'observation' ? (item.subject ?? 'run') : '(n/a)' }, { key: 'taxonomyElementId', label: 'Taxonomy', formatter: (item: any) => item.taxonomyElementId ?? '(none)' }, { key: 'dependsOn', label: 'Depends On', formatter: (item: any) => (item.dependsOn ?? []).join(', ') || '(none)' }, { key: 'gates', label: 'Gates', formatter: (item: any) => formatGateList(item.gates) }, @@ -129,6 +131,9 @@ criteria } console.log(`${label('Gates:')} ${value(formatGateList(c.gates))}`); console.log(`${label('Kind:')} ${value(c.kind ?? 'gate')}`); + if ((c.kind ?? 'gate') === 'observation') { + console.log(`${label('Subject:')} ${value(c.subject ?? 'run')}`); + } if (c.taxonomyElementId) { console.log(`${label('Taxonomy:')} ${value(c.taxonomyElementId)}`); } @@ -152,6 +157,7 @@ criteria .option("--gates ", "Compatible gates (space/comma separated), or all/* for unrestricted") .option("--kind ", "Criterion kind: gate (default) or observation") .option("--taxonomy ", "Taxonomy element id (observation only), e.g. dimension:dependency-currency") + .option("--subject ", "Evaluation subject (observation only): run (default) or iteration") .option("-u, --url ", "API base URL", getDefaultApiUrl()) .action(async (options) => { try { @@ -166,6 +172,7 @@ criteria if (gates !== undefined) body.gates = gates; if (options.kind) body.kind = options.kind; if (options.taxonomy) body.taxonomyElementId = options.taxonomy; + if (options.subject) body.subject = options.subject; const response = await fetch(`${normalizeUrl(options.url)}/api/v1/criteria`, { method: "POST", @@ -196,6 +203,7 @@ criteria .option("--gates ", "New compatible gates (space/comma separated), or all/* for unrestricted") .option("--kind ", "Criterion kind: gate or observation") .option("--taxonomy ", "Taxonomy element id (observation only)") + .option("--subject ", "Evaluation subject (observation only): run or iteration") .option("-u, --url ", "API base URL", getDefaultApiUrl()) .action(async (options) => { try { @@ -206,9 +214,10 @@ criteria if (gates !== undefined) body.gates = gates; if (options.kind) body.kind = options.kind; if (options.taxonomy) body.taxonomyElementId = options.taxonomy; + if (options.subject) body.subject = options.subject; if (Object.keys(body).length === 0) { - console.error(errorText("Error: provide --prompt, --depends-on, --gates, --kind, and/or --taxonomy")); + console.error(errorText("Error: provide --prompt, --depends-on, --gates, --kind, --taxonomy, and/or --subject")); process.exit(1); } @@ -363,7 +372,7 @@ criteria process.exit(1); } - const items = await response.json() as Array<{ id: string; prompt: string; dependsOn?: string[]; gates?: GateId[]; kind?: string; taxonomyElementId?: string }>; + const items = await response.json() as Array<{ id: string; prompt: string; dependsOn?: string[]; gates?: GateId[]; kind?: string; taxonomyElementId?: string; subject?: string }>; if (items.length === 0) { console.error(errorText("No criteria found to export.")); @@ -408,6 +417,9 @@ criteria if (c.taxonomyElementId) { doc.taxonomy_element_id = c.taxonomyElementId; } + if (c.subject && c.kind === 'observation') { + doc.subject = c.subject; + } return doc; }); @@ -460,7 +472,7 @@ criteria } // Parse all criteria from files (supports multi-document YAML) - const allCriteria: Array<{ id: string; prompt: string; dependsOn?: string[]; gates?: GateId[]; kind?: string; taxonomyElementId?: string }> = []; + const allCriteria: Array<{ id: string; prompt: string; dependsOn?: string[]; gates?: GateId[]; kind?: string; taxonomyElementId?: string; subject?: string }> = []; const parseErrors: string[] = []; for (const file of yamlFiles) { @@ -505,7 +517,7 @@ criteria const deps = (c.dependsOn ?? []).length; const depsStr = deps > 0 ? ` ${dimTimestamp(`(${deps} dep${deps > 1 ? 's' : ''})`)}` : ''; const gatesStr = c.gates ? ` ${dimTimestamp(`[${formatGateList(c.gates)}]`)}` : ''; - const kindStr = c.kind === 'observation' ? ` ${dimTimestamp(``)}` : ''; + const kindStr = c.kind === 'observation' ? ` ${dimTimestamp(``)}` : ''; console.log(` ${value(c.id)}${depsStr}${gatesStr}${kindStr}`); } diff --git a/apps/cli/src/run-get-action.ts b/apps/cli/src/run-get-action.ts index e2a9c9a8b..f98907990 100644 --- a/apps/cli/src/run-get-action.ts +++ b/apps/cli/src/run-get-action.ts @@ -173,8 +173,11 @@ export async function runGetAction(options: RunGetOptions): Promise { } // Observations (kind:"observation" criteria), grouped by taxonomy dimension. + // Whole-run (subject:"run") results live at run level; per-iteration + // (subject:"iteration") results live on each turn. + const runObs = rs?.observationResults ?? []; const turnsWithObs = (rs?.turns ?? []).filter((t) => (t.observationResults?.length ?? 0) > 0); - if (turnsWithObs.length > 0) { + if (runObs.length > 0 || turnsWithObs.length > 0) { // Build criterionId → taxonomyElementId map from the criteria store (best effort). const taxById = new Map(); try { @@ -185,32 +188,58 @@ export async function runGetAction(options: RunGetOptions): Promise { } } catch { /* grouping is best-effort */ } - // detected/evaluated tally per criterion id across iterations. - const tally = new Map(); - for (const t of turnsWithObs) { - for (const r of t.observationResults ?? []) { - const e = tally.get(r.criterionId) ?? { detected: 0, evaluated: 0 }; - e.evaluated += 1; - if (r.passed) e.detected += 1; - tally.set(r.criterionId, e); + const dimLabelOf = (dim: string) => + dim === "unclassified" ? "Unclassified" : (TAXONOMY_ELEMENT_METADATA[dim as TaxonomyElementId]?.label ?? dim); + + console.log(`\n${banner('─── Observations ───')}`); + + // Whole-run observations: one verdict + evidence per criterion. + if (runObs.length > 0) { + const byDimRun = new Map(); + for (const r of runObs) { + const dim = taxById.get(r.criterionId) ?? "unclassified"; + const arr = byDimRun.get(dim) ?? []; + arr.push(r); + byDimRun.set(dim, arr); + } + console.log(` ${label('Whole run')}`); + for (const [dim, results] of byDimRun) { + console.log(` ${label(dimLabelOf(dim))}`); + for (const r of results.sort((a, b) => a.criterionId.localeCompare(b.criterionId))) { + const verdict = r.evaluated ? (r.passed ? successText('true') : errorText('false')) : warnBanner('not evaluated'); + console.log(` ${value(r.criterionId)} — ${verdict}`); + if (r.feedback) console.log(` ${dimTimestamp(r.feedback.replace(/\n/g, ' ').slice(0, 200))}`); + } } } - const byDim = new Map(); - for (const id of tally.keys()) { - const dim = taxById.get(id) ?? "unclassified"; - const arr = byDim.get(dim) ?? []; - arr.push(id); - byDim.set(dim, arr); - } + // Per-iteration observations: detected/evaluated tally per criterion id. + if (turnsWithObs.length > 0) { + const tally = new Map(); + for (const t of turnsWithObs) { + for (const r of t.observationResults ?? []) { + const e = tally.get(r.criterionId) ?? { detected: 0, evaluated: 0 }; + e.evaluated += 1; + if (r.passed) e.detected += 1; + tally.set(r.criterionId, e); + } + } - console.log(`\n${banner('─── Observations ───')}`); - for (const [dim, ids] of byDim) { - const dimLabel = dim === "unclassified" ? "Unclassified" : (TAXONOMY_ELEMENT_METADATA[dim as TaxonomyElementId]?.label ?? dim); - console.log(` ${label(dimLabel)}`); - for (const id of ids.sort()) { - const { detected, evaluated } = tally.get(id)!; - console.log(` ${value(id)} — ${detected}/${evaluated} iterations detected`); + const byDim = new Map(); + for (const id of tally.keys()) { + const dim = taxById.get(id) ?? "unclassified"; + const arr = byDim.get(dim) ?? []; + arr.push(id); + byDim.set(dim, arr); + } + + console.log(` ${label('Per iteration')}`); + for (const [dim, ids] of byDim) { + console.log(` ${label(dimLabelOf(dim))}`); + for (const id of ids.sort()) { + const { detected, evaluated } = tally.get(id)!; + console.log(` ${value(id)} — ${detected}/${evaluated} iterations detected`); + } } } } diff --git a/apps/cli/src/utils/yaml-mappers.ts b/apps/cli/src/utils/yaml-mappers.ts index cad0c23dd..315f18c82 100644 --- a/apps/cli/src/utils/yaml-mappers.ts +++ b/apps/cli/src/utils/yaml-mappers.ts @@ -12,7 +12,7 @@ export function mapYamlCriterion( filename: string, _docIndex: number, options: { includeGates?: boolean } = {}, -): { id: string; prompt: string; dependsOn?: string[]; gates?: GateId[]; kind?: string; taxonomyElementId?: string } | null { +): { id: string; prompt: string; dependsOn?: string[]; gates?: GateId[]; kind?: string; taxonomyElementId?: string; subject?: string } | null { const id = doc.id as string | undefined; const prompt = doc.prompt as string | undefined; if (!id || !prompt) return null; @@ -28,6 +28,8 @@ export function mapYamlCriterion( const kind = kindRaw ? String(kindRaw).trim() : undefined; const taxRaw = (doc.taxonomy_element_id ?? doc.taxonomyElementId) as string | undefined; const taxonomyElementId = taxRaw ? String(taxRaw).trim() : undefined; + const subjectRaw = doc.subject as string | undefined; + const subject = subjectRaw ? String(subjectRaw).trim() : undefined; return { id: id.trim(), @@ -36,6 +38,7 @@ export function mapYamlCriterion( ...(gates !== undefined ? { gates } : {}), ...(kind ? { kind } : {}), ...(taxonomyElementId ? { taxonomyElementId } : {}), + ...(subject ? { subject } : {}), }; } From a7cfe9b3a6f46a6a4d075be033ed710b8bac89e3 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Mon, 29 Jun 2026 19:21:11 -0700 Subject: [PATCH 026/210] docs: criterion subject (run|iteration) + run-level observations (#1156) Document the new subject discriminator, the kind-dependent default and gate restriction, run-level run.observationResults storage, and the merged whole-run trajectory evaluation across post-processing.md, app-design.md, criteria-provider.md, and overview.md. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/architecture/app-design.md | 7 ++--- docs/architecture/criteria-provider.md | 7 +++++ docs/architecture/overview.md | 2 +- docs/architecture/post-processing.md | 37 ++++++++++++++++++++------ 4 files changed, 41 insertions(+), 12 deletions(-) diff --git a/docs/architecture/app-design.md b/docs/architecture/app-design.md index 6f1b528a7..ae557aa14 100644 --- a/docs/architecture/app-design.md +++ b/docs/architecture/app-design.md @@ -146,11 +146,12 @@ Criteria are reusable evaluation rules stored in the database and optionally def - **AI-generated prompts** — natural language behavior descriptions can be converted to evaluation prompts via LLM - **Traits** — reusable labels for filtering and composition (e.g., `has_azure`, `has_node`) - **Gate compatibility** — a `gates: GateId[]` list controls which [gates](#gates--multi-phase-evaluation-pipeline) a criterion may be selected for (empty = all); the list is downward-closed along the DAG -- **Criterion kind** — `kind: "gate" | "observation"` distinguishes criteria that gate the agent from record-only observations. Observation criteria can optionally set `taxonomyElementId` to one of the hard-coded observation dimensions; run detail derives dimension grouping by joining each per-turn `observationResults[].criterionId` back to the criterion metadata. -- **Kind** — `kind: "gate" | "observation"` (default `gate`). **Gate** criteria steer the coding agent through the gate DAG. **Observation** criteria (issue #1156) are record-only: they produce a boolean + evidence per iteration, never feed back to the agent, never pass/fail a gate, and never enter the gate DAG. Dependencies may only reference same-kind criteria. +- **Criterion kind** — `kind: "gate" | "observation"` distinguishes criteria that gate the agent from record-only observations. Observation criteria can optionally set `taxonomyElementId` to one of the hard-coded observation dimensions and a `subject` (`run`|`iteration`) that selects whole-run vs per-iteration evaluation; run detail derives dimension grouping by joining each `observationResults[].criterionId` (per-turn or run-level) back to the criterion metadata. +- **Kind** — `kind: "gate" | "observation"` (default `gate`). **Gate** criteria steer the coding agent through the gate DAG. **Observation** criteria (issue #1156) are record-only: they produce a boolean + evidence, never feed back to the agent, never pass/fail a gate, and never enter the gate DAG. Dependencies may only reference same-kind criteria. - **Taxonomy classification** — observation criteria carry an optional `taxonomyElementId` from a hard-coded enum of the three R&A Readout quality dimensions (`dimension:idiomatic-use`, `dimension:dependency-currency`, `dimension:configuration-correctness`). Classification is static/design-time, not per-run. +- **Evaluation subject** — `subject: "run" | "iteration"` decides the evaluation granularity of an observation. **`run`** (the default for observations) is evaluated **once** against the final snapshot + the merged trajectory across all iterations and stored at run level (`run.observationResults`); **`iteration`** is evaluated per turn and stored on each turn (`turn.observationResults`). Gate criteria are always `iteration` (the API rejects `run` for gates); `subject` is honored only by the `pp-taxonomy` pipeline. The AI authoring assistant auto-detects the subject and the user can override it. -Observation evaluation happens off the coding-agent critical path in the `pp-taxonomy` post-processor (see [post-processing](post-processing.md)). A run carries the chosen `observations: string[]` (observation-criteria ids); each evaluated turn stores `observationResults: CriterionResult[]` (same shape as gate `criteriaResults`). Dimension grouping is derived at read time by joining `criterionId` → criterion `taxonomyElementId`. +Observation evaluation happens off the coding-agent critical path in the `pp-taxonomy` post-processor (see [post-processing](post-processing.md)). A run carries the chosen `observations: string[]` (observation-criteria ids); **iteration-subject** results are stored per turn as `turn.observationResults: CriterionResult[]`, while **run-subject** results are stored once at run level as `run.observationResults: CriterionResult[]` (both the same shape as gate `criteriaResults`). Dimension grouping is derived at read time by joining `criterionId` → criterion `taxonomyElementId`. See [`ENV_VARIABLES.md`](../../scope-mt-app/ENV_VARIABLES.md) for related configuration options. diff --git a/docs/architecture/criteria-provider.md b/docs/architecture/criteria-provider.md index 08e623fbb..28ded0e43 100644 --- a/docs/architecture/criteria-provider.md +++ b/docs/architecture/criteria-provider.md @@ -164,6 +164,13 @@ bypassed or drift between callers: criteria of the same `kind`. This keeps the gate DAG closed under `resolveWithAncestors` (observations never leak into a gate's evaluation set) and lets `kind:"observation"` criteria form their own optional dependency chains. +- **Kind-dependent `subject` default + validation** — observation criteria carry a + `subject: "run" | "iteration"` deciding whole-run vs per-iteration evaluation. When + `subject` is omitted the store applies a **kind-dependent default** (not a flat zod + default): `kind:"observation"` ⇒ `"run"`, `kind:"gate"`/legacy ⇒ `"iteration"`. Gate + criteria are rejected if `subject:"run"` is supplied — `"iteration"` is their only legal + value. The field is threaded through `create`/`update`/`find` and both provider backends + so the `pp-taxonomy` worker and the CLI/Portal can read it. - **Referential integrity on delete** — deleting a criterion that still has dependents is rejected. diff --git a/docs/architecture/overview.md b/docs/architecture/overview.md index ea118f342..d7db0f416 100644 --- a/docs/architecture/overview.md +++ b/docs/architecture/overview.md @@ -80,7 +80,7 @@ flowchart TB | `workers/coder-acp-claude-code` | Claude Code agent via Agent Client Protocol (ACP) | | `workers/coder-acp-copilot` | GitHub Copilot agent via Agent Client Protocol (ACP) | | `workers/report-generator` | Copilot SDK worker that generates post-run markdown reports | -| `workers/post-processor` | DAG-based post-run handlers: `pp-atif` (trajectory ATIF) and `pp-taxonomy` (per-iteration boolean observations via the judge) | +| `workers/post-processor` | DAG-based post-run handlers: `pp-atif` (trajectory ATIF) and `pp-taxonomy` (boolean observations via the judge, per-iteration or whole-run by criterion `subject`) | | `gateway` | AI Gateway — shared Rust TLS-intercepting proxy with plugin architecture (HAR capture, future: token refresh, rate limiting) | ## Data Flow diff --git a/docs/architecture/post-processing.md b/docs/architecture/post-processing.md index baeed6e44..1ec97444b 100644 --- a/docs/architecture/post-processing.md +++ b/docs/architecture/post-processing.md @@ -58,18 +58,39 @@ The `iteration` query parameter is mandatory for the ATIF endpoints. ATIF files ## Taxonomy Observations (`pp-taxonomy`) -The `pp-taxonomy` handler records **observation criteria** — per-iteration boolean -outcomes + evidence about the codebase and the agent's trajectory, **without gating -or steering** the coding agent (issue #1156). It is a DAG node `dependsOn: [pp-atif]`, -because some observations are only derivable from the trajectory (ATIF), not the -final snapshot. +The `pp-taxonomy` handler records **observation criteria** — boolean outcomes + +evidence about the codebase and the agent's trajectory, **without gating or steering** +the coding agent (issue #1156). It is a DAG node `dependsOn: [pp-atif]`, because some +observations are only derivable from the trajectory (ATIF), not the final snapshot. + +### Evaluation subject (`run` vs `iteration`) + +Each observation criterion carries a **`subject: "run" | "iteration"`** that decides +*how* and *where* it is evaluated: + +- **`subject: "iteration"`** — evaluated on **each iteration in isolation**; the verdict is + stored on that turn (`turn.observationResults`). +- **`subject: "run"`** (the default for observations) — evaluated **once** against the + **whole run**: the final iteration's `snapshotUrl` + the **merged trajectory** (every + turn's ATIF concatenated, tool definitions unioned) + the full conversation history. The + single verdict is stored at **run level** (`run.observationResults`). This is what makes + cross-iteration observations correct — e.g. `dependency_added_then_removed`, where a + package is installed in one iteration and removed in a later one, is invisible to any + single-iteration evaluation but clearly `true` across the merged trajectory. + +Gate criteria are always `subject: "iteration"` (the API rejects `"run"` for gates); +`subject` is honored only by this handler. ### Flow 1. Reads the run's `observations: string[]` (observation-criteria ids chosen at submit). Empty/absent ⇒ no-op, handler `done`. -2. For each iteration with a `snapshotUrl`, calls the existing judge via the shared `JudgeClient` (`POST /api/v1/evaluate`) with `snapshotUrl` + `atifUrl` + the observation-criteria ids — no persona, no gate, no taxonomyElementId (the classifier lives on the criterion). ATIF supersedes per-turn `toolCallsUrl`, so only ATIF is sent. -3. Writes the returned per-criterion `{criterionId, passed, feedback}` to that turn's **`observationResults`** — same shape/storage as gate `criteriaResults`. No new blob, no `run.taxonomyUrl`. -4. Stamps `run.handlerStatus["pp-taxonomy"] = { status: "done", version: N }` and notifies the scheduler. +2. Resolves each selected criterion's `subject` and splits them into **iteration-subject** and **run-subject** buckets. +3. **Iteration-subject:** for each iteration with a `snapshotUrl`, calls the existing judge via the shared `JudgeClient` (`POST /api/v1/evaluate`) with `snapshotUrl` + `atifUrl` + the iteration-subject ids. Writes the returned `{criterionId, passed, feedback}` to that turn's **`turn.observationResults`**. +4. **Run-subject:** evaluates **once** with `snapshotUrl` = final turn's snapshot, `atifUrls` = every turn's `atifUrl` (the judge downloads + merges them into one `AgentTrajectory`), and the full `conversationHistory`. Writes the verdicts to **`run.observationResults`** (run level). + - In all judge calls there is no persona, no gate, no taxonomyElementId (the classifier lives on the criterion). ATIF supersedes per-turn `toolCallsUrl`, so only ATIF is sent. + - Result shape/storage mirrors gate `criteriaResults`. No new blob, no `run.taxonomyUrl`. + - **Runs exactly once per run:** the scheduler dispatches `pp-taxonomy` a single time (it never sets `message.iteration`), so the run-subject branch needs no idempotency guard. +5. Stamps `run.handlerStatus["pp-taxonomy"] = { status: "done", version: N }` and notifies the scheduler. Dimension grouping is **derived at read time** by joining each result's `criterionId` → criterion `taxonomyElementId` (the three R&A Readout dimensions; unset = unclassified). It never feeds back to the agent and never affects pass/fail. (#1053 later extends this worker with a richer scorecard artifact.) From 688fbb52ca9f1473c8ac29bb133a199c840a5770 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Wed, 1 Jul 2026 11:46:05 -0700 Subject: [PATCH 027/210] fix(scheduler): allow autoBackfill to re-dispatch runs with outdated versions The autoBackfill feature re-processes historical runs when a handler version bumps, enabling backfill of new/updated post-processing features across the whole dataset. However, buildDispatchFilter() was excluding 'done' status universally, preventing the version-check branch ($lt version) from matching any historical runs. This change makes status exclusions conditional: - autoBackfill handlers exclude only ['queued', 'processing'], allowing done runs to qualify for version-based re-dispatch - Non-backfill handlers still exclude 'done' (only dispatch on missing handler status) Fixes regression identified in #1147 code review. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- apps/scheduler/src/handler-dispatcher.test.ts | 34 +++++++++++++++++++ apps/scheduler/src/handler-dispatcher.ts | 6 +++- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/apps/scheduler/src/handler-dispatcher.test.ts b/apps/scheduler/src/handler-dispatcher.test.ts index 67264d02c..53d652061 100644 --- a/apps/scheduler/src/handler-dispatcher.test.ts +++ b/apps/scheduler/src/handler-dispatcher.test.ts @@ -249,3 +249,37 @@ describe("HandlerDispatcher — maybeTriggerReports", () => { expect(fetchMock).not.toHaveBeenCalled(); }); }); + +describe("HandlerDispatcher — buildDispatchFilter", () => { + let collection: ReturnType; + + beforeEach(() => { + collection = createMockCollection(); + }); + + it("allows done runs to be considered for autoBackfill version bumps", () => { + const d = makeDispatcher(collection) as any; + const autoBackfillHandler = HANDLERS[0]; + + const filter = d.buildDispatchFilter(autoBackfillHandler, HANDLERS, d.buildGraph(HANDLERS)); + + expect(filter[`run.handlerStatus.${autoBackfillHandler._id}.status`]).toEqual({ + $nin: ["queued", "processing"], + }); + expect(filter.$or).toEqual([ + { [`run.handlerStatus.${autoBackfillHandler._id}.version`]: { $exists: false } }, + { [`run.handlerStatus.${autoBackfillHandler._id}.version`]: { $lt: autoBackfillHandler.version } }, + ]); + }); + + it("keeps done runs excluded for non-backfill handlers", () => { + const d = makeDispatcher(collection) as any; + const noBackfillHandler = HANDLERS[1]; + + const filter = d.buildDispatchFilter(noBackfillHandler, HANDLERS, d.buildGraph(HANDLERS)); + + expect(filter[`run.handlerStatus.${noBackfillHandler._id}.status`]).toEqual({ + $nin: ["queued", "processing", "done"], + }); + }); +}); diff --git a/apps/scheduler/src/handler-dispatcher.ts b/apps/scheduler/src/handler-dispatcher.ts index 615a45e3d..1dcbe878b 100644 --- a/apps/scheduler/src/handler-dispatcher.ts +++ b/apps/scheduler/src/handler-dispatcher.ts @@ -400,10 +400,14 @@ export class HandlerDispatcher implements NotifyHandler { allHandlers: HandlerServiceDocument[], _graph: DependencyGraph, ): Record | null { + const statusExclusions = handler.autoBackfill + ? ["queued", "processing"] + : ["queued", "processing", "done"]; + const filter: Record = { "run.status": "done", deletedAt: { $exists: false }, - [`run.handlerStatus.${handler._id}.status`]: { $nin: ["queued", "processing", "done"] }, + [`run.handlerStatus.${handler._id}.status`]: { $nin: statusExclusions }, }; // All dependencies must be "done" From 7288b65dd928a4dcad0a114cfaed2ca7d87622ab Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Wed, 1 Jul 2026 13:32:05 -0700 Subject: [PATCH 028/210] fix(scheduler): ignore stale handler completion notifications Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- apps/scheduler/src/handler-dispatcher.test.ts | 44 ++++++++++++++++++- apps/scheduler/src/handler-dispatcher.ts | 15 +++++-- 2 files changed, 55 insertions(+), 4 deletions(-) diff --git a/apps/scheduler/src/handler-dispatcher.test.ts b/apps/scheduler/src/handler-dispatcher.test.ts index 53d652061..3adf8fb76 100644 --- a/apps/scheduler/src/handler-dispatcher.test.ts +++ b/apps/scheduler/src/handler-dispatcher.test.ts @@ -30,7 +30,7 @@ function createMockCollection() { return { findOne: vi.fn(), findOneAndUpdate: vi.fn(), - updateOne: vi.fn().mockResolvedValue(undefined), + updateOne: vi.fn().mockResolvedValue({ matchedCount: 1 }), find: vi.fn(), } as any; } @@ -250,6 +250,48 @@ describe("HandlerDispatcher — maybeTriggerReports", () => { }); }); +describe("HandlerDispatcher — onHandlerComplete", () => { + let collection: ReturnType; + + beforeEach(() => { + collection = createMockCollection(); + }); + + it("only accepts completion when current handler status is processing", async () => { + const d = makeDispatcher(collection) as any; + const maybeTriggerReportsSpy = vi + .spyOn(d, "maybeTriggerReports") + .mockResolvedValue(undefined); + + await d.onHandlerComplete("req-1", "run-1", "pp-atif", "failed"); + + expect(collection.updateOne).toHaveBeenCalledWith( + { _id: "req-1", "run.handlerStatus.pp-atif.status": "processing" }, + { + $set: { + "run.handlerStatus.pp-atif.status": "failed", + "run.handlerStatus.pp-atif.updatedAt": expect.any(Date), + }, + }, + ); + expect(maybeTriggerReportsSpy).toHaveBeenCalledWith("req-1", "run-1"); + }); + + it("ignores stale or duplicate completion notifications", async () => { + collection.updateOne.mockResolvedValue({ matchedCount: 0 }); + const d = makeDispatcher(collection) as any; + const maybeTriggerReportsSpy = vi + .spyOn(d, "maybeTriggerReports") + .mockResolvedValue(undefined); + const loadHandlersSpy = vi.spyOn(d, "loadHandlers"); + + await d.onHandlerComplete("req-1", "run-1", "pp-atif", "done"); + + expect(maybeTriggerReportsSpy).not.toHaveBeenCalled(); + expect(loadHandlersSpy).not.toHaveBeenCalled(); + }); +}); + describe("HandlerDispatcher — buildDispatchFilter", () => { let collection: ReturnType; diff --git a/apps/scheduler/src/handler-dispatcher.ts b/apps/scheduler/src/handler-dispatcher.ts index 1dcbe878b..c7b99b148 100644 --- a/apps/scheduler/src/handler-dispatcher.ts +++ b/apps/scheduler/src/handler-dispatcher.ts @@ -89,9 +89,11 @@ export class HandlerDispatcher implements NotifyHandler { `[HandlerDispatcher] Notify: handler-complete ${handlerId} for ${requestId} (status=${status})`, ); - // Update the handler status on the run document - await this.collection.updateOne( - { _id: requestId } as any, + // Only apply terminal status from an active in-flight execution. + // This avoids stale/duplicate notifies regressing a newly re-dispatched + // handler back to "done" or "failed". + const updateResult = await this.collection.updateOne( + { _id: requestId, [`run.handlerStatus.${handlerId}.status`]: "processing" } as any, { $set: { [`run.handlerStatus.${handlerId}.status`]: status, @@ -100,6 +102,13 @@ export class HandlerDispatcher implements NotifyHandler { } as any, ); + if (updateResult.matchedCount === 0) { + console.log( + `[HandlerDispatcher] Ignored stale/duplicate completion for ${handlerId} on ${requestId}`, + ); + return; + } + if (status === "failed") { // Don't dispatch downstream on failure, but the failure may have drained // the DAG (descendants are now permanently blocked) — check for reports. From 5c64dea4d76a13519a6dfb00dfefae63a1debbd0 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Wed, 1 Jul 2026 14:19:12 -0700 Subject: [PATCH 029/210] fix(post-processing): enforce worker-entrypoint idempotency Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- apps/scheduler/src/handler-dispatcher.test.ts | 87 +++++++++ apps/scheduler/src/handler-dispatcher.ts | 86 ++++---- .../src/handlers/atif-handler.ts | 3 + .../post-processor/src/post-processor.test.ts | 184 ++++++++++++++++++ .../post-processor/src/post-processor.ts | 139 ++++++++++--- apps/workers/post-processor/src/types.ts | 2 + docs/architecture/post-processing.md | 21 +- 7 files changed, 449 insertions(+), 73 deletions(-) create mode 100644 apps/workers/post-processor/src/post-processor.test.ts diff --git a/apps/scheduler/src/handler-dispatcher.test.ts b/apps/scheduler/src/handler-dispatcher.test.ts index 3adf8fb76..9431be37b 100644 --- a/apps/scheduler/src/handler-dispatcher.test.ts +++ b/apps/scheduler/src/handler-dispatcher.test.ts @@ -54,6 +54,21 @@ function makeDispatcher( return new HandlerDispatcher(collection, db, createQueueClient, 60_000, 30, apiUrl); } +function makeDispatcherWithQueue( + collection: any, + handlers: HandlerServiceDocument[] = HANDLERS, + apiUrl = "http://api.test", +) { + const db = createMockDb(handlers); + const queueClient = { + createIfNotExists: vi.fn().mockResolvedValue(undefined), + sendMessage: vi.fn().mockResolvedValue(undefined), + }; + const createQueueClient = vi.fn().mockReturnValue(queueClient); + const dispatcher = new HandlerDispatcher(collection, db, createQueueClient, 60_000, 30, apiUrl); + return { dispatcher, queueClient, createQueueClient }; +} + describe("HandlerDispatcher — drain detection", () => { let collection: ReturnType; @@ -324,4 +339,76 @@ describe("HandlerDispatcher — buildDispatchFilter", () => { $nin: ["queued", "processing", "done"], }); }); + + describe("HandlerDispatcher — dispatchIfEligible", () => { + let collection: ReturnType; + + beforeEach(() => { + collection = createMockCollection(); + }); + + it("allows autoBackfill re-dispatch for outdated done versions", async () => { + collection.findOne.mockResolvedValue({ + _id: "req-1", + run: { + _id: "run-1", + status: "done", + handlerStatus: { + "pp-atif": { status: "done", version: 0 }, + }, + }, + }); + collection.updateOne.mockResolvedValue({ matchedCount: 1 }); + + const { dispatcher, queueClient } = makeDispatcherWithQueue(collection); + await (dispatcher as any).dispatchIfEligible( + "req-1", + "run-1", + HANDLERS[0], + (dispatcher as any).buildGraph(HANDLERS), + HANDLERS, + ); + + expect(queueClient.sendMessage).toHaveBeenCalledTimes(1); + expect(collection.updateOne).toHaveBeenCalledWith( + expect.objectContaining({ + _id: "req-1", + "run._id": "run-1", + "run.status": "done", + "run.handlerStatus.pp-atif.status": { $nin: ["queued", "processing"] }, + $or: [ + { "run.handlerStatus.pp-atif.version": { $exists: false } }, + { "run.handlerStatus.pp-atif.version": { $lt: 1 } }, + ], + }), + { + $set: { + "run.handlerStatus.pp-atif.status": "queued", + "run.handlerStatus.pp-atif.updatedAt": expect.any(Date), + }, + }, + ); + }); + + it("enqueues before marking the handler queued", async () => { + collection.findOne.mockResolvedValue({ + _id: "req-1", + run: { _id: "run-1", status: "done", handlerStatus: {} }, + }); + collection.updateOne.mockResolvedValue({ matchedCount: 1 }); + + const { dispatcher, queueClient } = makeDispatcherWithQueue(collection); + await (dispatcher as any).dispatchIfEligible( + "req-1", + "run-1", + HANDLERS[0], + (dispatcher as any).buildGraph(HANDLERS), + HANDLERS, + ); + + expect(queueClient.sendMessage.mock.invocationCallOrder[0]).toBeLessThan( + collection.updateOne.mock.invocationCallOrder[0], + ); + }); + }); }); diff --git a/apps/scheduler/src/handler-dispatcher.ts b/apps/scheduler/src/handler-dispatcher.ts index c7b99b148..92a9752bc 100644 --- a/apps/scheduler/src/handler-dispatcher.ts +++ b/apps/scheduler/src/handler-dispatcher.ts @@ -288,26 +288,21 @@ export class HandlerDispatcher implements NotifyHandler { const graph = this.buildGraph(handlers); for (const handler of handlers) { - // Find runs that need this handler dispatched - for (let i = 0; i < this.batchSize; i++) { - const filter = this.buildDispatchFilter(handler, handlers, graph); - if (!filter) break; - - const claimed = await this.collection.findOneAndUpdate( - filter as any, - { - $set: { - [`run.handlerStatus.${handler._id}.status`]: "queued", - [`run.handlerStatus.${handler._id}.updatedAt`]: new Date(), - }, - } as any, - { sort: { updatedAt: -1 }, returnDocument: "after" }, - ); - - if (!claimed) break; - - await this.enqueueToHandler(handler, claimed._id, (claimed as any).run?._id); - console.log(`[HandlerDispatcher] Poll-dispatched ${handler._id} for ${claimed._id}`); + const filter = this.buildDispatchFilter(handler, handlers, graph); + if (!filter) continue; + + const candidates = await this.collection + .find(filter as any, { + projection: { _id: 1, "run._id": 1 }, + sort: { updatedAt: -1 }, + limit: this.batchSize, + }) + .toArray(); + + for (const candidate of candidates) { + const runId = (candidate as any).run?._id as string | undefined; + if (!runId) continue; + await this.dispatchIfEligible(candidate._id, runId, handler, graph, handlers); } } } @@ -347,7 +342,7 @@ export class HandlerDispatcher implements NotifyHandler { private async dispatchIfEligible( requestId: string, - _runId: string, + runId: string, handler: HandlerServiceDocument, graph: DependencyGraph, allHandlers: HandlerServiceDocument[], @@ -355,6 +350,7 @@ export class HandlerDispatcher implements NotifyHandler { // Check if all dependencies are satisfied for this request const doc = await this.collection.findOne({ _id: requestId } as any); if (!doc?.run || doc.run.status !== "done") return; + if (doc.run._id !== runId) return; const handlerStatus = (doc.run as any).handlerStatus as | Record @@ -368,24 +364,34 @@ export class HandlerDispatcher implements NotifyHandler { } } - // Check this handler hasn't already been dispatched + // Check whether this handler still needs work. const currentStatus = handlerStatus?.[handler._id]?.status; - if (currentStatus === "queued" || currentStatus === "processing" || currentStatus === "done") { + const currentVersion = handlerStatus?.[handler._id]?.version; + const statusExclusions = handler.autoBackfill + ? ["queued", "processing"] + : ["queued", "processing", "done"]; + + if (currentStatus && statusExclusions.includes(currentStatus)) { return; } - // Check version — skip if already at current version - const currentVersion = handlerStatus?.[handler._id]?.version; - if (currentVersion !== undefined && currentVersion >= handler.version && !handler.autoBackfill) { + if (handler.autoBackfill) { + if (currentVersion !== undefined && currentVersion >= handler.version) { + return; + } + } else if (currentVersion !== undefined) { return; } - // Atomic claim - const claimed = await this.collection.findOneAndUpdate( + const enqueued = await this.enqueueToHandler(handler, requestId, runId); + if (!enqueued) return; + + const queueMarkFilter = this.buildDispatchFilter(handler, allHandlers, graph); + const queueMarkResult = await this.collection.updateOne( { _id: requestId, - "run.status": "done", - [`run.handlerStatus.${handler._id}.status`]: { $nin: ["queued", "processing"] }, + "run._id": runId, + ...(queueMarkFilter ?? {}), } as any, { $set: { @@ -393,12 +399,15 @@ export class HandlerDispatcher implements NotifyHandler { [`run.handlerStatus.${handler._id}.updatedAt`]: new Date(), }, } as any, - { returnDocument: "after" }, ); - if (!claimed) return; + if ((queueMarkResult.matchedCount ?? 0) === 0) { + console.log( + `[HandlerDispatcher] ${handler._id} for ${requestId} advanced concurrently after enqueue; leaving queue message to worker idempotency guard`, + ); + return; + } - await this.enqueueToHandler(handler, requestId, (claimed as any).run?._id); console.log(`[HandlerDispatcher] Dispatched ${handler._id} for ${requestId}`); } @@ -444,7 +453,7 @@ export class HandlerDispatcher implements NotifyHandler { handler: HandlerServiceDocument, requestId: string, runId: string, - ): Promise { + ): Promise { const queueClient = await this.getOrCreateQueueClient(handler.queue); const message = Buffer.from( JSON.stringify({ @@ -456,16 +465,13 @@ export class HandlerDispatcher implements NotifyHandler { try { await queueClient.sendMessage(message); + return true; } catch (err) { - // Roll back status on queue failure - await this.collection.updateOne( - { _id: requestId } as any, - { $unset: { [`run.handlerStatus.${handler._id}.status`]: "" } } as any, - ); console.error( - `[HandlerDispatcher] Queue send failed for ${handler._id}/${requestId}, rolled back:`, + `[HandlerDispatcher] Queue send failed for ${handler._id}/${requestId}:`, err, ); + return false; } } diff --git a/apps/workers/post-processor/src/handlers/atif-handler.ts b/apps/workers/post-processor/src/handlers/atif-handler.ts index 5b51e208c..9a28cb604 100644 --- a/apps/workers/post-processor/src/handlers/atif-handler.ts +++ b/apps/workers/post-processor/src/handlers/atif-handler.ts @@ -5,6 +5,7 @@ import { writeFile, mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import type { PostProcessHandler, PostProcessorMessage, HandlerContext } from "../types.js"; +import { POST_PROCESSOR_VERSION } from "../version.js"; /** * Extracts the blob name (path within the container) from a full blob storage URL. @@ -30,6 +31,8 @@ function extractBlobName(url: string, container = "snapshots"): string | null { */ export class AtifHandler implements PostProcessHandler { readonly type = "atif"; + readonly version = POST_PROCESSOR_VERSION; + readonly autoBackfill = true; async process(message: PostProcessorMessage, ctx: HandlerContext): Promise { const { requestId, runId, iteration } = message; diff --git a/apps/workers/post-processor/src/post-processor.test.ts b/apps/workers/post-processor/src/post-processor.test.ts new file mode 100644 index 000000000..e33cccbd3 --- /dev/null +++ b/apps/workers/post-processor/src/post-processor.test.ts @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { RequestDocument } from "shared"; +import { PostProcessor } from "./post-processor.js"; +import type { PostProcessHandler, PostProcessorMessage } from "./types.js"; + +const CONFIG = { + mongoUri: "mongodb://localhost:27017", + mongoDatabase: "requests-db", + mongoCollection: "requests", + storageAccountName: "devstoreaccount1", + storageConnectionString: "UseDevelopmentStorage=true", + queueName: "post-processor-queue", + batchSize: 1, + pollIntervalMs: 5000, + redisHost: "localhost", + redisPort: 6379, + redisPassword: "", +}; + +function makeDoc(overrides: Partial = {}): RequestDocument { + return { + _id: "req-1", + scenario: { task: "task", criteria: [] }, + workerType: "post-processor", + createdAt: new Date(), + priority: 0, + run: { + _id: "run-1", + attemptNumber: 1, + status: "done", + handlerStatus: {}, + ...overrides, + }, + }; +} + +function makeProcessor() { + const processor = new PostProcessor(CONFIG); + const collection = { + findOneAndUpdate: vi.fn(), + updateOne: vi.fn(), + }; + const blobStorage = {}; + + (processor as any).collection = collection; + (processor as any).blobStorage = blobStorage; + + const safeDeleteMessage = vi + .spyOn(processor as any, "safeDeleteMessage") + .mockResolvedValue(undefined); + const notifyHandlerComplete = vi + .spyOn(processor as any, "notifyHandlerComplete") + .mockResolvedValue(undefined); + + return { processor, collection, blobStorage, safeDeleteMessage, notifyHandlerComplete }; +} + +function makeMessage(messageId = "message-1") { + return { + messageId, + popReceipt: "pop-0", + } as any; +} + +function makeHeartbeat() { + return { + popReceipt: "pop-0", + stop: vi.fn().mockReturnValue("pop-1"), + } as any; +} + +describe("PostProcessor", () => { + let handler: PostProcessHandler; + let log: ReturnType; + + beforeEach(() => { + handler = { + type: "atif", + version: 1, + autoBackfill: true, + process: vi.fn().mockResolvedValue(undefined), + }; + log = vi.fn().mockResolvedValue(undefined); + }); + + it("discards stale messages for an older run attempt", async () => { + const { processor, collection, safeDeleteMessage } = makeProcessor(); + processor.registerHandler(handler); + + const doc = makeDoc({ _id: "run-2" }); + const heartbeat = makeHeartbeat(); + const payload: PostProcessorMessage = { type: "atif", requestId: "req-1", runId: "run-1" }; + + await (processor as any).handleRequest(doc, makeMessage(), heartbeat, log, payload); + + expect(collection.findOneAndUpdate).not.toHaveBeenCalled(); + expect(handler.process).not.toHaveBeenCalled(); + expect(safeDeleteMessage).toHaveBeenCalledWith("message-1", "pop-1"); + }); + + it("no-ops duplicate messages when the handler is already current", async () => { + const { processor, collection, safeDeleteMessage, notifyHandlerComplete } = makeProcessor(); + processor.registerHandler(handler); + + const doc = makeDoc({ + handlerStatus: { + "pp-atif": { status: "done", version: 1, updatedAt: new Date() }, + }, + }); + const heartbeat = makeHeartbeat(); + const payload: PostProcessorMessage = { type: "atif", requestId: "req-1", runId: "run-1" }; + + collection.findOneAndUpdate.mockResolvedValue(null); + + await (processor as any).handleRequest(doc, makeMessage(), heartbeat, log, payload); + + expect(collection.findOneAndUpdate).toHaveBeenCalledWith( + expect.objectContaining({ + _id: "req-1", + "run._id": "run-1", + "run.status": "done", + "run.handlerStatus.pp-atif.status": { $nin: ["queued", "processing"] }, + $or: [ + { "run.handlerStatus.pp-atif.version": { $exists: false } }, + { "run.handlerStatus.pp-atif.version": { $lt: 1 } }, + ], + }), + expect.any(Object), + expect.objectContaining({ returnDocument: "after" }), + ); + expect(handler.process).not.toHaveBeenCalled(); + expect(collection.updateOne).not.toHaveBeenCalled(); + expect(notifyHandlerComplete).not.toHaveBeenCalled(); + expect(safeDeleteMessage).toHaveBeenCalledWith("message-1", "pop-1"); + }); + + it("re-processes stale versions and stamps success for the same run attempt", async () => { + const { processor, collection, safeDeleteMessage, notifyHandlerComplete } = makeProcessor(); + processor.registerHandler(handler); + + const doc = makeDoc({ + handlerStatus: { + "pp-atif": { status: "done", version: 0, updatedAt: new Date() }, + }, + }); + const heartbeat = makeHeartbeat(); + const payload: PostProcessorMessage = { type: "atif", requestId: "req-1", runId: "run-1" }; + + collection.findOneAndUpdate.mockResolvedValue({ _id: "req-1" }); + collection.updateOne.mockResolvedValue({ matchedCount: 1 }); + + await (processor as any).handleRequest(doc, makeMessage(), heartbeat, log, payload); + + expect(handler.process).toHaveBeenCalledWith( + payload, + expect.objectContaining({ + blobStorage: expect.any(Object), + collection, + log, + }), + ); + expect(collection.updateOne).toHaveBeenCalledWith( + { + _id: "req-1", + "run._id": "run-1", + "run.handlerStatus.pp-atif.status": "processing", + }, + { + $set: expect.objectContaining({ + "run.postProcessorVersion": 1, + "run.postProcessorStatus": "done", + "run.handlerStatus.pp-atif.status": "done", + "run.handlerStatus.pp-atif.version": 1, + "run.handlerStatus.pp-atif.updatedAt": expect.any(Date), + }), + }, + ); + expect(notifyHandlerComplete).toHaveBeenCalledWith("req-1", "run-1", "pp-atif", "done"); + expect(safeDeleteMessage).toHaveBeenCalledWith("message-1", "pop-1"); + }); +}); diff --git a/apps/workers/post-processor/src/post-processor.ts b/apps/workers/post-processor/src/post-processor.ts index 4b1b6e847..32bec7202 100644 --- a/apps/workers/post-processor/src/post-processor.ts +++ b/apps/workers/post-processor/src/post-processor.ts @@ -3,24 +3,13 @@ import type { DequeuedMessageItem } from "@azure/storage-queue"; import { BaseQueueProcessor, BlobStorage, type BaseQueueProcessorConfig, type LogEvent, type VisibilityHeartbeat } from "shared"; -import { POST_PROCESSOR_VERSION } from "./version.js"; +import type { RequestDocument, HandlerRunStatus } from "shared"; import type { PostProcessHandler, PostProcessorMessage, HandlerContext } from "./types.js"; export interface PostProcessorConfig extends BaseQueueProcessorConfig { apiBaseUrl?: string; } -interface RequestDocument { - _id: string; - run?: { - _id: string; - status: string; - turns?: Array<{ iteration: number; harUrl?: string; atifUrl?: string }>; - postProcessorVersion?: number; - postProcessorStatus?: string; - }; -} - /** * Post-processor worker: extensible queue processor with handler registry. * Dispatched by the PostProcessorDispatcher in the scheduler when runs @@ -45,6 +34,43 @@ export class PostProcessor extends BaseQueueProcessor { console.log(`[post-processor] Registered handler: ${handler.type}`); } + private isPostProcessorMessage(payload: unknown): payload is PostProcessorMessage { + return typeof payload === "object" && + payload !== null && + typeof (payload as Record).type === "string" && + typeof (payload as Record).requestId === "string" && + typeof (payload as Record).runId === "string"; + } + + private buildHandlerClaimFilter( + requestId: string, + runId: string, + handlerId: string, + handler: PostProcessHandler, + ): Record { + const statusExclusions = handler.autoBackfill + ? ["queued", "processing"] + : ["queued", "processing", "done"]; + + const filter: Record = { + _id: requestId, + "run._id": runId, + "run.status": "done", + [`run.handlerStatus.${handlerId}.status`]: { $nin: statusExclusions }, + }; + + if (handler.autoBackfill) { + filter.$or = [ + { [`run.handlerStatus.${handlerId}.version`]: { $exists: false } }, + { [`run.handlerStatus.${handlerId}.version`]: { $lt: handler.version } }, + ]; + } else { + filter[`run.handlerStatus.${handlerId}.version`] = { $exists: false }; + } + + return filter; + } + protected async handleRequest( doc: RequestDocument, message: DequeuedMessageItem, @@ -52,14 +78,14 @@ export class PostProcessor extends BaseQueueProcessor { log: (level: LogEvent["level"], msg: string, data?: Record) => Promise, payload?: Record, ): Promise { - const msg = payload as unknown as PostProcessorMessage; - - if (!msg?.type) { + if (!this.isPostProcessorMessage(payload)) { await log("warn", "Message missing 'type' field, discarding"); await this.safeDeleteMessage(message.messageId, heartbeat.stop()); return; } + const msg: PostProcessorMessage = payload; + const handler = this.handlers.get(msg.type); if (!handler) { await log("warn", `No handler registered for type '${msg.type}', discarding`); @@ -67,14 +93,45 @@ export class PostProcessor extends BaseQueueProcessor { return; } - // Set status to "processing". - // Concurrency safety: the Azure Storage Queue guarantees at-most-once delivery - // via visibility timeout, so only one worker processes a given message at a time. - await this.collection.updateOne( - { _id: doc._id } as any, - { $set: { "run.postProcessorStatus": "processing" } } as any, + if (doc.run?._id !== msg.runId) { + await log("info", "Stale post-processing message discarded (runId mismatch)", { + messageRunId: msg.runId, + currentRunId: doc.run?._id, + }); + await this.safeDeleteMessage(message.messageId, heartbeat.stop()); + return; + } + + const handlerId = `pp-${msg.type}`; + const currentStatus = doc.run?.handlerStatus?.[handlerId] as HandlerRunStatus | undefined; + + const claim = await this.collection.findOneAndUpdate( + this.buildHandlerClaimFilter(doc._id, msg.runId, handlerId, handler) as any, + { + $set: { + "run.postProcessorStatus": "processing", + [`run.handlerStatus.${handlerId}.status`]: "processing", + [`run.handlerStatus.${handlerId}.updatedAt`]: new Date(), + }, + $unset: { + [`run.handlerStatus.${handlerId}.error`]: "", + }, + } as any, + { returnDocument: "after" }, ); + if (!claim) { + await log("info", "Post-processing message no longer needed, discarding", { + handlerId, + runId: msg.runId, + currentStatus: currentStatus?.status, + currentVersion: currentStatus?.version, + targetVersion: handler.version, + }); + await this.safeDeleteMessage(message.messageId, heartbeat.stop()); + return; + } + try { await log("info", `Running handler: ${msg.type}`); @@ -87,21 +144,33 @@ export class PostProcessor extends BaseQueueProcessor { await handler.process(msg, ctx); // Stamp version and status on success (legacy fields + new handlerStatus) - const handlerId = `pp-${msg.type}`; // e.g., "pp-atif" - await this.collection.updateOne( - { _id: doc._id } as any, + const successResult = await this.collection.updateOne( + { + _id: doc._id, + "run._id": msg.runId, + [`run.handlerStatus.${handlerId}.status`]: "processing", + } as any, { $set: { - "run.postProcessorVersion": POST_PROCESSOR_VERSION, + "run.postProcessorVersion": handler.version, "run.postProcessorStatus": "done", [`run.handlerStatus.${handlerId}.status`]: "done", - [`run.handlerStatus.${handlerId}.version`]: POST_PROCESSOR_VERSION, + [`run.handlerStatus.${handlerId}.version`]: handler.version, [`run.handlerStatus.${handlerId}.updatedAt`]: new Date(), }, } as any, ); - await log("info", `Post-processing complete (v${POST_PROCESSOR_VERSION})`); + if ((successResult.matchedCount ?? 0) === 0) { + await log("warn", `Handler '${msg.type}' completed after state changed; skipping terminal write`, { + handlerId, + runId: msg.runId, + }); + await this.safeDeleteMessage(message.messageId, heartbeat.stop()); + return; + } + + await log("info", `Post-processing complete (v${handler.version})`); // Notify the scheduler that this handler is done (best-effort) await this.notifyHandlerComplete(doc._id, doc.run?._id ?? "", handlerId, "done"); @@ -110,20 +179,26 @@ export class PostProcessor extends BaseQueueProcessor { await log("error", `Handler '${msg.type}' failed: ${errMsg}`); // Mark as failed so scheduler doesn't immediately re-dispatch - const handlerId = `pp-${msg.type}`; - await this.collection.updateOne( - { _id: doc._id } as any, + const failureResult = await this.collection.updateOne( + { + _id: doc._id, + "run._id": msg.runId, + [`run.handlerStatus.${handlerId}.status`]: "processing", + } as any, { $set: { "run.postProcessorStatus": "failed", [`run.handlerStatus.${handlerId}.status`]: "failed", [`run.handlerStatus.${handlerId}.updatedAt`]: new Date(), + [`run.handlerStatus.${handlerId}.error`]: errMsg, }, } as any, ); - // Notify scheduler of failure (best-effort — don't dispatch downstream) - await this.notifyHandlerComplete(doc._id, doc.run?._id ?? "", handlerId, "failed"); + if ((failureResult.matchedCount ?? 0) > 0) { + // Notify scheduler of failure (best-effort — don't dispatch downstream) + await this.notifyHandlerComplete(doc._id, doc.run?._id ?? "", handlerId, "failed"); + } throw err; } diff --git a/apps/workers/post-processor/src/types.ts b/apps/workers/post-processor/src/types.ts index 8765dd926..e1ee29669 100644 --- a/apps/workers/post-processor/src/types.ts +++ b/apps/workers/post-processor/src/types.ts @@ -22,5 +22,7 @@ export interface HandlerContext { /** Interface for post-processing handlers (extensibility point). */ export interface PostProcessHandler { readonly type: string; + readonly version: number; + readonly autoBackfill: boolean; process(message: PostProcessorMessage, ctx: HandlerContext): Promise; } diff --git a/docs/architecture/post-processing.md b/docs/architecture/post-processing.md index 910812ac0..4407afad0 100644 --- a/docs/architecture/post-processing.md +++ b/docs/architecture/post-processing.md @@ -63,6 +63,8 @@ The post-processor uses a registry pattern for extensibility: ```typescript interface PostProcessHandler { readonly type: string; + readonly version: number; + readonly autoBackfill: boolean; process(message: PostProcessorMessage, ctx: HandlerContext): Promise; } @@ -88,6 +90,23 @@ processor.registerHandler(new AtifHandler()); processor.start(); ``` +## Idempotency and Dispatch Semantics + +Post-processing delivery is treated as **at-least-once**. Queue messages may be duplicated or redelivered, and the scheduler may enqueue a handler message before the corresponding `queued` marker is durably written back to MongoDB. + +To keep this safe, idempotency is enforced at the **post-processor worker entrypoint**, not inside each individual handler: + +1. The scheduler decides whether work is needed from `run.handlerStatus[handlerId]` + handler metadata (`version`, `autoBackfill`). +2. The worker re-checks that same eligibility when a message is dequeued, scoped to the specific `runId`. +3. The worker atomically claims the handler by transitioning its status to `processing`. +4. If the message is stale, duplicated, or the handler is already current, the worker deletes the queue message and no-ops. + +This means: + +- A crash after queue send but before the scheduler writes `queued` no longer wedges the run forever. +- Duplicate queue messages are harmless. +- Handler implementations can stay simple; correctness does not depend on each handler re-implementing duplicate guards. + ### Adding a New Handler 1. Create a new file in `apps/workers/post-processor/src/handlers/` @@ -207,7 +226,7 @@ stateDiagram-v2 | Status | Meaning | | --- | --- | | *(absent)* | Run hasn't been dispatched for post-processing yet | -| `queued` | Message sent to queue, awaiting pickup | +| `queued` | Message sent to queue, awaiting pickup (best-effort marker; the worker entrypoint is authoritative) | | `processing` | Worker is actively processing | | `done` | Post-processing completed successfully | | `failed` | Handler threw an error (may be retried by scheduler on next poll) | From fe5b9eed30ba2bde3d23f115c95b946d6eaaffd1 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Wed, 1 Jul 2026 14:21:51 -0700 Subject: [PATCH 030/210] docs(post-processing): clarify enqueue and claim boundaries Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- apps/scheduler/src/handler-dispatcher.ts | 9 +++++++++ apps/workers/post-processor/src/post-processor.ts | 7 +++++++ 2 files changed, 16 insertions(+) diff --git a/apps/scheduler/src/handler-dispatcher.ts b/apps/scheduler/src/handler-dispatcher.ts index 92a9752bc..b93afca52 100644 --- a/apps/scheduler/src/handler-dispatcher.ts +++ b/apps/scheduler/src/handler-dispatcher.ts @@ -383,9 +383,18 @@ export class HandlerDispatcher implements NotifyHandler { return; } + // Queue FIRST, then write the best-effort "queued" marker back to Mongo. + // The queue message is the durable work signal; the DB status is only an + // optimization / observability hint. If we crash after sendMessage() but + // before this update, the worker entrypoint claim still makes the message + // safe and prevents a permanent "queued" wedge. const enqueued = await this.enqueueToHandler(handler, requestId, runId); if (!enqueued) return; + // This is NOT the authoritative processing claim. It only records that a + // message was successfully placed on the queue and is expected to be picked + // up soon. The worker performs the real claim when it atomically flips the + // handler from eligible -> processing for this specific run attempt. const queueMarkFilter = this.buildDispatchFilter(handler, allHandlers, graph); const queueMarkResult = await this.collection.updateOne( { diff --git a/apps/workers/post-processor/src/post-processor.ts b/apps/workers/post-processor/src/post-processor.ts index 32bec7202..db2a46c9f 100644 --- a/apps/workers/post-processor/src/post-processor.ts +++ b/apps/workers/post-processor/src/post-processor.ts @@ -105,6 +105,11 @@ export class PostProcessor extends BaseQueueProcessor { const handlerId = `pp-${msg.type}`; const currentStatus = doc.run?.handlerStatus?.[handlerId] as HandlerRunStatus | undefined; + // This is the authoritative claim. A queued message alone does not mean the + // handler still needs work: the scheduler may have enqueued optimistically, + // another worker may already be processing it, or a fresher backfill may + // have completed it. Only the worker can safely decide that by atomically + // transitioning the specific run attempt into "processing". const claim = await this.collection.findOneAndUpdate( this.buildHandlerClaimFilter(doc._id, msg.runId, handlerId, handler) as any, { @@ -121,6 +126,8 @@ export class PostProcessor extends BaseQueueProcessor { ); if (!claim) { + // No claim means the message is stale, duplicate, or already satisfied. + // Ack and drop it — at-least-once delivery is expected here. await log("info", "Post-processing message no longer needed, discarding", { handlerId, runId: msg.runId, From 87df1b0573339259ed3a848623495698a47ca050 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Wed, 1 Jul 2026 14:45:58 -0700 Subject: [PATCH 031/210] perf(scheduler): cache handler topology with short TTL MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit loadHandlers() sits on the notify/poll hot path (2-3 reads per notify, one per poll cycle) but the services collection only changes on deploys. Cache the topology in-memory with a 60s TTL (configurable) to eliminate nearly all of those reads — meaningful on CosmosDB where each query costs RUs. registerHandler invalidates the cache after upserting so new topology is picked up immediately; cycle-check validation reads fresh. Addresses jduffney review feedback #4 on #1147. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- apps/scheduler/src/handler-dispatcher.test.ts | 58 +++++++++++++++++++ apps/scheduler/src/handler-dispatcher.ts | 35 +++++++++-- docs/architecture/post-processing.md | 2 + 3 files changed, 89 insertions(+), 6 deletions(-) diff --git a/apps/scheduler/src/handler-dispatcher.test.ts b/apps/scheduler/src/handler-dispatcher.test.ts index 9431be37b..32d954243 100644 --- a/apps/scheduler/src/handler-dispatcher.test.ts +++ b/apps/scheduler/src/handler-dispatcher.test.ts @@ -307,6 +307,64 @@ describe("HandlerDispatcher — onHandlerComplete", () => { }); }); +describe("HandlerDispatcher — handler topology caching", () => { + function makeWithSpies(ttlMs = 60_000, handlers: HandlerServiceDocument[] = HANDLERS) { + const collection = createMockCollection(); + const toArray = vi.fn().mockResolvedValue(handlers); + const find = vi.fn().mockReturnValue({ toArray }); + const servicesUpdateOne = vi.fn().mockResolvedValue(undefined); + const db = { + collection: vi.fn().mockReturnValue({ find, updateOne: servicesUpdateOne }), + } as any; + const dispatcher = new HandlerDispatcher( + collection, + db, + vi.fn(), + 60_000, + 30, + "http://api.test", + ttlMs, + ) as any; + return { dispatcher, find, toArray, servicesUpdateOne }; + } + + it("reuses cached topology within the TTL window", async () => { + const { dispatcher, toArray } = makeWithSpies(60_000); + + await dispatcher.loadHandlers(); + await dispatcher.loadHandlers(); + + expect(toArray).toHaveBeenCalledTimes(1); + }); + + it("re-reads topology once the TTL has elapsed", async () => { + const { dispatcher, toArray } = makeWithSpies(0); // TTL 0 → every read is stale + + await dispatcher.loadHandlers(); + await dispatcher.loadHandlers(); + + expect(toArray).toHaveBeenCalledTimes(2); + }); + + it("invalidates the cache when a handler is registered", async () => { + const { dispatcher, toArray } = makeWithSpies(60_000); + + await dispatcher.loadHandlers(); // read #1 — populates cache + await dispatcher.registerHandler({ + _id: "pp-new", + type: "post-process-handler", + version: 1, + queue: "pp-new-queue", + selector: "new", + autoBackfill: false, + dependsOn: [], + }); // read #2 (forceFresh validation) + invalidate + await dispatcher.loadHandlers(); // read #3 — cache was invalidated + + expect(toArray).toHaveBeenCalledTimes(3); + }); +}); + describe("HandlerDispatcher — buildDispatchFilter", () => { let collection: ReturnType; diff --git a/apps/scheduler/src/handler-dispatcher.ts b/apps/scheduler/src/handler-dispatcher.ts index b93afca52..760bd87d8 100644 --- a/apps/scheduler/src/handler-dispatcher.ts +++ b/apps/scheduler/src/handler-dispatcher.ts @@ -25,6 +25,14 @@ export class HandlerDispatcher implements NotifyHandler { private dispatching = false; private queueClients = new Map(); + /** Cached handler topology. The `services` collection changes only on deploys + * (via registerHandler), yet loadHandlers() sits on the notify/poll hot path + * (2–3 reads per notify, plus every poll cycle). A short TTL cache eliminates + * nearly all of those reads — significant on CosmosDB where each query costs + * RUs — while registerHandler invalidates it so new topology is picked up at + * once rather than after the TTL elapses. */ + private handlerCache: { docs: HandlerServiceDocument[]; expiresAt: number } | null = null; + /** Retry policy for the report-trigger POST. The 30s poll net is the durable * backstop, so in-call retries are modest. Overridable in tests. */ private reportRetryOptions: RetryOptions = { @@ -41,6 +49,7 @@ export class HandlerDispatcher implements NotifyHandler { private readonly pollIntervalMs: number = 30_000, private readonly batchSize: number = 30, private readonly apiUrl: string = process.env.API_URL || "http://api:80", + private readonly handlerCacheTtlMs: number = 60_000, ) {} start(): void { @@ -137,8 +146,9 @@ export class HandlerDispatcher implements NotifyHandler { } async registerHandler(doc: HandlerServiceDocument): Promise { - // Validate the resulting topology has no cycles before persisting. - const existing = await this.loadHandlers(); + // Validate the resulting topology has no cycles before persisting. Read + // fresh (bypass the cache) so validation reflects any concurrent registrations. + const existing = await this.loadHandlers(true); const merged = [ ...existing.filter((h) => h._id !== doc._id), doc, @@ -158,6 +168,8 @@ export class HandlerDispatcher implements NotifyHandler { } as any, { upsert: true }, ); + // Topology changed — drop the cache so the next read picks up the new handler. + this.invalidateHandlerCache(); console.log( `[HandlerDispatcher] Registered handler ${_id} (version=${doc.version}, queue=${doc.queue}, dependsOn=[${doc.dependsOn.join(", ")}])`, ); @@ -494,12 +506,23 @@ export class HandlerDispatcher implements NotifyHandler { return client; } - private async loadHandlers(): Promise { - const docs = await this.db + private async loadHandlers(forceFresh = false): Promise { + const now = Date.now(); + if (!forceFresh && this.handlerCache && this.handlerCache.expiresAt > now) { + return this.handlerCache.docs; + } + const docs = (await this.db .collection("services") .find({ type: "post-process-handler" }) - .toArray(); - return docs as unknown as HandlerServiceDocument[]; + .toArray()) as unknown as HandlerServiceDocument[]; + this.handlerCache = { docs, expiresAt: now + this.handlerCacheTtlMs }; + return docs; + } + + /** Drops the cached topology so the next loadHandlers() re-reads from Mongo. + * Called after registerHandler persists a change. */ + private invalidateHandlerCache(): void { + this.handlerCache = null; } private buildGraph(handlers: HandlerServiceDocument[]): DependencyGraph { diff --git a/docs/architecture/post-processing.md b/docs/architecture/post-processing.md index 4407afad0..b695ca92e 100644 --- a/docs/architecture/post-processing.md +++ b/docs/architecture/post-processing.md @@ -149,6 +149,8 @@ dependsOn: [] On deploy, a generic registration script — `packages/shared/src/scripts/register-handler.ts` — reads the `handler.yaml` pointed to by `HANDLER_YAML_PATH`, waits for the scheduler's `/health`, and POSTs the parsed document to `${SCHEDULER_URL}/handlers/register` (with retry). The scheduler validates the document, runs a cycle check against the existing topology, and upserts it into the `services` collection via `HandlerDispatcher.registerHandler`. **Workers never write to the `services` collection directly** — the scheduler is the sole owner. +Because handler topology is read on the dispatch hot path (every notify reads it 2–3 times, and every poll cycle once) but only changes on deploys, the scheduler caches it in-memory with a short TTL (60s, configurable via the `HandlerDispatcher` constructor). `registerHandler` invalidates the cache immediately after upserting, so a freshly registered handler is picked up on the next dispatch rather than after the TTL elapses. Cycle-check validation always reads fresh (bypassing the cache). + ```mermaid flowchart LR YAML[handler.yaml] --> SCRIPT[register-handler.ts] From a56c0beb8700566ebcfebf0162be4a769bf749d2 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Wed, 1 Jul 2026 15:06:17 -0700 Subject: [PATCH 032/210] perf(scheduler): raise handler topology cache TTL to 5min, make it env-configurable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The scheduler is a singleton (replicas: 1, Recreate) and the sole writer of the services collection, and registerHandler invalidates the cache on every topology change — so cache coherence rests on invalidation, not expiry. A 60s TTL sat barely above the 30s poll, forcing a needless fresh read on roughly every other poll cycle. Raise the default to 5min (well above the poll interval) and expose SCHEDULER_HANDLER_CACHE_TTL_MS so the TTL is only a coarse backstop for out-of-band writes or a future scale-out beyond one replica. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- ENV_VARIABLES.md | 6 ++++++ apps/scheduler/src/handler-dispatcher.ts | 16 +++++++++++----- apps/scheduler/src/index.ts | 13 ++++++++++++- docs/architecture/post-processing.md | 2 +- 4 files changed, 30 insertions(+), 7 deletions(-) diff --git a/ENV_VARIABLES.md b/ENV_VARIABLES.md index 73262c238..48016b472 100644 --- a/ENV_VARIABLES.md +++ b/ENV_VARIABLES.md @@ -360,6 +360,12 @@ How often the request scheduler polls MongoDB for pending requests to dispatch t How often the post-processor dispatcher polls for completed runs needing post-processing. This is a **backfill/catch-up** mechanism — the primary dispatch path is event-driven (coder workers enqueue directly on run completion). The 30s default keeps idle RU consumption low while still catching missed events or version-upgrade backfills within a reasonable window. Reduce temporarily for large backfills. +### SCHEDULER_HANDLER_CACHE_TTL_MS +**Default:** `300000` +**Type:** integer (milliseconds) + +TTL for the DAG dispatcher's in-memory cache of handler topology (the `services` collection, `type: "post-process-handler"`). `loadHandlers()` runs on the notify/poll hot path (2–3 reads per notify plus every poll cycle) but topology only changes on deploys, so caching it eliminates nearly all of those reads (meaningful on CosmosDB where each query costs RUs). Cache coherence comes primarily from `HandlerDispatcher.registerHandler` invalidating the cache the moment topology changes — the scheduler is a singleton (`replicas: 1`, `Recreate`) and the sole writer of the collection — so this TTL is only a coarse backstop for out-of-band writes or a future scale-out to more than one replica. Kept well above `SCHEDULER_PP_POLL_INTERVAL_MS` so the poll loop doesn't force a fresh read every cycle. + ### QUEUE_NAME_POST_PROCESSOR **Default:** `post-processor-queue` **Type:** string diff --git a/apps/scheduler/src/handler-dispatcher.ts b/apps/scheduler/src/handler-dispatcher.ts index 760bd87d8..4ff1f8275 100644 --- a/apps/scheduler/src/handler-dispatcher.ts +++ b/apps/scheduler/src/handler-dispatcher.ts @@ -27,10 +27,16 @@ export class HandlerDispatcher implements NotifyHandler { /** Cached handler topology. The `services` collection changes only on deploys * (via registerHandler), yet loadHandlers() sits on the notify/poll hot path - * (2–3 reads per notify, plus every poll cycle). A short TTL cache eliminates - * nearly all of those reads — significant on CosmosDB where each query costs - * RUs — while registerHandler invalidates it so new topology is picked up at - * once rather than after the TTL elapses. */ + * (2–3 reads per notify, plus every poll cycle). A TTL cache eliminates nearly + * all of those reads — significant on CosmosDB where each query costs RUs. + * + * Coherence comes primarily from `registerHandler` invalidating the cache the + * moment topology changes, not from expiry: the scheduler is a singleton + * (`replicas: 1`, `Recreate`) and the sole writer of the `services` collection, + * so a same-process registration is reflected immediately regardless of TTL. + * The TTL is therefore a coarse defensive backstop (out-of-band writes, or a + * future scale-out to >1 replica) and is intentionally set well above the poll + * interval so the poll loop doesn't force a fresh read every cycle. */ private handlerCache: { docs: HandlerServiceDocument[]; expiresAt: number } | null = null; /** Retry policy for the report-trigger POST. The 30s poll net is the durable @@ -49,7 +55,7 @@ export class HandlerDispatcher implements NotifyHandler { private readonly pollIntervalMs: number = 30_000, private readonly batchSize: number = 30, private readonly apiUrl: string = process.env.API_URL || "http://api:80", - private readonly handlerCacheTtlMs: number = 60_000, + private readonly handlerCacheTtlMs: number = 300_000, ) {} start(): void { diff --git a/apps/scheduler/src/index.ts b/apps/scheduler/src/index.ts index c59522167..4ce9f053f 100644 --- a/apps/scheduler/src/index.ts +++ b/apps/scheduler/src/index.ts @@ -184,6 +184,14 @@ async function main(): Promise { 10, ); + // Handler topology is deploy-static and invalidated on registration, so this + // TTL only backstops out-of-band/multi-replica changes — keep it well above + // the poll interval so the poll loop doesn't force a fresh read every cycle. + const handlerCacheTtlMs = parseInt( + process.env.SCHEDULER_HANDLER_CACHE_TTL_MS || "300000", + 10, + ); + const postProcessorDispatcher = new PostProcessorDispatcher( collection, db, @@ -201,9 +209,12 @@ async function main(): Promise { ppPollIntervalMs, 30, API_URL, + handlerCacheTtlMs, ); handlerDispatcher.start(); - console.log("[Scheduler] Handler dispatcher (DAG) started"); + console.log( + `[Scheduler] Handler dispatcher (DAG) started (poll=${ppPollIntervalMs}ms, topologyCacheTtl=${handlerCacheTtlMs}ms)`, + ); // Start the stuck-run reaper (authoritative backstop). Redis is non-fatal: // on misconfig or connection failure the reaper self-disables (its sweeps diff --git a/docs/architecture/post-processing.md b/docs/architecture/post-processing.md index b695ca92e..298a0058d 100644 --- a/docs/architecture/post-processing.md +++ b/docs/architecture/post-processing.md @@ -149,7 +149,7 @@ dependsOn: [] On deploy, a generic registration script — `packages/shared/src/scripts/register-handler.ts` — reads the `handler.yaml` pointed to by `HANDLER_YAML_PATH`, waits for the scheduler's `/health`, and POSTs the parsed document to `${SCHEDULER_URL}/handlers/register` (with retry). The scheduler validates the document, runs a cycle check against the existing topology, and upserts it into the `services` collection via `HandlerDispatcher.registerHandler`. **Workers never write to the `services` collection directly** — the scheduler is the sole owner. -Because handler topology is read on the dispatch hot path (every notify reads it 2–3 times, and every poll cycle once) but only changes on deploys, the scheduler caches it in-memory with a short TTL (60s, configurable via the `HandlerDispatcher` constructor). `registerHandler` invalidates the cache immediately after upserting, so a freshly registered handler is picked up on the next dispatch rather than after the TTL elapses. Cycle-check validation always reads fresh (bypassing the cache). +Because handler topology is read on the dispatch hot path (every notify reads it 2–3 times, and every poll cycle once) but only changes on deploys, the scheduler caches it in-memory with a TTL (default 5 min, `SCHEDULER_HANDLER_CACHE_TTL_MS`). Coherence comes primarily from invalidation, not expiry: `registerHandler` invalidates the cache immediately after upserting, and since the scheduler is a singleton (`replicas: 1`, `Recreate`) and the sole writer of the `services` collection, a change is reflected at once regardless of TTL. The TTL is therefore only a defensive backstop for out-of-band writes or a future scale-out to more than one replica, and is deliberately kept well above the poll interval so the poll loop doesn't force a fresh read every cycle. Cycle-check validation always reads fresh (bypassing the cache). ```mermaid flowchart LR From b55299c9a06f3b27d6676e048717dbe1c3be1400 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Wed, 1 Jul 2026 15:14:21 -0700 Subject: [PATCH 033/210] docs: call out single-replica limitation of the handler topology cache Make explicit that process-local cache invalidation is only correct while the scheduler runs as a single replica, and document the cross-replica mitigations (Redis pub/sub or change-stream watcher, or a shorter TTL) required before any scale-out. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/architecture/post-processing.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/architecture/post-processing.md b/docs/architecture/post-processing.md index 298a0058d..7fd352e55 100644 --- a/docs/architecture/post-processing.md +++ b/docs/architecture/post-processing.md @@ -151,6 +151,8 @@ On deploy, a generic registration script — `packages/shared/src/scripts/regist Because handler topology is read on the dispatch hot path (every notify reads it 2–3 times, and every poll cycle once) but only changes on deploys, the scheduler caches it in-memory with a TTL (default 5 min, `SCHEDULER_HANDLER_CACHE_TTL_MS`). Coherence comes primarily from invalidation, not expiry: `registerHandler` invalidates the cache immediately after upserting, and since the scheduler is a singleton (`replicas: 1`, `Recreate`) and the sole writer of the `services` collection, a change is reflected at once regardless of TTL. The TTL is therefore only a defensive backstop for out-of-band writes or a future scale-out to more than one replica, and is deliberately kept well above the poll interval so the poll loop doesn't force a fresh read every cycle. Cycle-check validation always reads fresh (bypassing the cache). +> **Limitation — the topology cache assumes a single scheduler replica.** In-memory cache invalidation is process-local, so it is only correct while the scheduler runs as one replica. This holds today (`deploy/base/scheduler.yaml`: `replicas: 1`, `strategy: Recreate`, so pods never overlap). **If the scheduler is ever scaled beyond one replica, this cache becomes stale-prone:** a `registerHandler` on one replica invalidates only that replica's cache, so the others keep serving old topology for up to the TTL. The blast radius is bounded — with idempotent dispatch a newly added handler is still dispatched by whichever replica has fresh topology, and a removed/re-wired handler self-heals within the TTL — but it is real. Before scaling out, replace process-local invalidation with a cross-replica signal (e.g. Redis pub/sub on `registerHandler`, or a change-stream watcher on the `services` collection), or lower `SCHEDULER_HANDLER_CACHE_TTL_MS` to shrink the staleness window. + ```mermaid flowchart LR YAML[handler.yaml] --> SCRIPT[register-handler.ts] From ab696a2b94129e4f1af71665240da4071fecd5a5 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Wed, 1 Jul 2026 15:24:04 -0700 Subject: [PATCH 034/210] feat(scheduler): cap notify/register request body size (64 KB) Guards the singleton scheduler HTTP server against unbounded-memory requests. Rejects oversized payloads with 413 Payload Too Large + Connection: close, using a Content-Length fast-reject plus a streaming byte-count cap for chunked/lying clients. maxBodyBytes is threaded through createHttpServer so tests can use a small deterministic cap. Addresses jduffney review feedback #5 on #1147. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- apps/scheduler/src/notify-routes.test.ts | 88 +++++++++++++++- apps/scheduler/src/notify-routes.ts | 122 ++++++++++++++++++++--- docs/architecture/post-processing.md | 2 +- 3 files changed, 192 insertions(+), 20 deletions(-) diff --git a/apps/scheduler/src/notify-routes.test.ts b/apps/scheduler/src/notify-routes.test.ts index 797256018..2d7ef741b 100644 --- a/apps/scheduler/src/notify-routes.test.ts +++ b/apps/scheduler/src/notify-routes.test.ts @@ -2,11 +2,22 @@ // Licensed under the MIT License. import type { AddressInfo } from "node:net"; +import type { IncomingMessage } from "node:http"; +import { PassThrough } from "node:stream"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { createHttpServer, type NotifyHandler } from "./notify-routes.js"; +import { + createHttpServer, + readJsonBody, + MAX_BODY_BYTES, + type HttpServerOptions, + type NotifyHandler, +} from "./notify-routes.js"; -async function startServer(handler: NotifyHandler): Promise<{ server: ReturnType; baseUrl: string }> { - const server = createHttpServer(handler); +async function startServer( + handler: NotifyHandler, + options?: HttpServerOptions, +): Promise<{ server: ReturnType; baseUrl: string }> { + const server = createHttpServer(handler, options); await new Promise((resolve, reject) => { server.once("error", reject); @@ -201,4 +212,75 @@ describe("createHttpServer", () => { expect(response.status).toBe(400); expect(handler.registerHandler).not.toHaveBeenCalled(); }); + + it("returns 413 and does not invoke the handler when the body exceeds the cap", async () => { + const handler: NotifyHandler = { + onRunTerminal: vi.fn().mockResolvedValue(undefined), + onHandlerComplete: vi.fn().mockResolvedValue(undefined), + registerHandler: vi.fn().mockResolvedValue(undefined), + }; + // Tiny cap so a small, deterministic payload trips it (no socket-buffer race). + const { server, baseUrl } = await startServer(handler, { maxBodyBytes: 32 }); + servers.push(server); + + const response = await fetch(`${baseUrl}/notify/run-terminal`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ requestId: "r".repeat(100), runId: "run-1" }), + }); + + expect(response.status).toBe(413); + expect(await response.json()).toEqual({ error: "Request body too large" }); + expect(handler.onRunTerminal).not.toHaveBeenCalled(); + }); +}); + +describe("readJsonBody", () => { + /** Build a mock IncomingMessage backed by a PassThrough with the given headers. */ + function mockReq(headers: Record = {}): IncomingMessage & PassThrough { + const req = new PassThrough() as PassThrough & { headers: Record }; + req.headers = headers; + return req as unknown as IncomingMessage & PassThrough; + } + + it("parses a valid JSON body under the cap", async () => { + const req = mockReq(); + const promise = readJsonBody(req, 1024); + req.end(JSON.stringify({ hello: "world" })); + + await expect(promise).resolves.toEqual({ hello: "world" }); + }); + + it("rejects a declared Content-Length over the cap without reading the body", async () => { + const req = mockReq({ "content-length": "5000" }); + const onData = vi.fn(); + req.on("data", onData); + + await expect(readJsonBody(req, 1024)).rejects.toThrow(/limit/); + expect(onData).not.toHaveBeenCalled(); // fast-path rejects before consuming + }); + + it("rejects a chunked body that streams past the cap (no Content-Length)", async () => { + const req = mockReq(); // no content-length → exercises the streaming guard + const promise = readJsonBody(req, 16); + req.write("x".repeat(10)); + req.write("x".repeat(10)); // total 20 > 16 + req.end(); + + await expect(promise).rejects.toThrow(/limit/); + }); + + it("rejects an empty body", async () => { + const req = mockReq(); + const promise = readJsonBody(req, 1024); + req.end(""); + + await expect(promise).rejects.toThrow("Request body is required"); + }); + + it("defaults the cap to MAX_BODY_BYTES (64 KB)", async () => { + const req = mockReq({ "content-length": String(MAX_BODY_BYTES + 1) }); + + await expect(readJsonBody(req)).rejects.toThrow(/limit/); + }); }); diff --git a/apps/scheduler/src/notify-routes.ts b/apps/scheduler/src/notify-routes.ts index 577478b64..b63d13dd9 100644 --- a/apps/scheduler/src/notify-routes.ts +++ b/apps/scheduler/src/notify-routes.ts @@ -4,6 +4,22 @@ import http from "node:http"; import type { HandlerServiceDocument } from "shared"; +/** + * Maximum accepted request body size for the scheduler's HTTP endpoints. + * Notify/register payloads are a few hundred bytes; 64 KB is a generous cap + * that protects this singleton control-plane process from unbounded buffering + * (and OOM) if a buggy caller streams a large body. + */ +export const MAX_BODY_BYTES = 64 * 1024; + +/** Thrown by readJsonBody when the request body exceeds MAX_BODY_BYTES. */ +class PayloadTooLargeError extends Error { + constructor(maxBytes: number) { + super(`Request body exceeds ${maxBytes}-byte limit`); + this.name = "PayloadTooLargeError"; + } +} + export interface NotifyHandler { onRunTerminal(requestId: string, runId: string): Promise; onHandlerComplete( @@ -27,8 +43,13 @@ interface HandlerCompleteRequest { status: "done" | "failed"; } -function sendJson(res: http.ServerResponse, statusCode: number, body: object): void { - res.writeHead(statusCode, { "Content-Type": "application/json" }); +function sendJson( + res: http.ServerResponse, + statusCode: number, + body: object, + extraHeaders?: http.OutgoingHttpHeaders, +): void { + res.writeHead(statusCode, { "Content-Type": "application/json", ...extraHeaders }); res.end(JSON.stringify(body)); } @@ -117,22 +138,84 @@ function parseHandlerRegisterRequest(body: unknown): HandlerServiceDocument | nu }; } -async function readJsonBody(req: http.IncomingMessage): Promise { - const chunks: Buffer[] = []; +export function readJsonBody( + req: http.IncomingMessage, + maxBytes: number = MAX_BODY_BYTES, +): Promise { + return new Promise((resolve, reject) => { + // Fast path: reject an oversized declared Content-Length before reading any + // body. Well-behaved clients (fetch/axios/http.request with a body) always + // send it, so this catches the common case without buffering a single byte. + const declaredLength = Number(req.headers["content-length"]); + if (Number.isFinite(declaredLength) && declaredLength > maxBytes) { + reject(new PayloadTooLargeError(maxBytes)); + return; + } - for await (const chunk of req) { - chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk); - } + const chunks: Buffer[] = []; + let total = 0; + let settled = false; - const rawBody = Buffer.concat(chunks).toString("utf-8").trim(); - if (rawBody.length === 0) { - throw new Error("Request body is required"); - } + const cleanup = (): void => { + req.removeListener("data", onData); + req.removeListener("end", onEnd); + req.removeListener("error", onError); + }; + + // Streaming guard: Content-Length may be absent (chunked) or lie, so also + // enforce the cap as bytes arrive and bail the moment it is exceeded. + const onData = (chunk: Buffer | string): void => { + if (settled) return; + const buf = typeof chunk === "string" ? Buffer.from(chunk) : chunk; + total += buf.length; + if (total > maxBytes) { + settled = true; + cleanup(); + reject(new PayloadTooLargeError(maxBytes)); + return; + } + chunks.push(buf); + }; - return JSON.parse(rawBody) as unknown; + const onEnd = (): void => { + if (settled) return; + settled = true; + cleanup(); + const rawBody = Buffer.concat(chunks).toString("utf-8").trim(); + if (rawBody.length === 0) { + reject(new Error("Request body is required")); + return; + } + try { + resolve(JSON.parse(rawBody) as unknown); + } catch (err) { + reject(err); + } + }; + + const onError = (err: Error): void => { + if (settled) return; + settled = true; + cleanup(); + reject(err); + }; + + req.on("data", onData); + req.on("end", onEnd); + req.on("error", onError); + }); } -export function createHttpServer(handler: NotifyHandler): http.Server { +export interface HttpServerOptions { + /** Max request body size in bytes. Defaults to MAX_BODY_BYTES (64 KB). */ + maxBodyBytes?: number; +} + +export function createHttpServer( + handler: NotifyHandler, + options: HttpServerOptions = {}, +): http.Server { + const maxBodyBytes = options.maxBodyBytes ?? MAX_BODY_BYTES; return http.createServer(async (req, res) => { const method = req.method ?? "GET"; const url = new URL(req.url ?? "/", "http://localhost"); @@ -144,7 +227,7 @@ export function createHttpServer(handler: NotifyHandler): http.Server { } if (method === "POST" && url.pathname === "/notify/run-terminal") { - const parsedBody = parseRunTerminalRequest(await readJsonBody(req)); + const parsedBody = parseRunTerminalRequest(await readJsonBody(req, maxBodyBytes)); if (!parsedBody) { sendJson(res, 400, { error: "requestId and runId are required" }); return; @@ -156,7 +239,7 @@ export function createHttpServer(handler: NotifyHandler): http.Server { } if (method === "POST" && url.pathname === "/notify/handler-complete") { - const parsedBody = parseHandlerCompleteRequest(await readJsonBody(req)); + const parsedBody = parseHandlerCompleteRequest(await readJsonBody(req, maxBodyBytes)); if (!parsedBody) { sendJson(res, 400, { error: "requestId, runId, handlerId, and status (done|failed) are required", @@ -175,7 +258,7 @@ export function createHttpServer(handler: NotifyHandler): http.Server { } if (method === "POST" && url.pathname === "/handlers/register") { - const parsedBody = parseHandlerRegisterRequest(await readJsonBody(req)); + const parsedBody = parseHandlerRegisterRequest(await readJsonBody(req, maxBodyBytes)); if (!parsedBody) { sendJson(res, 400, { error: @@ -189,6 +272,13 @@ export function createHttpServer(handler: NotifyHandler): http.Server { return; } } catch (error) { + // Body was not fully consumed — close the connection so leftover bytes + // can't corrupt the next request on a keep-alive socket. + if (error instanceof PayloadTooLargeError) { + sendJson(res, 413, { error: "Request body too large" }, { Connection: "close" }); + return; + } + const message = error instanceof Error ? error.message : "Internal server error"; const statusCode = message === "Request body is required" || error instanceof SyntaxError ? 400 : 500; diff --git a/docs/architecture/post-processing.md b/docs/architecture/post-processing.md index 7fd352e55..5bc1efbd5 100644 --- a/docs/architecture/post-processing.md +++ b/docs/architecture/post-processing.md @@ -16,7 +16,7 @@ Two paths trigger post-processing: 1. **Event-driven (primary):** Coder workers enqueue a post-processing message immediately when a run completes, currently setting the deprecated `run.postProcessorStatus: "queued"` compatibility field atomically in the same DB write while the system migrates to per-handler status. 2. **Scheduler backfill:** The `PostProcessorDispatcher` polls every 30 seconds for runs that have `status: "done"` but no post-processing marker set (or a stale handler version). During the migration window this may consult the deprecated flat fields; the long-term source of truth is `run.handlerStatus[handlerId]`. This catches runs that completed before the event-driven dispatch was deployed, or that need re-processing after a version bump. -3. **Scheduler notify & registration server:** The scheduler also exposes `GET /health`, `POST /notify/run-terminal`, `POST /notify/handler-complete`, and `POST /handlers/register` on a lightweight `node:http` server. Workers and post-process handlers use the notify endpoints to signal terminal states so the scheduler can re-evaluate which root or downstream handlers are ready to dispatch. The `/handlers/register` endpoint is the single writer to the `services` collection — see [Handler Registration](#handler-registration). +3. **Scheduler notify & registration server:** The scheduler also exposes `GET /health`, `POST /notify/run-terminal`, `POST /notify/handler-complete`, and `POST /handlers/register` on a lightweight `node:http` server. Workers and post-process handlers use the notify endpoints to signal terminal states so the scheduler can re-evaluate which root or downstream handlers are ready to dispatch. The `/handlers/register` endpoint is the single writer to the `services` collection — see [Handler Registration](#handler-registration). All POST endpoints cap the request body at 64 KB (`MAX_BODY_BYTES` in `notify-routes.ts`); oversized payloads are rejected with `413 Payload Too Large` and `Connection: close` before the body is fully buffered, guarding the singleton scheduler against unbounded-memory requests. ## ATIF Generation From 726e0cd9b95f5148365edb265b9d7ab0897ae105 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Wed, 1 Jul 2026 16:02:48 -0700 Subject: [PATCH 035/210] fix(post-processing): let worker claim scheduler-queued runs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The enqueue-before-claim refactor made the scheduler write a best-effort handlerStatus..status="queued" marker in-process immediately after enqueueing. The worker's claim filter excluded "queued", so once that marker won the (near-certain) race against queue delivery, the worker dequeued its own message, matched nothing on the atomic claim, logged "no longer needed, discarding", and deleted the message — stranding the run at "queued" forever (the 30s backfill poll also excludes "queued", so nothing recovered it). This reintroduced the stuck-dispatch failure mode via a new path. Fix: remove "queued" from the worker claim exclusions so queued -> processing is a permitted transition. Idempotency is preserved: still exclude "processing" (another worker in-flight) and, for non-backfill handlers, "done"; autoBackfill "done" stays gated by the version check. Add a regression test asserting a run in the scheduler's "queued" state is claimable and driven to done, update the existing filter-shape assertion, and document that queued -> processing must be permitted. Verified end-to-end against the docker-compose stack: a synthetic status=done run dispatched via /notify/run-terminal now reaches handlerStatus.pp-atif.status=done + reportsTriggeredAt, with duplicate delivery still no-oping and the report trigger firing exactly once. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../post-processor/src/post-processor.test.ts | 56 ++++++++++++++++++- .../post-processor/src/post-processor.ts | 14 ++++- docs/architecture/post-processing.md | 2 +- 3 files changed, 68 insertions(+), 4 deletions(-) diff --git a/apps/workers/post-processor/src/post-processor.test.ts b/apps/workers/post-processor/src/post-processor.test.ts index e33cccbd3..44f102fa9 100644 --- a/apps/workers/post-processor/src/post-processor.test.ts +++ b/apps/workers/post-processor/src/post-processor.test.ts @@ -122,7 +122,7 @@ describe("PostProcessor", () => { _id: "req-1", "run._id": "run-1", "run.status": "done", - "run.handlerStatus.pp-atif.status": { $nin: ["queued", "processing"] }, + "run.handlerStatus.pp-atif.status": { $nin: ["processing"] }, $or: [ { "run.handlerStatus.pp-atif.version": { $exists: false } }, { "run.handlerStatus.pp-atif.version": { $lt: 1 } }, @@ -181,4 +181,58 @@ describe("PostProcessor", () => { expect(notifyHandlerComplete).toHaveBeenCalledWith("req-1", "run-1", "pp-atif", "done"); expect(safeDeleteMessage).toHaveBeenCalledWith("message-1", "pop-1"); }); + + it("claims a run left in the scheduler's 'queued' state and drives it to done", async () => { + // Regression: the scheduler writes a best-effort "queued" marker right after + // enqueue-before-claim, so a dequeued message almost always sees status + // "queued". The worker MUST be able to claim it (queued -> processing). + // Previously "queued" was in the claim exclusion list, so the worker + // discarded its own message and stranded the run at "queued" forever. + const { processor, collection, safeDeleteMessage, notifyHandlerComplete } = makeProcessor(); + processor.registerHandler(handler); + + const doc = makeDoc({ + handlerStatus: { + "pp-atif": { status: "queued", updatedAt: new Date() }, + }, + }); + const heartbeat = makeHeartbeat(); + const payload: PostProcessorMessage = { type: "atif", requestId: "req-1", runId: "run-1" }; + + collection.findOneAndUpdate.mockResolvedValue({ _id: "req-1" }); + collection.updateOne.mockResolvedValue({ matchedCount: 1 }); + + await (processor as any).handleRequest(doc, makeMessage(), heartbeat, log, payload); + + // The claim filter must NOT exclude "queued" — only "processing". + expect(collection.findOneAndUpdate).toHaveBeenCalledWith( + expect.objectContaining({ + _id: "req-1", + "run._id": "run-1", + "run.status": "done", + "run.handlerStatus.pp-atif.status": { $nin: ["processing"] }, + }), + expect.any(Object), + expect.objectContaining({ returnDocument: "after" }), + ); + expect(handler.process).toHaveBeenCalledWith( + payload, + expect.objectContaining({ collection, log }), + ); + expect(collection.updateOne).toHaveBeenCalledWith( + { + _id: "req-1", + "run._id": "run-1", + "run.handlerStatus.pp-atif.status": "processing", + }, + { + $set: expect.objectContaining({ + "run.handlerStatus.pp-atif.status": "done", + "run.handlerStatus.pp-atif.version": 1, + }), + }, + ); + expect(notifyHandlerComplete).toHaveBeenCalledWith("req-1", "run-1", "pp-atif", "done"); + expect(safeDeleteMessage).toHaveBeenCalledWith("message-1", "pop-1"); + }); }); diff --git a/apps/workers/post-processor/src/post-processor.ts b/apps/workers/post-processor/src/post-processor.ts index db2a46c9f..d8dcb2a66 100644 --- a/apps/workers/post-processor/src/post-processor.ts +++ b/apps/workers/post-processor/src/post-processor.ts @@ -48,9 +48,19 @@ export class PostProcessor extends BaseQueueProcessor { handlerId: string, handler: PostProcessHandler, ): Record { + // "queued" is deliberately NOT excluded: the scheduler writes a best-effort + // "queued" marker immediately after enqueueing (enqueue-before-claim), so by + // the time this message is dequeued the status is almost always "queued". + // The worker is exactly what transitions queued -> processing, so it must be + // able to claim a "queued" attempt. Excluding it would let the worker discard + // its own message and strand the run at "queued" (the scheduler poll also + // excludes "queued", so nothing would ever retry it). We only exclude + // "processing" (another worker is mid-flight) and — for non-backfill handlers + // — "done" (already complete). For autoBackfill, "done" is gated by the + // version check below instead, so a version bump can re-process it. const statusExclusions = handler.autoBackfill - ? ["queued", "processing"] - : ["queued", "processing", "done"]; + ? ["processing"] + : ["processing", "done"]; const filter: Record = { _id: requestId, diff --git a/docs/architecture/post-processing.md b/docs/architecture/post-processing.md index 5bc1efbd5..1370e5b7c 100644 --- a/docs/architecture/post-processing.md +++ b/docs/architecture/post-processing.md @@ -98,7 +98,7 @@ To keep this safe, idempotency is enforced at the **post-processor worker entryp 1. The scheduler decides whether work is needed from `run.handlerStatus[handlerId]` + handler metadata (`version`, `autoBackfill`). 2. The worker re-checks that same eligibility when a message is dequeued, scoped to the specific `runId`. -3. The worker atomically claims the handler by transitioning its status to `processing`. +3. The worker atomically claims the handler by transitioning its status to `processing`. The claim filter accepts both the *absent* state and the `queued` marker as valid source states — it only excludes `processing` (another worker is mid-flight) and, for non-backfill handlers, `done` (already complete; for `autoBackfill` handlers a stale `done` is re-claimable via the version gate). Because the scheduler writes the best-effort `queued` marker in-process immediately after enqueueing (enqueue-before-claim), a dequeued message almost always sees `queued`; excluding `queued` from the claim filter would make the worker discard its own message and strand the run at `queued` forever (the 30s backfill poll also skips `queued`), so `queued → processing` **must** be a permitted worker transition. 4. If the message is stale, duplicated, or the handler is already current, the worker deletes the queue message and no-ops. This means: From 0531a0ad6440f41058c514b2f1fac7af6ea4bad5 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Thu, 9 Jul 2026 18:47:31 -0700 Subject: [PATCH 036/210] chore(db-migrations): renumber handler-DAG migrations to 025-027 `main` independently claimed 018/019/020 (backfill-criteria-gates, backfill-task-prompt-type, create-codebase-indexes) after this branch had assigned those numbers to the handler-DAG migrations, producing duplicate prefixes once main was merged in. Renumber the three handler migrations to sit after main's highest (024) so prefixes are unique and monotonic: 018-migrate-services-to-handler-dag -> 025-migrate-services-to-handler-dag 019-add-handler-status-index -> 026-add-handler-status-index 020-backfill-handler-status -> 027-backfill-handler-status Class names are unchanged (mongo-migrate-ts tracks applied migrations by className), and these migrations have not been applied to any shared environment (int/prod migrations come from main only), so the renumber is safe. Also updates required-migrations.ts, the internal [NNN] log prefixes, and the db-migrations doc table. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/architecture/db-migrations.md | 6 +++--- ...r-dag.ts => 025-migrate-services-to-handler-dag.ts} | 6 +++--- ...status-index.ts => 026-add-handler-status-index.ts} | 10 +++++----- ...andler-status.ts => 027-backfill-handler-status.ts} | 0 packages/db-migrations/src/required-migrations.ts | 6 +++--- 5 files changed, 14 insertions(+), 14 deletions(-) rename packages/db-migrations/src/migrations/{018-migrate-services-to-handler-dag.ts => 025-migrate-services-to-handler-dag.ts} (86%) rename packages/db-migrations/src/migrations/{019-add-handler-status-index.ts => 026-add-handler-status-index.ts} (82%) rename packages/db-migrations/src/migrations/{020-backfill-handler-status.ts => 027-backfill-handler-status.ts} (100%) diff --git a/docs/architecture/db-migrations.md b/docs/architecture/db-migrations.md index f69880a10..2e5b28da0 100644 --- a/docs/architecture/db-migrations.md +++ b/docs/architecture/db-migrations.md @@ -102,9 +102,9 @@ When you run a command: | `007-rename-exhausted-to-finished` | Renames outcome `exhausted` → `finished` | | `008-backfill-ai-call-count` | Downloads HARs from blob storage to count AI completion calls per turn | | `009-add-requests-filter-indexes` | Adds indexes on `taskPromptId`, `status`, `outcome`, `workerType`, `deletedAt` for server-side filtering/grouping | -| `018-migrate-services-to-handler-dag` | Replaces the legacy single `post-processor` service row with per-handler service registrations and dependencies | -| `019-add-handler-status-index` | Adds a handler-specific dispatch index for `pp-atif` polling | -| `020-backfill-handler-status` | Backfills `run.handlerStatus.pp-atif` from deprecated `run.postProcessorStatus` / `run.postProcessorVersion` fields | +| `025-migrate-services-to-handler-dag` | Replaces the legacy single `post-processor` service row with per-handler service registrations and dependencies | +| `026-add-handler-status-index` | Adds a handler-specific dispatch index for `pp-atif` polling | +| `027-backfill-handler-status` | Backfills `run.handlerStatus.pp-atif` from deprecated `run.postProcessorStatus` / `run.postProcessorVersion` fields | ## CI/CD diff --git a/packages/db-migrations/src/migrations/018-migrate-services-to-handler-dag.ts b/packages/db-migrations/src/migrations/025-migrate-services-to-handler-dag.ts similarity index 86% rename from packages/db-migrations/src/migrations/018-migrate-services-to-handler-dag.ts rename to packages/db-migrations/src/migrations/025-migrate-services-to-handler-dag.ts index 6d2aa2c94..e2c683b56 100644 --- a/packages/db-migrations/src/migrations/018-migrate-services-to-handler-dag.ts +++ b/packages/db-migrations/src/migrations/025-migrate-services-to-handler-dag.ts @@ -5,7 +5,7 @@ import type { Db } from "mongodb"; import type { MigrationInterface } from "mongo-migrate-ts"; /** - * Migration 018: Remove the legacy "post-processor" service entry. + * Migration 025: Remove the legacy "post-processor" service entry. * * Handler service registration (e.g. pp-atif) is now owned * by each worker's handler.yaml + the generic register-handler script, @@ -18,7 +18,7 @@ export class MigrateServicesToHandlerDag implements MigrationInterface { async up(db: Db): Promise { const services = db.collection("services"); await services.deleteOne({ _id: "post-processor" } as any); - console.log("[018] Deleted legacy post-processor service entry (handler registration now owned by workers)"); + console.log("[025] Deleted legacy post-processor service entry (handler registration now owned by workers)"); } async down(db: Db): Promise { @@ -37,6 +37,6 @@ export class MigrateServicesToHandlerDag implements MigrationInterface { }, { upsert: true }, ); - console.log("[018-down] Restored legacy post-processor service entry"); + console.log("[025-down] Restored legacy post-processor service entry"); } } diff --git a/packages/db-migrations/src/migrations/019-add-handler-status-index.ts b/packages/db-migrations/src/migrations/026-add-handler-status-index.ts similarity index 82% rename from packages/db-migrations/src/migrations/019-add-handler-status-index.ts rename to packages/db-migrations/src/migrations/026-add-handler-status-index.ts index ee6e35f95..cf514668e 100644 --- a/packages/db-migrations/src/migrations/019-add-handler-status-index.ts +++ b/packages/db-migrations/src/migrations/026-add-handler-status-index.ts @@ -25,12 +25,12 @@ export class AddHandlerStatusIndex implements MigrationInterface { const exists = await requests.indexExists(createdName); console.log( exists - ? `[019] Created ${index.name} index on requests` - : `[019] ${index.name} was requested but is not visible in getIndexes()`, + ? `[026] Created ${index.name} index on requests` + : `[026] ${index.name} was requested but is not visible in getIndexes()`, ); } catch (err: unknown) { const message = err instanceof Error ? err.message : String(err); - console.log(`[019] ${index.name} already exists or couldn't be created: ${message}`); + console.log(`[026] ${index.name} already exists or couldn't be created: ${message}`); } } } @@ -41,14 +41,14 @@ export class AddHandlerStatusIndex implements MigrationInterface { for (const index of HANDLER_STATUS_INDEXES) { try { await requests.dropIndex(index.name); - console.log(`[019-down] Dropped ${index.name} index`); + console.log(`[026-down] Dropped ${index.name} index`); } catch (err: unknown) { const codeName = typeof err === "object" && err !== null && "codeName" in err ? String((err as { codeName?: unknown }).codeName) : undefined; if (codeName !== "IndexNotFound") { const message = err instanceof Error ? err.message : String(err); - console.log(`[019-down] ${index.name} not found: ${message}`); + console.log(`[026-down] ${index.name} not found: ${message}`); } } } diff --git a/packages/db-migrations/src/migrations/020-backfill-handler-status.ts b/packages/db-migrations/src/migrations/027-backfill-handler-status.ts similarity index 100% rename from packages/db-migrations/src/migrations/020-backfill-handler-status.ts rename to packages/db-migrations/src/migrations/027-backfill-handler-status.ts diff --git a/packages/db-migrations/src/required-migrations.ts b/packages/db-migrations/src/required-migrations.ts index 41f0897ba..8d8484068 100644 --- a/packages/db-migrations/src/required-migrations.ts +++ b/packages/db-migrations/src/required-migrations.ts @@ -31,13 +31,13 @@ export const REQUIRED_MIGRATIONS: readonly string[] = [ "016-fix-scheduler-sort-index.ts", "017-add-post-processor-dispatch-index.ts", "018-backfill-criteria-gates.ts", - "018-migrate-services-to-handler-dag.ts", - "019-add-handler-status-index.ts", "019-backfill-task-prompt-type.ts", - "020-backfill-handler-status.ts", "020-create-codebase-indexes.ts", "021-add-runs-filter-indexes.ts", "022-add-runs-sort-indexes.ts", "023-add-runs-search-task-index.ts", "024-add-criteria-sort-index.ts", + "025-migrate-services-to-handler-dag.ts", + "026-add-handler-status-index.ts", + "027-backfill-handler-status.ts", ]; From 17e8c508d6182b2bb74fe7e74a5f2571ed723171 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Sun, 11 Oct 2026 18:02:51 +0200 Subject: [PATCH 037/210] feat(portal): add Copilot SDK AI backend Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: ff08bace-4f82-42b3-9451-4063717e348f --- ENV_VARIABLES.md | 148 +++-- NOTICE | 30 ++ apps/api/Dockerfile | 5 + apps/api/package.json | 4 +- apps/api/src/copilot-client-pool.test.ts | 256 +++++++++ apps/api/src/copilot-client-pool.ts | 508 ++++++++++++++++++ apps/api/src/index.ts | 2 + apps/api/src/llm-token.test.ts | 173 ++++++ apps/api/src/llm-token.ts | 248 +++++++-- apps/api/src/llm.test.ts | 22 +- apps/api/src/llm.ts | 61 +-- .../src/portal-ai-copilot.integration.test.ts | 175 ++++++ apps/api/src/portal-ai-copy.test.ts | 16 + apps/api/src/portal-ai-copy.ts | 5 + apps/api/src/prompt-feature-llm.ts | 67 +-- apps/api/src/prompt-request-transport.test.ts | 27 +- apps/api/src/routes/criteria.ts | 3 +- apps/api/src/routes/prompt-features.ts | 5 +- apps/api/src/routes/task-prompts.ts | 5 +- apps/api/src/task-prompt-llm.test.ts | 37 +- apps/api/src/task-prompt-llm.ts | 38 +- .../components/CriteriaWizardStep2.test.tsx | 13 +- .../src/components/CriteriaWizardStep2.tsx | 3 +- .../src/components/PromptFeatureWizard.tsx | 3 +- apps/portal/src/lib/portal-ai-copy.ts | 5 + apps/portal/src/pages/CreateToken.test.ts | 31 +- apps/portal/src/pages/CreateToken.tsx | 16 +- apps/portal/src/types.ts | 4 +- docs/architecture/token-manager.md | 111 ++-- docs/responsible-ai-faq.md | 7 +- pnpm-lock.yaml | 260 ++++----- 31 files changed, 1858 insertions(+), 430 deletions(-) create mode 100644 apps/api/src/copilot-client-pool.test.ts create mode 100644 apps/api/src/copilot-client-pool.ts create mode 100644 apps/api/src/llm-token.test.ts create mode 100644 apps/api/src/portal-ai-copilot.integration.test.ts create mode 100644 apps/api/src/portal-ai-copy.test.ts create mode 100644 apps/api/src/portal-ai-copy.ts create mode 100644 apps/portal/src/lib/portal-ai-copy.ts diff --git a/ENV_VARIABLES.md b/ENV_VARIABLES.md index bc66a4316..ebdaee4e8 100644 --- a/ENV_VARIABLES.md +++ b/ENV_VARIABLES.md @@ -56,40 +56,115 @@ queue. Local Compose sets it to the checked-in development manifest version. ## LLM Configuration (Portal AI Features) The portal's AI features — criteria prompt generation, prompt-feature -extraction/generation, and task-prompt generation/variation — all call an -OpenAI-style chat-completions endpoint through the -[`@azure-rest/ai-inference`](https://www.npmjs.com/package/@azure-rest/ai-inference) -SDK. Two backends are supported, resolved in `acquireInferenceClient` -([`apps/api/src/llm-token.ts`](apps/api/src/llm-token.ts)) using the -following priority order. The **first source that returns a credential -wins**; later sources are not consulted. +extraction/generation, and task-prompt generation/variation — support Azure AI +Foundry, the GitHub Copilot SDK, and a legacy GitHub Models fallback. The +**first source that returns a credential wins**; later sources are not +consulted. | # | Source | Trigger | `via` log tag | |---|--------|---------|---------------| | 1 | Azure AI Foundry via env vars | `AZURE_AI_INFERENCE_ENDPOINT` + `AZURE_AI_INFERENCE_API_KEY` both set | `azure-ai-foundry-env` | | 2 | Azure AI Foundry via Token Manager | At least one `azure-ai-foundry` key registered at the Portal `/secrets/keys/new` (recommended for integration / prod — credentials live in Key Vault, the API round-robins across valid keys) | `azure-ai-foundry-token-manager` | -| 3 | GitHub Models via env var | `GITHUB_MODELS_API_KEY` set | `github-models-env` | -| 4 | GitHub Models via Token Manager | A `github-models` key registered at `/secrets/keys/new` | `github-models-token-manager` | -| 5 | Bare GitHub token fallback | `GITHUB_TOKEN` set | `github-token` | +| 3 | GitHub Copilot SDK | `GITHUB_TOKEN` is set, or a classic PAT/OAuth token with the validated `copilot-sdk` capability is registered at `/secrets/keys/new` | `copilot-sdk-env` or `copilot-sdk-token-manager` | +| 4 | GitHub Models legacy fallback | `GITHUB_MODELS_API_KEY`, a registered `github-models` key, or the legacy `GITHUB_TOKEN` path | `github-models-*` | **Two important properties of this chain:** -- **Foundry beats GitHub Models, and env vars beat the Token Manager - within each backend.** Having both a Foundry env var and a registered - `github-models` key means every call goes to Foundry; the GitHub - Models key is dormant. +- **Foundry beats Copilot SDK, which beats legacy GitHub Models.** Environment + Foundry credentials override registered Foundry keys. A classic PAT or OAuth + token that validates with `copilot-sdk` enables Portal AI without requiring + GitHub Models access. - **There is no automatic failover at request time.** The chain only steps down when the predecessor returns *nothing* (env var unset, no key registered). It does **not** step down when the predecessor - returns a credential that then 4xx/5xx's on the actual chat-completion - call. This is intentional — silent fallback would mask misconfiguration - (e.g. a wrong Foundry deployment name) and hide the real error from - the user. + returns a credential that then fails authentication, times out, is rate + limited, or fails inference. This is intentional — silent fallback would + mask misconfiguration and hide the real provider error. If no source returns a credential, the portal's AI buttons return HTTP -`503` with a single actionable error message (`LLM not configured: no -inference backend available. Please register a new secret key for GitHub -Model or Azure Foundry.`), and the rest of the API works unchanged. +`503` with actionable guidance to register Foundry or a classic PAT/OAuth +token with Copilot SDK capability. GitHub Models is identified as a legacy +fallback, and the rest of the API works unchanged. + +### Portal AI Copilot SDK isolation and limits + +The Copilot SDK provider uses a bounded client pool. Each Portal AI operation +waits only for the configured pool-acquisition timeout and then runs under a +separate response timeout. Each request creates a one-shot SDK session and +destroys it in `finally`, including after errors and timeouts, before the client +returns to the pool. + +Sessions are created with an empty tool set and receive no MCP servers, skills, +or repository/workspace context. The Copilot CLI child process receives a +sanitized environment with only the runtime and authentication variables it +needs; the API service's unrelated credentials are not forwarded. Sessions are +never reused across Portal AI requests. + +The Copilot SDK adapter preserves the Portal operation's system prompt and user +prompt. Its model resolves independently from the REST default, in this order: +an explicit request override, `PORTAL_COPILOT_MODEL`, `LLM_MODEL`, then automatic +selection from the models available to the authenticated Copilot account. The +automatic preference order is `gpt-5.4-mini`, `gpt-5.4`, `gpt-5.1`, +`gpt-5-mini`, then the first model returned by Copilot. The SDK session API does +not expose the REST chat-completions `temperature` or maximum-token controls, so +those two settings apply only to the Foundry and legacy GitHub Models REST +providers. + +### PORTAL_COPILOT_MODEL +**Default:** automatic model discovery +**Type:** string + +Optional Portal AI model override for the Copilot SDK provider. Resolution is: +explicit request override → `PORTAL_COPILOT_MODEL` → `LLM_MODEL` → automatic +available-model preference (`gpt-5.4-mini`, `gpt-5.4`, `gpt-5.1`, +`gpt-5-mini`, then the first listed model). Do not assume the REST default +`gpt-4.1` is available to the Copilot account. + +### PORTAL_COPILOT_POOL_SIZE +**Default:** `2` +**Type:** positive integer + +Maximum number of Copilot SDK clients that can serve Portal AI requests +concurrently. Additional requests wait for a pooled client until +`PORTAL_COPILOT_ACQUIRE_TIMEOUT_MS` expires. + +### PORTAL_COPILOT_ACQUIRE_TIMEOUT_MS +**Default:** `30000` (30 seconds) +**Type:** positive integer (milliseconds) + +Maximum time a Portal AI request waits for an available Copilot SDK client. +Expiration fails the request; it does not trigger the GitHub Models fallback. + +### PORTAL_COPILOT_STARTUP_TIMEOUT_MS +**Default:** `30000` (30 seconds) +**Type:** positive integer (milliseconds) + +Maximum time allowed to start and ping a pooled Copilot CLI runtime. A runtime +that cannot become ready in time is destroyed and is not added to the pool. + +### PORTAL_COPILOT_REQUEST_TIMEOUT_MS +**Default:** `300000` (5 minutes) +**Type:** positive integer (milliseconds) + +Maximum time for the one-shot Copilot SDK session to produce a response. +Expiration destroys the session, returns the client to the pool, and fails the +request without runtime provider failover. + +### PORTAL_COPILOT_SHUTDOWN_TIMEOUT_MS +**Default:** `10000` (10 seconds) +**Type:** positive integer (milliseconds) + +Maximum graceful shutdown time for an individual pooled Copilot CLI runtime and +for draining the pool during API shutdown. Scope force-stops runtimes that do +not stop within this limit. + +### PORTAL_COPILOT_IDLE_TIMEOUT_MS +**Default:** `60000` (1 minute) +**Type:** positive integer (milliseconds) + +How long an unused Copilot SDK client remains in the zero-minimum pool before +it is reaped. The pool recreates clients on demand up to +`PORTAL_COPILOT_POOL_SIZE`. Every successful acquisition also logs a single line so operators can verify which provider served a given AI call: @@ -156,29 +231,36 @@ API key for the Foundry endpoint. ExternalSecret (Key Vault key `azure-ai-inference-api-key`). ### GITHUB_MODELS_API_KEY -**Optional (used as fallback when Foundry is not configured)** +**Optional (legacy fallback after Foundry and Copilot SDK)** **Type:** string GitHub personal access token (with the `models` read permission) used to authenticate with GitHub Models (`https://models.inference.ai.azure.com`). -Useful for local dev where no Foundry endpoint is available. Goes in `.env` +Retained for compatibility where neither Foundry nor a Copilot SDK credential +is available. New deployments should prefer Foundry or register a classic PAT +or OAuth token with Copilot access. Goes in `.env` (or `.env.base`) since it is read via Compose variable substitution, not the api service's `env_file`. -> **Note:** This is separate from `GITHUB_TOKEN`, which is used by the Judge -> and worker services for Copilot SDK / ACP access and does **not** need the -> `models` permission. If `GITHUB_MODELS_API_KEY` is unset the API also -> accepts `GITHUB_TOKEN` (or `TOKEN_MANAGER_URL` with a registered -> `github-models` token) as a fallback. +> **Note:** A classic PAT or OAuth token with the `copilot-sdk` capability can +> enable Portal AI directly and does not need the `models` permission. +> `GITHUB_MODELS_API_KEY`, registered `github-models` tokens, and the bare +> `GITHUB_TOKEN` path are legacy compatibility fallbacks. ### LLM_MODEL -**Default:** `gpt-4.1` (applied inside the API when unset) +**Default:** `gpt-4.1` for REST inference; automatic discovery for Copilot SDK **Type:** string -Model name / deployment name used by both backends. For Foundry, this must -match the deployment name on the Foundry resource. Examples: `gpt-4.1`, -`gpt-4o`, `gpt-4.1-mini`, `gpt-5.4-mini`. Put in `.env.local` (see note above). -The API discovers supported token-limit and sampling parameters from structured +Fallback model/deployment override shared by Portal AI providers. For Foundry, +this must match the deployment name on the Foundry resource. Foundry and legacy +GitHub Models default to `gpt-4.1` when this is unset. Copilot SDK considers +`LLM_MODEL` only after an explicit request model and `PORTAL_COPILOT_MODEL`; when +all three are unset it discovers an available Copilot model instead of assuming +`gpt-4.1`. + +REST examples include `gpt-4.1`, `gpt-4o`, `gpt-4.1-mini`, and +`gpt-5.4-mini`. Put this setting in `.env.local` (see note above). The REST +adapter discovers supported token-limit and sampling parameters from structured inference errors at runtime. Learned compatibility is cached in each API process by endpoint and deployment name. It is relearned after a process restart or when Azure rejects a previously accepted request shape. diff --git a/NOTICE b/NOTICE index 3773e8ed3..ca6d06ae0 100644 --- a/NOTICE +++ b/NOTICE @@ -10365,6 +10365,36 @@ SOFTWARE. ----------- +The following npm package may be included in this product: + + - tarn@3.0.2 + +This package contains the following license: + +The MIT License (MIT) + +Copyright (c) 2015 Vincit Oy + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +----------- + The following npm package may be included in this product: - ioredis@5.9.2 diff --git a/apps/api/Dockerfile b/apps/api/Dockerfile index 874efc590..39422fd4f 100644 --- a/apps/api/Dockerfile +++ b/apps/api/Dockerfile @@ -1,5 +1,8 @@ FROM node:22.22.0-slim AS builder +# The Copilot SDK spawns its bundled CLI runtime, which uses the OS CA store. +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/* + ARG NPM_CONFIG_REGISTRY=https://registry.npmjs.org/ ENV npm_config_registry=${NPM_CONFIG_REGISTRY} \ COREPACK_NPM_REGISTRY=${NPM_CONFIG_REGISTRY} @@ -46,6 +49,8 @@ CMD ["/app/scripts/dev-entrypoint.sh"] # --- Production stage --- FROM node:22.22.0-slim +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/* + ARG NPM_CONFIG_REGISTRY=https://registry.npmjs.org/ ENV npm_config_registry=${NPM_CONFIG_REGISTRY} \ COREPACK_NPM_REGISTRY=${NPM_CONFIG_REGISTRY} diff --git a/apps/api/package.json b/apps/api/package.json index 172be797d..714ad4644 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -18,6 +18,7 @@ "@azure/keyvault-secrets": "^4.8.0", "@azure/storage-blob": "^12.26.0", "@azure/storage-queue": "^12.24.0", + "@github/copilot-sdk": "1.0.1", "cors": "^2.8.5", "db-migrations": "workspace:*", "dotenv": "^16.4.5", @@ -27,9 +28,10 @@ "multer": "^2.2.0", "openapi3-ts": "^4.5.0", "shared": "workspace:*", - "telemetry": "workspace:*", "swagger-ui-express": "^5.0.1", "tar-stream": "^3.1.7", + "tarn": "3.0.2", + "telemetry": "workspace:*", "uuid": "^11.1.1", "yaml": "^2.8.3", "zod": "^4.3.6" diff --git a/apps/api/src/copilot-client-pool.test.ts b/apps/api/src/copilot-client-pool.test.ts new file mode 100644 index 000000000..5a557757f --- /dev/null +++ b/apps/api/src/copilot-client-pool.test.ts @@ -0,0 +1,256 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +interface MockClient { + start: ReturnType; + ping: ReturnType; + listModels: ReturnType; + createSession: ReturnType; + deleteSession: ReturnType; + stop: ReturnType; + forceStop: ReturnType; +} + +const mocks = vi.hoisted(() => ({ + clientOptions: [] as Array>, + clients: [] as MockClient[], + mkdir: vi.fn(), + mkdtemp: vi.fn(), + rm: vi.fn(), + ping: vi.fn(), + sessionFactory: vi.fn(), +})); + +interface MockSession { + sessionId: string; + on: ReturnType; + sendAndWait: ReturnType; + abort: ReturnType; + disconnect: ReturnType; +} + +vi.mock("@github/copilot-sdk", () => ({ + CopilotClient: class implements MockClient { + start = vi.fn(async () => undefined); + ping = vi.fn((message: string) => mocks.ping(message)); + listModels = vi.fn(async () => [ + { id: "test-default-model", name: "Test Default", capabilities: {} }, + ]); + createSession = vi.fn((options: Record) => + mocks.sessionFactory(options), + ); + deleteSession = vi.fn(async () => undefined); + stop = vi.fn(async () => []); + forceStop = vi.fn(async () => undefined); + + constructor(options: Record) { + mocks.clientOptions.push(options); + mocks.clients.push(this); + } + }, +})); + +vi.mock("node:fs/promises", () => ({ + mkdir: mocks.mkdir, + mkdtemp: mocks.mkdtemp, + rm: mocks.rm, +})); + +vi.mock("node:os", () => ({ + tmpdir: () => "/scope-tests", +})); + +vi.mock("shared", () => ({ + TokenManagerClient: class {}, + withRetry: (operation: () => Promise) => operation(), +})); + +import { PortalCopilotClientPool } from "./copilot-client-pool.js"; + +const pools: PortalCopilotClientPool[] = []; +let sessionNumber = 0; + +function makeSession(overrides: Partial = {}): MockSession { + const sessionId = `session-${++sessionNumber}`; + return { + sessionId, + on: vi.fn(() => vi.fn()), + sendAndWait: vi.fn(async () => ({ + data: { content: `response-${sessionId}` }, + })), + abort: vi.fn(async () => undefined), + disconnect: vi.fn(async () => undefined), + ...overrides, + }; +} + +function makePool(): PortalCopilotClientPool { + const tokenClient = { + acquireToken: vi.fn(async () => "copilot-token"), + }; + const pool = new PortalCopilotClientPool( + tokenClient as unknown as ConstructorParameters[0], + ); + pools.push(pool); + return pool; +} + +async function complete(pool: PortalCopilotClientPool, suffix = ""): Promise { + return pool.complete({ + systemPrompt: `system${suffix}`, + userPrompt: `user${suffix}`, + model: "test-model", + }); +} + +beforeEach(() => { + vi.clearAllMocks(); + mocks.clientOptions.length = 0; + mocks.clients.length = 0; + pools.length = 0; + sessionNumber = 0; + vi.stubEnv("PORTAL_COPILOT_POOL_SIZE", "1"); + vi.stubEnv("PATH", "/usr/bin"); + vi.stubEnv("LANG", "en_US.UTF-8"); + vi.stubEnv("HOME", "/sensitive/home"); + vi.stubEnv("GITHUB_TOKEN", "must-not-leak"); + mocks.mkdtemp.mockResolvedValue("/scope-tests/runtime"); + mocks.mkdir.mockResolvedValue(undefined); + mocks.rm.mockResolvedValue(undefined); + mocks.ping.mockResolvedValue({ message: "pong" }); + mocks.sessionFactory.mockImplementation(() => makeSession()); + vi.spyOn(console, "log").mockImplementation(() => undefined); + vi.spyOn(console, "warn").mockImplementation(() => undefined); +}); + +afterEach(async () => { + await Promise.allSettled(pools.map((pool) => pool.shutdown())); + vi.restoreAllMocks(); + vi.unstubAllEnvs(); +}); + +describe("PortalCopilotClientPool", () => { + it("starts an empty, sanitized runtime and creates a tool-free denied-permission session", async () => { + const pool = makePool(); + + await expect(complete(pool)).resolves.toBe("response-session-1"); + + expect(mocks.clientOptions).toHaveLength(1); + expect(mocks.clientOptions[0]).toMatchObject({ + gitHubToken: "copilot-token", + useLoggedInUser: false, + mode: "empty", + enableRemoteSessions: false, + env: { + PATH: "/usr/bin", + LANG: "en_US.UTF-8", + }, + }); + expect(mocks.clientOptions[0].env).not.toHaveProperty("HOME"); + expect(mocks.clientOptions[0].env).not.toHaveProperty("GITHUB_TOKEN"); + + const sessionOptions = mocks.clients[0].createSession.mock.calls[0][0]; + expect(sessionOptions).toMatchObject({ + model: "test-model", + availableTools: [], + excludedTools: ["builtin:*", "mcp:*"], + tools: [], + mcpServers: {}, + skillDirectories: [], + customAgents: [], + enableConfigDiscovery: false, + skipCustomInstructions: true, + requestExtensions: false, + enableMcpApps: false, + }); + expect( + (sessionOptions.onPermissionRequest as () => unknown)(), + ).toEqual({ + kind: "reject", + feedback: "Portal AI completions do not permit tool execution.", + }); + + const session = await mocks.clients[0].createSession.mock.results[0].value; + expect(session.disconnect).toHaveBeenCalledOnce(); + expect(mocks.clients[0].deleteSession).toHaveBeenCalledWith(session.sessionId); + }); + + it("does not release a resource for bounded reuse until its health ping succeeds", async () => { + let releaseHealthPing: (() => void) | undefined; + const healthGate = new Promise((resolve) => { + releaseHealthPing = resolve; + }); + mocks.ping.mockImplementation(async (message: string) => { + if (message === "scope-portal-ai-health") await healthGate; + return { message: "pong" }; + }); + const pool = makePool(); + + const first = complete(pool, "-first"); + await vi.waitFor(() => { + expect(mocks.ping).toHaveBeenCalledWith("scope-portal-ai-health"); + }); + + const second = complete(pool, "-second"); + await Promise.resolve(); + expect(mocks.clients).toHaveLength(1); + expect(mocks.clients[0].createSession).toHaveBeenCalledTimes(1); + + releaseHealthPing?.(); + await expect(Promise.all([first, second])).resolves.toEqual([ + "response-session-1", + "response-session-2", + ]); + expect(mocks.clients).toHaveLength(1); + expect(mocks.clients[0].createSession).toHaveBeenCalledTimes(2); + }); + + it("invalidates the pooled client when session cleanup fails", async () => { + const failedCleanupSession = makeSession({ + disconnect: vi.fn(async () => { + throw new Error("disconnect failed"); + }), + }); + mocks.sessionFactory + .mockResolvedValueOnce(failedCleanupSession) + .mockImplementation(() => makeSession()); + const pool = makePool(); + + await expect(complete(pool, "-first")).resolves.toBe( + `response-${failedCleanupSession.sessionId}`, + ); + await expect(complete(pool, "-second")).resolves.toBe("response-session-2"); + + expect(mocks.clients).toHaveLength(2); + expect(mocks.clients[0].forceStop).toHaveBeenCalledOnce(); + expect(mocks.clients[1].createSession).toHaveBeenCalledOnce(); + }); + + it("drains resources on shutdown and rejects subsequent completions", async () => { + const pool = makePool(); + await complete(pool); + + await pool.shutdown(); + + expect(mocks.clients[0].stop).toHaveBeenCalledOnce(); + expect(mocks.rm).toHaveBeenCalledWith( + "/scope-tests/runtime", + { recursive: true, force: true }, + ); + expect(pool.stats()).toEqual({ + used: 0, + free: 0, + pendingAcquires: 0, + pendingCreates: 0, + resources: 0, + resourcesCreated: 1, + sessionsCreated: 1, + sessionsDeleted: 1, + }); + await expect(complete(pool)).rejects.toThrow( + "Copilot SDK pool is shutting down", + ); + }); +}); diff --git a/apps/api/src/copilot-client-pool.ts b/apps/api/src/copilot-client-pool.ts new file mode 100644 index 000000000..0734a81f6 --- /dev/null +++ b/apps/api/src/copilot-client-pool.ts @@ -0,0 +1,508 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { + CopilotClient, + type CopilotSession, + type PermissionHandler, +} from "@github/copilot-sdk"; +import { mkdtemp, mkdir, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { randomUUID } from "node:crypto"; +import { Pool } from "tarn"; +import { TokenManagerClient, withRetry } from "shared"; + +const DEFAULT_POOL_SIZE = 2; +const DEFAULT_ACQUIRE_TIMEOUT_MS = 30_000; +const DEFAULT_STARTUP_TIMEOUT_MS = 30_000; +const DEFAULT_REQUEST_TIMEOUT_MS = 300_000; +const DEFAULT_SHUTDOWN_TIMEOUT_MS = 10_000; +const DEFAULT_IDLE_TIMEOUT_MS = 60_000; + +interface CopilotPoolResource { + client: CopilotClient; + rootDirectory: string; + defaultModel: string; + healthy: boolean; + destroyed: boolean; +} + +export interface CopilotPoolStats { + used: number; + free: number; + pendingAcquires: number; + pendingCreates: number; + resources: number; + resourcesCreated: number; + sessionsCreated: number; + sessionsDeleted: number; +} + +export interface CopilotCompletionRequest { + systemPrompt: string; + userPrompt: string; + model?: string; +} + +export class CopilotCredentialUnavailableError extends Error { + constructor(message: string, options?: ErrorOptions) { + super(message, options); + this.name = "CopilotCredentialUnavailableError"; + } +} + +function positiveInt(name: string, fallback: number): number { + const raw = process.env[name]; + if (!raw) return fallback; + const parsed = Number.parseInt(raw, 10); + if (Number.isInteger(parsed) && parsed > 0) return parsed; + console.warn(`[portal-copilot] ignoring invalid ${name}=${JSON.stringify(raw)}`); + return fallback; +} + +function sanitizedRuntimeEnv(): Record { + const allowed = [ + "PATH", + "LANG", + "LC_ALL", + "TMPDIR", + "TMP", + "TEMP", + "SSL_CERT_FILE", + "SSL_CERT_DIR", + "NODE_EXTRA_CA_CERTS", + "HTTP_PROXY", + "HTTPS_PROXY", + "NO_PROXY", + "http_proxy", + "https_proxy", + "no_proxy", + ] as const; + + const env: Record = {}; + for (const name of allowed) { + const value = process.env[name]; + if (value !== undefined) env[name] = value; + } + return env; +} + +function errorText(error: unknown): string { + if (!(error instanceof Error)) return String(error); + const cause = error.cause; + const causeText = + cause && typeof cause === "object" + ? `${"message" in cause ? String(cause.message) : ""} ${"code" in cause ? String(cause.code) : ""}` + : ""; + return `${error.message} ${causeText}`.trim(); +} + +function isRetryableCopilotError(error: unknown): boolean { + if (error instanceof CopilotCredentialUnavailableError) return false; + const text = errorText(error).toLowerCase(); + if ( + text.includes("authentication") || + text.includes("unauthorized") || + text.includes("forbidden") || + text.includes("invalid token") || + text.includes("protocol version mismatch") + ) { + return false; + } + return [ + "timeout", + "timed out", + "aborted", + "fetch failed", + "econnreset", + "econnrefused", + "etimedout", + "socket hang up", + "rate limit", + "too many requests", + "http 429", + "http 500", + "http 502", + "http 503", + "http 504", + ].some((pattern) => text.includes(pattern)); +} + +async function withTimeout( + operation: Promise, + timeoutMs: number, + message: string, +): Promise { + let timer: ReturnType | undefined; + const timeout = new Promise((_resolve, reject) => { + timer = setTimeout(() => reject(new Error(message)), timeoutMs); + }); + return Promise.race([operation, timeout]).finally(() => { + if (timer) clearTimeout(timer); + }); +} + +const denyPermissions: PermissionHandler = () => ({ + kind: "reject", + feedback: "Portal AI completions do not permit tool execution.", +}); + +export class PortalCopilotClientPool { + private readonly tokenClient: TokenManagerClient; + private readonly resources = new Set(); + private readonly pool: Pool; + private readonly requestTimeoutMs: number; + private readonly startupTimeoutMs: number; + private readonly shutdownTimeoutMs: number; + private resourcesCreated = 0; + private sessionsCreated = 0; + private sessionsDeleted = 0; + private shuttingDown = false; + + constructor(tokenClient = new TokenManagerClient()) { + this.tokenClient = tokenClient; + const max = positiveInt("PORTAL_COPILOT_POOL_SIZE", DEFAULT_POOL_SIZE); + const acquireTimeoutMillis = positiveInt( + "PORTAL_COPILOT_ACQUIRE_TIMEOUT_MS", + DEFAULT_ACQUIRE_TIMEOUT_MS, + ); + this.startupTimeoutMs = positiveInt( + "PORTAL_COPILOT_STARTUP_TIMEOUT_MS", + DEFAULT_STARTUP_TIMEOUT_MS, + ); + this.requestTimeoutMs = positiveInt( + "PORTAL_COPILOT_REQUEST_TIMEOUT_MS", + DEFAULT_REQUEST_TIMEOUT_MS, + ); + this.shutdownTimeoutMs = positiveInt( + "PORTAL_COPILOT_SHUTDOWN_TIMEOUT_MS", + DEFAULT_SHUTDOWN_TIMEOUT_MS, + ); + + this.pool = new Pool({ + min: 0, + max, + acquireTimeoutMillis, + createTimeoutMillis: this.startupTimeoutMs, + destroyTimeoutMillis: this.shutdownTimeoutMs, + idleTimeoutMillis: positiveInt( + "PORTAL_COPILOT_IDLE_TIMEOUT_MS", + DEFAULT_IDLE_TIMEOUT_MS, + ), + reapIntervalMillis: 1_000, + createRetryIntervalMillis: 500, + propagateCreateError: true, + create: () => this.createResource(), + validate: (resource) => resource.healthy && !resource.destroyed, + destroy: (resource) => this.destroyResource(resource), + log: (message) => console.warn(`[portal-copilot-pool] ${message}`), + }); + + this.pool.on("createFail", (_eventId, error) => { + console.warn(`[portal-copilot-pool] create failed: ${errorText(error)}`); + }); + this.pool.on("acquireFail", (_eventId, error) => { + console.warn(`[portal-copilot-pool] acquire failed: ${errorText(error)}`); + }); + } + + stats(): CopilotPoolStats { + return { + used: this.pool.numUsed(), + free: this.pool.numFree(), + pendingAcquires: this.pool.numPendingAcquires(), + pendingCreates: this.pool.numPendingCreates(), + resources: this.resources.size, + resourcesCreated: this.resourcesCreated, + sessionsCreated: this.sessionsCreated, + sessionsDeleted: this.sessionsDeleted, + }; + } + + async complete(request: CopilotCompletionRequest): Promise { + if (this.shuttingDown) { + throw new Error("Copilot SDK pool is shutting down"); + } + + try { + return await withRetry( + () => this.completeOnce(request), + { + maxRetries: 2, + baseDelayMs: 500, + maxDelayMs: 5_000, + isRetryable: isRetryableCopilotError, + onRetry: (error: unknown, attempt: number) => { + console.warn( + `[portal-copilot] completion attempt ${attempt} failed: ${errorText(error)}`, + ); + }, + }, + ); + } catch (error) { + if (error instanceof CopilotCredentialUnavailableError) throw error; + throw new Error(`Copilot SDK request failed: ${errorText(error)}`, { + cause: error, + }); + } + } + + async shutdown(): Promise { + if (this.shuttingDown) return; + this.shuttingDown = true; + + try { + await withTimeout( + this.pool.destroy(), + this.shutdownTimeoutMs, + `Copilot SDK pool did not drain within ${this.shutdownTimeoutMs}ms`, + ); + console.log("[portal-copilot-pool] shutdown complete"); + } catch (error) { + console.warn(`[portal-copilot-pool] graceful shutdown failed: ${errorText(error)}`); + await Promise.allSettled( + [...this.resources].map((resource) => this.destroyResource(resource, true)), + ); + } + } + + private async createResource(): Promise { + let token: string; + try { + token = await this.tokenClient.acquireToken("copilot-sdk"); + } catch (error) { + throw new CopilotCredentialUnavailableError( + `No Copilot SDK credential is available: ${errorText(error)}`, + { cause: error }, + ); + } + + const rootDirectory = await mkdtemp(join(tmpdir(), "scope-portal-copilot-")); + const workingDirectory = join(rootDirectory, "workspace"); + const baseDirectory = join(rootDirectory, "copilot-home"); + await Promise.all([ + mkdir(workingDirectory, { recursive: true }), + mkdir(baseDirectory, { recursive: true }), + ]); + + const client = new CopilotClient({ + gitHubToken: token, + useLoggedInUser: false, + mode: "empty", + workingDirectory, + baseDirectory, + enableRemoteSessions: false, + sessionIdleTimeoutSeconds: 60, + logLevel: "warning", + env: sanitizedRuntimeEnv(), + }); + const resource: CopilotPoolResource = { + client, + rootDirectory, + defaultModel: "", + healthy: true, + destroyed: false, + }; + this.resources.add(resource); + this.resourcesCreated += 1; + + try { + await withTimeout( + client.start(), + this.startupTimeoutMs, + `Copilot CLI did not start within ${this.startupTimeoutMs}ms`, + ); + await withTimeout( + client.ping("scope-portal-ai-ready"), + this.startupTimeoutMs, + `Copilot CLI did not respond within ${this.startupTimeoutMs}ms`, + ); + const models = await withTimeout( + client.listModels(), + this.startupTimeoutMs, + `Copilot model discovery did not finish within ${this.startupTimeoutMs}ms`, + ); + const preferred = [ + "gpt-5.4-mini", + "gpt-5.4", + "gpt-5.1", + "gpt-5-mini", + ]; + resource.defaultModel = + preferred.find((id) => models.some((model) => model.id === id)) || + models[0]?.id || + ""; + if (!resource.defaultModel) { + throw new Error("Copilot SDK returned no available models"); + } + console.log( + `[portal-copilot-pool] started pooled Copilot CLI runtime defaultModel=${resource.defaultModel}`, + ); + return resource; + } catch (error) { + resource.healthy = false; + await this.destroyResource(resource, true); + throw error; + } + } + + private async completeOnce(request: CopilotCompletionRequest): Promise { + const pending = this.pool.acquire(); + const resource = await pending.promise; + let session: CopilotSession | undefined; + let unsubscribe: (() => void) | undefined; + let reusable = true; + let fullResponse = ""; + + try { + session = await resource.client.createSession({ + sessionId: randomUUID(), + model: request.model || resource.defaultModel, + streaming: true, + systemMessage: { mode: "replace", content: request.systemPrompt }, + availableTools: [], + excludedTools: ["builtin:*", "mcp:*"], + tools: [], + mcpServers: {}, + skillDirectories: [], + customAgents: [], + enableConfigDiscovery: false, + skipCustomInstructions: true, + requestCanvasRenderer: false, + requestExtensions: false, + enableMcpApps: false, + enableSessionTelemetry: false, + includeSubAgentStreamingEvents: false, + mcpOAuthTokenStorage: "in-memory", + onPermissionRequest: denyPermissions, + }); + this.sessionsCreated += 1; + + unsubscribe = session.on("assistant.message_delta", (event) => { + fullResponse += event.data.deltaContent; + }); + + const response = await session.sendAndWait( + { prompt: request.userPrompt }, + this.requestTimeoutMs, + ); + const content = fullResponse.trim() || response?.data.content?.trim() || ""; + if (!content) { + throw new Error("Copilot SDK returned an empty response"); + } + return content; + } catch (error) { + reusable = !( + errorText(error).toLowerCase().includes("authentication") || + errorText(error).toLowerCase().includes("protocol") || + errorText(error).toLowerCase().includes("connection") || + errorText(error).toLowerCase().includes("process exited") + ); + if (session && errorText(error).toLowerCase().includes("timeout")) { + await withTimeout( + session.abort(), + 5_000, + "Copilot session abort timed out", + ).catch(() => undefined); + } + throw error; + } finally { + unsubscribe?.(); + + if (session) { + try { + await withTimeout( + session.disconnect(), + this.shutdownTimeoutMs, + "Copilot session disconnect timed out", + ); + await withTimeout( + resource.client.deleteSession(session.sessionId), + this.shutdownTimeoutMs, + "Copilot session deletion timed out", + ); + this.sessionsDeleted += 1; + } catch (error) { + reusable = false; + console.warn(`[portal-copilot] session cleanup failed: ${errorText(error)}`); + } + } + + if (reusable) { + try { + await withTimeout( + resource.client.ping("scope-portal-ai-health"), + 5_000, + "Copilot CLI health check timed out", + ); + } catch (error) { + reusable = false; + console.warn(`[portal-copilot] health check failed: ${errorText(error)}`); + } + } + + if (reusable) { + this.pool.release(resource); + } else { + resource.healthy = false; + await this.destroyResource(resource, true); + this.pool.release(resource); + } + } + } + + private async destroyResource( + resource: CopilotPoolResource, + force = false, + ): Promise { + if (resource.destroyed) return; + resource.destroyed = true; + resource.healthy = false; + + try { + if (force) { + await resource.client.forceStop().catch(() => undefined); + } else { + const errors = await withTimeout( + resource.client.stop(), + this.shutdownTimeoutMs, + `Copilot CLI did not stop within ${this.shutdownTimeoutMs}ms`, + ); + if (errors.length > 0) { + console.warn( + `[portal-copilot-pool] client stopped with ${errors.length} cleanup error(s)`, + ); + } + } + } catch (error) { + console.warn(`[portal-copilot-pool] stop failed: ${errorText(error)}`); + await resource.client.forceStop().catch(() => undefined); + } finally { + await rm(resource.rootDirectory, { recursive: true, force: true }).catch((error) => { + console.warn(`[portal-copilot-pool] temp cleanup failed: ${errorText(error)}`); + }); + this.resources.delete(resource); + } + } +} + +let sharedPool: PortalCopilotClientPool | undefined; + +export function getPortalCopilotClientPool(): PortalCopilotClientPool { + sharedPool ??= new PortalCopilotClientPool(); + return sharedPool; +} + +export async function shutdownPortalCopilotClientPool(): Promise { + const pool = sharedPool; + sharedPool = undefined; + await pool?.shutdown(); +} + +/** @internal */ +export function setPortalCopilotClientPoolForTests( + pool: PortalCopilotClientPool | undefined, +): void { + sharedPool = pool; +} diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index f35f6d0de..9803a0581 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -49,6 +49,7 @@ import { registerProfilesRoutes } from "./routes/profiles.js"; import { registerProjectsRoutes } from "./routes/projects.js"; import { ProjectScopeError } from "./utils/project-scope.js"; import { registerUsersRoutes } from "./routes/users.js"; +import { shutdownPortalCopilotClientPool } from "./copilot-client-pool.js"; import type { RouteContext } from "./route-context.js"; import type { CriteriaDocument, @@ -400,6 +401,7 @@ async function main(): Promise { process.exitCode = 1; } void Promise.all([ + shutdownPortalCopilotClientPool(), userAccessCache?.close(), heartbeatStore.close(), mongoClient.close(), diff --git a/apps/api/src/llm-token.test.ts b/apps/api/src/llm-token.test.ts new file mode 100644 index 000000000..f274756ab --- /dev/null +++ b/apps/api/src/llm-token.test.ts @@ -0,0 +1,173 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + acquireToken: vi.fn(), + copilotComplete: vi.fn(), + modelClient: vi.fn(), + modelPost: vi.fn(), + parseFoundrySecret: vi.fn(), +})); + +vi.mock("@azure-rest/ai-inference", () => ({ + default: mocks.modelClient, + isUnexpected: (response: { status: string }) => response.status !== "200", +})); + +vi.mock("@azure/core-auth", () => ({ + AzureKeyCredential: class { + constructor(readonly key: string) {} + }, +})); + +vi.mock("shared", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + TokenManagerClient: class { + acquireToken = mocks.acquireToken; + }, + parseAzureAiFoundrySecret: mocks.parseFoundrySecret, + }; +}); + +vi.mock("./copilot-client-pool.js", () => { + class CopilotCredentialUnavailableError extends Error {} + return { + CopilotCredentialUnavailableError, + getPortalCopilotClientPool: () => ({ complete: mocks.copilotComplete }), + }; +}); + +import { + completePortalLlm, + type PortalLlmCompletionRequest, +} from "./llm-token.js"; +import { CopilotCredentialUnavailableError } from "./copilot-client-pool.js"; + +const request: PortalLlmCompletionRequest = { + messages: [ + { role: "system", content: "system" }, + { role: "user", content: "user" }, + ], + model: "request-model", + temperature: 0.2, + max_tokens: 128, +}; + +function completion(content: string) { + return { + status: "200", + body: { choices: [{ message: { content } }] }, + }; +} + +beforeEach(() => { + vi.resetAllMocks(); + for (const name of [ + "AZURE_AI_INFERENCE_ENDPOINT", + "AZURE_AI_INFERENCE_API_KEY", + "TOKEN_MANAGER_URL", + "GITHUB_MODELS_API_KEY", + "GITHUB_TOKEN", + "LLM_MODEL", + ]) { + vi.stubEnv(name, ""); + } + mocks.modelClient.mockReturnValue({ + path: () => ({ post: mocks.modelPost }), + }); + mocks.parseFoundrySecret.mockReturnValue(null); +}); + +afterEach(() => { + vi.unstubAllEnvs(); +}); + +describe("completePortalLlm provider resolution", () => { + it("prefers an explicit Foundry configuration over Copilot and GitHub Models", async () => { + vi.stubEnv("AZURE_AI_INFERENCE_ENDPOINT", "https://foundry.services.ai.azure.com"); + vi.stubEnv("AZURE_AI_INFERENCE_API_KEY", "foundry-key"); + vi.stubEnv("GITHUB_TOKEN", "github-token"); + mocks.modelPost.mockResolvedValue(completion("from-foundry")); + + await expect(completePortalLlm(request, "explicit-model")).resolves.toBe("from-foundry"); + + expect(mocks.modelClient).toHaveBeenCalledWith( + "https://foundry.services.ai.azure.com/models", + expect.objectContaining({ key: "foundry-key" }), + ); + expect(mocks.modelPost).toHaveBeenCalledWith({ + body: expect.objectContaining({ model: "explicit-model" }), + }); + expect(mocks.copilotComplete).not.toHaveBeenCalled(); + }); + + it("uses a Token Manager Foundry credential before Copilot", async () => { + vi.stubEnv("TOKEN_MANAGER_URL", "https://tokens.example.test"); + vi.stubEnv("GITHUB_TOKEN", "github-token"); + mocks.acquireToken.mockResolvedValueOnce("serialized-foundry-secret"); + mocks.parseFoundrySecret.mockReturnValue({ + endpoint: "https://managed-foundry.example.test/models", + apiKey: "managed-key", + model: "managed-model", + }); + mocks.modelPost.mockResolvedValue(completion("from-managed-foundry")); + + await expect(completePortalLlm(request)).resolves.toBe("from-managed-foundry"); + + expect(mocks.acquireToken).toHaveBeenCalledWith("azure-ai-inference"); + expect(mocks.modelPost).toHaveBeenCalledWith({ + body: expect.objectContaining({ model: "managed-model" }), + }); + expect(mocks.copilotComplete).not.toHaveBeenCalled(); + }); + + it("falls back to the Copilot SDK when Foundry credentials are unavailable", async () => { + vi.stubEnv("GITHUB_TOKEN", "github-token"); + mocks.copilotComplete.mockResolvedValue("from-copilot"); + + await expect(completePortalLlm(request, "copilot-model")).resolves.toBe("from-copilot"); + + expect(mocks.copilotComplete).toHaveBeenCalledWith({ + systemPrompt: "system", + userPrompt: "user", + model: "copilot-model", + }); + expect(mocks.modelPost).not.toHaveBeenCalled(); + }); + + it("falls back to GitHub Models only when Copilot has no usable credential", async () => { + vi.stubEnv("TOKEN_MANAGER_URL", "https://tokens.example.test"); + mocks.acquireToken + .mockRejectedValueOnce(new Error("no Foundry key")) + .mockResolvedValueOnce("github-models-key"); + mocks.copilotComplete.mockRejectedValue( + new CopilotCredentialUnavailableError("no Copilot credential"), + ); + mocks.modelPost.mockResolvedValue(completion("from-github-models")); + + await expect(completePortalLlm(request)).resolves.toBe("from-github-models"); + + expect(mocks.copilotComplete).toHaveBeenCalledOnce(); + expect(mocks.acquireToken).toHaveBeenNthCalledWith(2, "github-models"); + expect(mocks.modelPost).toHaveBeenCalledOnce(); + }); + + it("does not hide an inference failure by falling through to another provider", async () => { + vi.stubEnv("AZURE_AI_INFERENCE_ENDPOINT", "https://foundry.example.test/models"); + vi.stubEnv("AZURE_AI_INFERENCE_API_KEY", "foundry-key"); + vi.stubEnv("GITHUB_TOKEN", "github-token"); + mocks.modelPost.mockResolvedValue({ + status: "500", + body: { error: { message: "Foundry unavailable" } }, + }); + + await expect(completePortalLlm(request)).rejects.toThrow( + "LLM request failed: Foundry unavailable", + ); + expect(mocks.copilotComplete).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/api/src/llm-token.ts b/apps/api/src/llm-token.ts index b9d080357..6b879cfc0 100644 --- a/apps/api/src/llm-token.ts +++ b/apps/api/src/llm-token.ts @@ -10,20 +10,30 @@ * 2. Azure AI Foundry via the Token Manager — TOKEN_MANAGER_URL with at * least one registered `azure-ai-foundry` key (preferred for prod; * round-robins across registered keys). - * 3. GitHub Models — https://models.inference.ai.azure.com via + * 3. GitHub Copilot SDK — a bounded pool of tool-less Copilot CLI runtimes + * using the `copilot-sdk` Token Manager capability (or GITHUB_TOKEN). + * 4. GitHub Models — https://models.inference.ai.azure.com via * GITHUB_MODELS_API_KEY → TokenManagerClient("github-models") → GITHUB_TOKEN - * (fallback; slow public endpoint, fine for local dev only). + * (legacy compatibility fallback). * - * All three portal LLM modules (llm.ts, prompt-feature-llm.ts, - * task-prompt-llm.ts) call acquireInferenceClient() instead of constructing - * a ModelClient inline so the endpoint can be swapped in one place. + * All portal LLM modules call completePortalLlm() so provider selection and + * lifecycle policy remain centralized. */ -import ModelClient, { type ModelClient as ModelClientType } from "@azure-rest/ai-inference"; +import ModelClient, { + isUnexpected, + type ModelClient as ModelClientType, +} from "@azure-rest/ai-inference"; import { AzureKeyCredential } from "@azure/core-auth"; import { + type ChatCompletionMessage, TokenManagerClient, parseAzureAiFoundrySecret, } from "shared"; +import { postAdaptiveChatCompletion } from "./adaptive-chat-completions.js"; +import { + CopilotCredentialUnavailableError, + getPortalCopilotClientPool, +} from "./copilot-client-pool.js"; const GITHUB_MODELS_ENDPOINT = "https://models.inference.ai.azure.com"; @@ -84,6 +94,8 @@ export function isInferenceError(err: unknown): err is Error { return ( err.message.includes("not configured") || lower.includes("llm request failed") || + lower.includes("copilot sdk") || + lower.includes("copilot cli") || lower.includes("resource not found") || lower.includes("authentication failed") ); @@ -103,11 +115,19 @@ export function isGitHubModelsTokenAvailable(): boolean { ); } +export function isCopilotSdkTokenAvailable(): boolean { + return !!(process.env.GITHUB_TOKEN || process.env.TOKEN_MANAGER_URL); +} + /** - * Returns true if any inference backend (Foundry or GitHub Models) is configured. + * Returns true if any inference backend is configured. */ export function isLlmAvailable(): boolean { - return isFoundryConfigured() || isGitHubModelsTokenAvailable(); + return ( + isFoundryConfigured() || + isCopilotSdkTokenAvailable() || + isGitHubModelsTokenAvailable() + ); } /** @@ -150,7 +170,10 @@ export async function acquireGitHubModelsToken(): Promise { ); } -export type InferenceSource = "azure-ai-foundry" | "github-models"; +export type InferenceSource = + | "azure-ai-foundry" + | "copilot-sdk" + | "github-models"; /** * How the credential was actually resolved. Useful for log lines so an @@ -160,6 +183,8 @@ export type InferenceSource = "azure-ai-foundry" | "github-models"; export type InferenceVia = | "azure-ai-foundry-env" | "azure-ai-foundry-token-manager" + | "copilot-sdk-env" + | "copilot-sdk-token-manager" | "github-models-env" | "github-models-token-manager" | "github-token"; @@ -213,16 +238,7 @@ async function tryAcquireFoundryFromTokenManager(): Promise<{ } } -/** - * Build a ModelClient for the configured inference backend. - * - * Tries Azure AI Foundry first (env vars, then Token Manager), then falls - * back to GitHub Models. See module docstring for the full priority order. - * - * @throws Error if no inference backend is configured. - */ -export async function acquireInferenceClient(): Promise { - // 1. Azure AI Foundry via env vars — explicit override, preferred locally. +async function tryAcquireFoundryClient(): Promise { if (isFoundryConfigured()) { const endpoint = normalizeFoundryEndpoint(process.env.AZURE_AI_INFERENCE_ENDPOINT!); const apiKey = process.env.AZURE_AI_INFERENCE_API_KEY!; @@ -238,38 +254,176 @@ export async function acquireInferenceClient(): Promise { return handle; } - // 2. Azure AI Foundry via the Token Manager — preferred in production. const tmFoundry = await tryAcquireFoundryFromTokenManager(); - if (tmFoundry) { - const model = tmFoundry.model || process.env.LLM_MODEL || "gpt-4.1"; - const handle: InferenceClientHandle = { - client: ModelClient(tmFoundry.endpoint, new AzureKeyCredential(tmFoundry.apiKey)), - endpoint: tmFoundry.endpoint, - source: "azure-ai-foundry", - via: "azure-ai-foundry-token-manager", - model, - }; - logInferenceAcquired(handle); - return handle; + if (!tmFoundry) return null; + + const model = tmFoundry.model || process.env.LLM_MODEL || "gpt-4.1"; + const handle: InferenceClientHandle = { + client: ModelClient(tmFoundry.endpoint, new AzureKeyCredential(tmFoundry.apiKey)), + endpoint: tmFoundry.endpoint, + source: "azure-ai-foundry", + via: "azure-ai-foundry-token-manager", + model, + }; + logInferenceAcquired(handle); + return handle; +} + +async function acquireGitHubModelsClient(): Promise { + const token = await acquireGitHubModelsToken(); + const via: InferenceVia = process.env.GITHUB_MODELS_API_KEY + ? "github-models-env" + : process.env.TOKEN_MANAGER_URL + ? "github-models-token-manager" + : "github-token"; + const handle: InferenceClientHandle = { + client: ModelClient(GITHUB_MODELS_ENDPOINT, new AzureKeyCredential(token)), + endpoint: GITHUB_MODELS_ENDPOINT, + source: "github-models", + via, + }; + logInferenceAcquired(handle); + return handle; +} + +export interface PortalLlmCompletionRequest { + messages: [ + { role: "system"; content: string }, + { role: "user"; content: string }, + ]; + model: string; + temperature: number; + max_tokens: number; +} + +function inferenceErrorMessage(body: unknown, status: string): string { + if ( + body && + typeof body === "object" && + "error" in body && + body.error && + typeof body.error === "object" && + "message" in body.error && + typeof body.error.message === "string" + ) { + return body.error.message; + } + return status; +} + +async function completeWithRestInference( + handle: InferenceClientHandle, + request: PortalLlmCompletionRequest, +): Promise { + const messages: ChatCompletionMessage[] = request.messages; + const response = await postAdaptiveChatCompletion({ + endpoint: handle.endpoint, + model: request.model, + messages, + temperature: request.temperature, + maxTokens: request.max_tokens, + send: (body) => handle.client.path("/chat/completions").post({ body }), + }); + + if (isUnexpected(response)) { + throw new Error( + `LLM request failed: ${inferenceErrorMessage(response.body, response.status)}`, + ); + } + + const content = response.body.choices?.[0]?.message?.content; + if (!content) { + throw new Error("LLM returned empty response"); } + return content; +} + +/** + * Complete one Portal AI request using the configured provider chain: + * Foundry env, Foundry Token Manager, Copilot SDK, then legacy GitHub Models. + * + * Provider fallback only happens while resolving a credential. Once a provider + * begins inference, its errors are surfaced and never hidden by another backend. + */ +export async function completePortalLlm( + request: PortalLlmCompletionRequest, + explicitModel?: string, +): Promise { + const foundry = await tryAcquireFoundryClient(); + if (foundry) { + const model = + explicitModel || + foundry.model || + process.env.LLM_MODEL || + request.model || + "gpt-4.1"; + return completeWithRestInference(foundry, { ...request, model }); + } + + if (isCopilotSdkTokenAvailable()) { + try { + const via: InferenceVia = process.env.GITHUB_TOKEN + ? "copilot-sdk-env" + : "copilot-sdk-token-manager"; + const copilotModel = + explicitModel || + process.env.PORTAL_COPILOT_MODEL || + process.env.LLM_MODEL; + console.log( + `[llm-token] inference provider: source=copilot-sdk via=${via} model=${copilotModel || "auto"}`, + ); + return await getPortalCopilotClientPool().complete({ + systemPrompt: request.messages[0].content, + userPrompt: request.messages[1].content, + model: copilotModel, + }); + } catch (error) { + if (!(error instanceof CopilotCredentialUnavailableError)) { + throw error; + } + } + } + + if (isGitHubModelsTokenAvailable()) { + let githubModels: InferenceClientHandle | null = null; + try { + githubModels = await acquireGitHubModelsClient(); + } catch { + // Credential resolution failed; continue to the unified unavailable error. + } + if (githubModels) { + return completeWithRestInference(githubModels, { + ...request, + model: + explicitModel || + process.env.LLM_MODEL || + request.model || + "gpt-4.1", + }); + } + } + + throw new Error( + "LLM not configured: no inference backend available. Register an Azure AI Foundry credential, a GitHub token with Copilot SDK capability, or a legacy GitHub Models key." + ); +} + +/** + * Build a ModelClient for the configured inference backend. + * + * Tries Azure AI Foundry first (env vars, then Token Manager), then falls + * back to GitHub Models. See module docstring for the full priority order. + * + * @throws Error if no inference backend is configured. + */ +export async function acquireInferenceClient(): Promise { + const foundry = await tryAcquireFoundryClient(); + if (foundry) return foundry; - // 3. GitHub Models — public fallback (slow; fine for local dev). + // Legacy REST-only helper: Copilot SDK is exposed through completePortalLlm(). if (isGitHubModelsTokenAvailable()) { try { - const token = await acquireGitHubModelsToken(); - const via: InferenceVia = process.env.GITHUB_MODELS_API_KEY - ? "github-models-env" - : process.env.TOKEN_MANAGER_URL - ? "github-models-token-manager" - : "github-token"; - const handle: InferenceClientHandle = { - client: ModelClient(GITHUB_MODELS_ENDPOINT, new AzureKeyCredential(token)), - endpoint: GITHUB_MODELS_ENDPOINT, - source: "github-models", - via, - }; - logInferenceAcquired(handle); - return handle; + return await acquireGitHubModelsClient(); } catch { // No usable GitHub Models token after all — drop through to the // unified "no backend configured" error below so the UI gets a @@ -279,6 +433,6 @@ export async function acquireInferenceClient(): Promise { } throw new Error( - "LLM not configured: no inference backend available. Please register a new secret key for GitHub Model or Azure Foundry." + "LLM not configured: no REST inference backend available. Register an Azure AI Foundry credential or a legacy GitHub Models key." ); } diff --git a/apps/api/src/llm.test.ts b/apps/api/src/llm.test.ts index df069a242..e6ebf08da 100644 --- a/apps/api/src/llm.test.ts +++ b/apps/api/src/llm.test.ts @@ -11,11 +11,23 @@ vi.mock("@azure-rest/ai-inference", () => ({ // Mock the inference client acquisition; the per-test `postSpy` drives responses. const postSpy = vi.fn(); vi.mock("./llm-token.js", () => ({ - acquireInferenceClient: vi.fn(async () => ({ - client: { path: () => ({ post: postSpy }) }, - endpoint: "https://test.example.com/models", - model: "test-model", - })), + completePortalLlm: vi.fn(async (request: { + messages: Array<{ role: string; content: string }>; + model: string; + temperature: number; + max_tokens: number; + }, explicitModel?: string) => { + const { postAdaptiveChatCompletion } = await import("./adaptive-chat-completions.js"); + const response = await postAdaptiveChatCompletion({ + endpoint: "https://test.example.com/models", + model: explicitModel || request.model, + messages: request.messages, + temperature: request.temperature, + maxTokens: request.max_tokens, + send: (body) => postSpy({ body }), + }); + return response.body.choices[0].message.content; + }), isLlmAvailable: () => true, })); diff --git a/apps/api/src/llm.ts b/apps/api/src/llm.ts index 90393f2b6..3a9836d5d 100644 --- a/apps/api/src/llm.ts +++ b/apps/api/src/llm.ts @@ -5,9 +5,10 @@ import { gatesSatisfyInvariant, type GateId, } from "shared"; -import { isUnexpected } from "@azure-rest/ai-inference"; -import { postAdaptiveChatCompletion } from "./adaptive-chat-completions.js"; -import { acquireInferenceClient, isLlmAvailable as inferenceAvailable } from "./llm-token.js"; +import { + completePortalLlm, + isLlmAvailable as inferenceAvailable, +} from "./llm-token.js"; export type SuggestDirection = "parents" | "children"; @@ -180,8 +181,6 @@ export function isLlmAvailable(): boolean { return inferenceAvailable(); } -type ChatClient = Awaited>["client"]; - function sanitizeId(suggestedId: unknown): string { if (typeof suggestedId !== "string") return "new_criterion"; const sanitized = suggestedId @@ -292,29 +291,10 @@ export function selectCriteriaDependencyPool( } async function chat( - llm: ChatClient, - endpoint: string, request: CriteriaPromptRequest, + explicitModel?: string, ): Promise { - const response = await postAdaptiveChatCompletion({ - endpoint, - model: request.model, - messages: request.messages, - temperature: request.temperature, - maxTokens: request.max_tokens, - send: (body) => llm.path("/chat/completions").post({ body }), - }); - - if (isUnexpected(response)) { - const errBody = response.body as any; - throw new Error(`LLM request failed: ${errBody?.error?.message || response.status}`); - } - - const content = response.body.choices?.[0]?.message?.content; - if (!content) { - throw new Error("LLM returned empty response"); - } - return content; + return completePortalLlm(request, explicitModel); } /** @@ -322,16 +302,14 @@ async function chat( * is the one indispensable result of generation. */ async function author( - llm: ChatClient, - endpoint: string, model: string, behavior: string, gates?: GateId[], + explicitModel?: string, ): Promise<{ prompt: string; suggestedId: string }> { const content = await chat( - llm, - endpoint, buildCriteriaAuthoringRequest(behavior, gates, model), + explicitModel, ); return parseCriteriaAuthoringResponse(content); } @@ -363,23 +341,21 @@ function buildSuggestMessage( */ async function suggestDeps( direction: SuggestDirection, - llm: ChatClient, - endpoint: string, model: string, behavior: string, pool: ExistingCriterion[], + explicitModel?: string, ): Promise { if (pool.length === 0) return []; try { const content = await chat( - llm, - endpoint, buildCriteriaDependencySuggestionRequest( direction, behavior, pool, model, ), + explicitModel, ); return parseCriteriaDependencySuggestionResponse(content, pool); } catch (err) { @@ -408,14 +384,7 @@ export async function generateCriteriaPrompt( newGates?: GateId[], model?: string, ): Promise { - const { - client: llm, - endpoint, - model: foundryModel, - } = await acquireInferenceClient(); - - // Priority: explicit arg > key-specific (from Foundry blob) > env > default. - const modelName = model || foundryModel || process.env.LLM_MODEL || "gpt-4.1"; + const modelName = model || process.env.LLM_MODEL || "gpt-4.1"; const parentPool = selectCriteriaDependencyPool( "parents", @@ -429,22 +398,20 @@ export async function generateCriteriaPrompt( ); const [authored, suggestedParents, suggestedChildrenRaw] = await Promise.all([ - author(llm, endpoint, modelName, behavior, newGates), + author(modelName, behavior, newGates, model), suggestDeps( "parents", - llm, - endpoint, modelName, behavior, parentPool, + model, ), suggestDeps( "children", - llm, - endpoint, modelName, behavior, childPool, + model, ), ]); diff --git a/apps/api/src/portal-ai-copilot.integration.test.ts b/apps/api/src/portal-ai-copilot.integration.test.ts new file mode 100644 index 000000000..26ff853b4 --- /dev/null +++ b/apps/api/src/portal-ai-copilot.integration.test.ts @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import express from "express"; +import request from "supertest"; +import { OpenAPIRegistry } from "@asteasolutions/zod-to-openapi"; +import { afterAll, describe, expect, it } from "vitest"; +import type { RouteContext } from "./route-context.js"; +import { registerCriteriaRoutes } from "./routes/criteria.js"; +import { registerPromptFeaturesRoutes } from "./routes/prompt-features.js"; +import { registerTaskPromptsRoutes } from "./routes/task-prompts.js"; +import { + getPortalCopilotClientPool, + shutdownPortalCopilotClientPool, +} from "./copilot-client-pool.js"; + +const integrationEnabled = + process.env.RUN_PORTAL_AI_COPILOT_INTEGRATION === "1" && + !!process.env.TOKEN_MANAGER_URL; +const describeIntegration = integrationEnabled ? describe : describe.skip; + +function cursor(rows: T[]) { + return { + project() { + return this; + }, + sort() { + return this; + }, + limit() { + return this; + }, + async toArray() { + return rows; + }, + }; +} + +function createPortalAiApp() { + const app = express(); + app.use(express.json()); + + const criteria = [ + { + id: "has_tests", + prompt: "The project includes tests.", + dependsOn: [], + gates: ["select"], + }, + { + id: "tests_pass", + prompt: "The captured test command succeeds.", + dependsOn: ["has_tests"], + gates: ["select", "test"], + }, + ]; + const promptFeatures = [ + { + id: "asks_for_tests", + prompt: "The task asks the coding agent to add or run tests.", + type: "select", + }, + ]; + + const ctx = { + app, + registry: new OpenAPIRegistry(), + criteriaCollection: { + find: () => cursor(criteria), + }, + promptFeatureCollection: { + find: () => cursor(promptFeatures), + }, + taskPromptCollection: { + find: () => cursor([]), + }, + } as unknown as RouteContext; + + registerCriteriaRoutes(ctx); + registerPromptFeaturesRoutes(ctx); + registerTaskPromptsRoutes(ctx); + app.use((error: Error, _req: express.Request, res: express.Response, _next: express.NextFunction) => { + res.status(500).json({ error: error.message }); + }); + return app; +} + +describeIntegration("Portal AI Copilot end-to-end smoke", () => { + const app = createPortalAiApp(); + + afterAll(async () => { + await shutdownPortalCopilotClientPool(); + }); + + it("forces Token Manager to Copilot SDK and exercises every Portal AI route", async () => { + expect(process.env.GITHUB_TOKEN).toBeFalsy(); + expect(process.env.GITHUB_MODELS_API_KEY).toBeFalsy(); + expect(process.env.AZURE_AI_INFERENCE_ENDPOINT).toBeFalsy(); + expect(process.env.AZURE_AI_INFERENCE_API_KEY).toBeFalsy(); + + const pool = getPortalCopilotClientPool(); + const before = pool.stats(); + + const criterion = await request(app) + .post("/api/v1/criteria/generate-prompt") + .send({ + behavior: "The project includes meaningful automated tests.", + gates: ["select"], + }) + .expect(200); + expect(criterion.body).toEqual({ + prompt: expect.any(String), + suggestedId: expect.any(String), + suggestedParents: expect.any(Array), + suggestedChildren: expect.any(Array), + }); + + const afterCriterion = pool.stats(); + expect(afterCriterion.sessionsCreated - before.sessionsCreated).toBe(3); + expect(afterCriterion.sessionsDeleted - before.sessionsDeleted).toBe(3); + expect(afterCriterion.resourcesCreated - before.resourcesCreated).toBeLessThanOrEqual( + Number(process.env.PORTAL_COPILOT_POOL_SIZE || 2), + ); + expect(afterCriterion.used).toBe(0); + expect(afterCriterion.pendingAcquires).toBe(0); + + const generatedTask = await request(app) + .post("/api/v1/task-prompts/generate") + .send({ description: "A small TypeScript REST API with tests." }) + .expect(200); + expect(generatedTask.body.taskPrompt).toEqual(expect.any(String)); + + const variedTask = await request(app) + .post("/api/v1/task-prompts/generate") + .send({ + existingPrompt: generatedTask.body.taskPrompt, + description: "Use Python instead of TypeScript.", + }) + .expect(200); + expect(variedTask.body.taskPrompt).toEqual(expect.any(String)); + + const generatedFeature = await request(app) + .post("/api/v1/prompt-features/generate-prompt") + .send({ behavior: "The task asks for automated tests." }) + .expect(200); + expect(generatedFeature.body).toEqual({ + prompt: expect.any(String), + suggestedId: expect.any(String), + suggestedParents: expect.any(Array), + suggestedChildren: expect.any(Array), + }); + + const extracted = await request(app) + .post("/api/v1/prompt-features/extract-from-text") + .send({ + text: "Create a TypeScript service and include unit tests.", + type: "select", + }) + .expect(200); + expect(extracted.body).toEqual({ + features: expect.any(Array), + cached: false, + ...(extracted.body.suggestedFeatures + ? { suggestedFeatures: expect.any(Array) } + : {}), + }); + + const after = pool.stats(); + expect(after.sessionsCreated - before.sessionsCreated).toBe(7); + expect(after.sessionsDeleted).toBe(after.sessionsCreated); + expect(after.used).toBe(0); + expect(after.pendingAcquires).toBe(0); + expect(after.pendingCreates).toBe(0); + }); +}); diff --git a/apps/api/src/portal-ai-copy.test.ts b/apps/api/src/portal-ai-copy.test.ts new file mode 100644 index 000000000..5bc273000 --- /dev/null +++ b/apps/api/src/portal-ai-copy.test.ts @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { describe, expect, it } from "vitest"; +import { PORTAL_AI_NOT_CONFIGURED_ERROR } from "./portal-ai-copy.js"; + +describe("Portal AI fallback copy", () => { + it("recommends Copilot SDK and identifies GitHub Models as legacy", () => { + expect(PORTAL_AI_NOT_CONFIGURED_ERROR).toContain( + "GitHub token with Copilot SDK capability", + ); + expect(PORTAL_AI_NOT_CONFIGURED_ERROR).toContain( + "legacy GitHub Models key", + ); + }); +}); diff --git a/apps/api/src/portal-ai-copy.ts b/apps/api/src/portal-ai-copy.ts new file mode 100644 index 000000000..d2ca4370f --- /dev/null +++ b/apps/api/src/portal-ai-copy.ts @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +export const PORTAL_AI_NOT_CONFIGURED_ERROR = + "LLM not configured: no inference backend available. Register an Azure AI Foundry credential, a GitHub token with Copilot SDK capability, or a legacy GitHub Models key."; diff --git a/apps/api/src/prompt-feature-llm.ts b/apps/api/src/prompt-feature-llm.ts index dc1cdff79..626e68d8d 100644 --- a/apps/api/src/prompt-feature-llm.ts +++ b/apps/api/src/prompt-feature-llm.ts @@ -1,14 +1,15 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { isUnexpected } from "@azure-rest/ai-inference"; import { PromptFeatureConfig, PromptFeatureResult, SuggestedPromptFeature, } from "shared"; -import { postAdaptiveChatCompletion } from "./adaptive-chat-completions.js"; -import { acquireInferenceClient, isLlmAvailable as inferenceAvailable } from "./llm-token.js"; +import { + completePortalLlm, + isLlmAvailable as inferenceAvailable, +} from "./llm-token.js"; // --------------------------------------------------------------------------- // Generate prompt feature prompt (mirrors criteria generateCriteriaPrompt) @@ -166,40 +167,14 @@ export async function generatePromptFeaturePrompt( existingFeatures: ExistingPromptFeature[] = [], model?: string, ): Promise { - const { - client: llm, - endpoint, - model: foundryModel, - } = await acquireInferenceClient(); - - // Priority: explicit arg > key-specific (from Foundry blob) > env > default. - const modelName = model || foundryModel || process.env.LLM_MODEL || "gpt-4.1"; + const modelName = model || process.env.LLM_MODEL || "gpt-4.1"; const request = buildPromptFeatureAuthoringRequest( behavior, existingFeatures, modelName, ); - const response = await postAdaptiveChatCompletion({ - endpoint, - model: request.model, - messages: request.messages, - temperature: request.temperature, - maxTokens: request.max_tokens, - send: (body) => llm.path("/chat/completions").post({ body }), - }); - - if (isUnexpected(response)) { - const errBody = response.body as any; - throw new Error( - `LLM request failed: ${errBody?.error?.message || response.status}`, - ); - } - - const content = response.body.choices?.[0]?.message?.content; - if (!content) { - throw new Error("LLM returned empty response"); - } + const content = await completePortalLlm(request, model); return parsePromptFeatureAuthoringResponse(content, existingFeatures); } @@ -348,40 +323,14 @@ export async function extractPromptFeatures( features: PromptFeatureConfig[], model?: string, ): Promise { - const { - client: llm, - endpoint, - model: foundryModel, - } = await acquireInferenceClient(); - - // Priority: explicit arg > key-specific (from Foundry blob) > env > default. - const modelName = model || foundryModel || process.env.LLM_MODEL || "gpt-4.1"; + const modelName = model || process.env.LLM_MODEL || "gpt-4.1"; const request = buildPromptFeatureExtractionRequest( taskText, features, modelName, ); - const response = await postAdaptiveChatCompletion({ - endpoint, - model: request.model, - messages: request.messages, - temperature: request.temperature, - maxTokens: request.max_tokens, - send: (body) => llm.path("/chat/completions").post({ body }), - }); - - if (isUnexpected(response)) { - const errBody = response.body as any; - throw new Error( - `LLM extraction failed: ${errBody?.error?.message || response.status}`, - ); - } - - const content = response.body.choices?.[0]?.message?.content; - if (!content) { - throw new Error("LLM returned empty response"); - } + const content = await completePortalLlm(request, model); return parsePromptFeatureExtractionResponse(content, features); } diff --git a/apps/api/src/prompt-request-transport.test.ts b/apps/api/src/prompt-request-transport.test.ts index ca03672c9..f4f261411 100644 --- a/apps/api/src/prompt-request-transport.test.ts +++ b/apps/api/src/prompt-request-transport.test.ts @@ -31,11 +31,28 @@ vi.mock("@azure-rest/ai-inference", () => ({ })); vi.mock("./llm-token.js", () => ({ - acquireInferenceClient: async () => ({ - client: { path: () => ({ post: mockPost }) }, - endpoint: "https://prompt-transport.example.test/models", - model: "test-deployment", - }), + completePortalLlm: async (request: { + messages: ChatCompletionRequestBody["messages"]; + model: string; + temperature: number; + max_tokens: number; + }, explicitModel?: string) => { + const { postAdaptiveChatCompletion } = await import("./adaptive-chat-completions.js"); + const response = await postAdaptiveChatCompletion({ + endpoint: "https://prompt-transport.example.test/models", + model: explicitModel || request.model, + messages: request.messages, + temperature: request.temperature, + maxTokens: request.max_tokens, + send: (body) => mockPost({ body }), + }); + const body = response.body as { + choices?: Array<{ message?: { content?: string } }>; + }; + const content = body.choices?.[0]?.message?.content; + if (!content) throw new Error("LLM returned empty response"); + return content; + }, isLlmAvailable: () => true, })); diff --git a/apps/api/src/routes/criteria.ts b/apps/api/src/routes/criteria.ts index 36564769e..6408098c6 100644 --- a/apps/api/src/routes/criteria.ts +++ b/apps/api/src/routes/criteria.ts @@ -19,6 +19,7 @@ import { computeMdp } from "../criteria-mdp.js"; import type { MdpAnalyzableRun } from "../criteria-mdp.js"; import { generateCriteriaPrompt, isLlmAvailable } from "../llm.js"; import { isInferenceError } from "../llm-token.js"; +import { PORTAL_AI_NOT_CONFIGURED_ERROR } from "../portal-ai-copy.js"; import { ProjectIdQuerySchema, OptionalProjectIdQuerySchema, getQueryProjectId, getOptionalQueryProjectId } from "../utils/project-scope.js"; /** @@ -84,7 +85,7 @@ apiRoute(ctx.app, ctx.registry, { } if (!isLlmAvailable()) { - res.status(503).json({ error: "LLM not configured: no inference backend available. Please register a new secret key for GitHub Model or Azure Foundry." }); + res.status(503).json({ error: PORTAL_AI_NOT_CONFIGURED_ERROR }); return; } diff --git a/apps/api/src/routes/prompt-features.ts b/apps/api/src/routes/prompt-features.ts index 30e96f5ef..ca2eafea9 100644 --- a/apps/api/src/routes/prompt-features.ts +++ b/apps/api/src/routes/prompt-features.ts @@ -13,6 +13,7 @@ import { apiRoute } from "../openapi/api-route.js"; import type { PromptFeatureDocument, RouteContext } from "../route-context.js"; import { extractPromptFeatures, generatePromptFeaturePrompt, isLlmAvailable as isPromptFeatureLlmAvailable } from "../prompt-feature-llm.js"; import { isInferenceError } from "../llm-token.js"; +import { PORTAL_AI_NOT_CONFIGURED_ERROR } from "../portal-ai-copy.js"; import { ProjectIdQuerySchema, OptionalProjectIdQuerySchema, getQueryProjectId, getOptionalQueryProjectId } from "../utils/project-scope.js"; export function registerPromptFeaturesRoutes(ctx: RouteContext): void { @@ -43,7 +44,7 @@ apiRoute(ctx.app, ctx.registry, { } if (!isPromptFeatureLlmAvailable()) { - res.status(503).json({ error: "LLM not configured: no inference backend available. Please register a new secret key for GitHub Model or Azure Foundry." }); + res.status(503).json({ error: PORTAL_AI_NOT_CONFIGURED_ERROR }); return; } @@ -161,7 +162,7 @@ apiRoute(ctx.app, ctx.registry, { } if (!isPromptFeatureLlmAvailable()) { - res.status(503).json({ error: "LLM not configured: no inference backend available. Please register a new secret key for GitHub Model or Azure Foundry." }); + res.status(503).json({ error: PORTAL_AI_NOT_CONFIGURED_ERROR }); return; } diff --git a/apps/api/src/routes/task-prompts.ts b/apps/api/src/routes/task-prompts.ts index f626ea079..a9a15df55 100644 --- a/apps/api/src/routes/task-prompts.ts +++ b/apps/api/src/routes/task-prompts.ts @@ -15,6 +15,7 @@ import type { RouteContext } from "../route-context.js"; import { extractPromptFeatures, isLlmAvailable as isPromptFeatureLlmAvailable } from "../prompt-feature-llm.js"; import { generateTaskPrompt, isTaskPromptLlmAvailable } from "../task-prompt-llm.js"; import { isInferenceError } from "../llm-token.js"; +import { PORTAL_AI_NOT_CONFIGURED_ERROR } from "../portal-ai-copy.js"; import { ProjectIdQuerySchema, getQueryProjectId } from "../utils/project-scope.js"; export function registerTaskPromptsRoutes(ctx: RouteContext): void { @@ -42,7 +43,7 @@ apiRoute(ctx.app, ctx.registry, { const { description, existingPrompt } = req.body; if (!isTaskPromptLlmAvailable()) { - res.status(503).json({ error: "LLM not configured: no inference backend available. Please register a new secret key for GitHub Model or Azure Foundry." }); + res.status(503).json({ error: PORTAL_AI_NOT_CONFIGURED_ERROR }); return; } @@ -253,7 +254,7 @@ apiRoute(ctx.app, ctx.registry, { } if (!isPromptFeatureLlmAvailable()) { - res.status(503).json({ error: "LLM not configured: no inference backend available. Please register a new secret key for GitHub Model or Azure Foundry." }); + res.status(503).json({ error: PORTAL_AI_NOT_CONFIGURED_ERROR }); return; } diff --git a/apps/api/src/task-prompt-llm.test.ts b/apps/api/src/task-prompt-llm.test.ts index 47ed006e9..04a01f460 100644 --- a/apps/api/src/task-prompt-llm.test.ts +++ b/apps/api/src/task-prompt-llm.test.ts @@ -17,19 +17,34 @@ vi.mock("@azure/core-auth", () => ({ AzureKeyCredential: vi.fn(), })); -// Mock llm-token module — provides both the legacy GitHub Models helpers -// and the new shared acquireInferenceClient(). The task-prompt module now -// only calls acquireInferenceClient, but we keep the legacy exports so -// the rest of the module surface stays compatible. vi.mock("./llm-token.js", () => ({ isLlmAvailable: vi.fn(() => true), - isGitHubModelsTokenAvailable: vi.fn(() => true), - acquireGitHubModelsToken: vi.fn(async () => "fake-token"), - acquireInferenceClient: vi.fn(async () => ({ - client: { path: () => ({ post: mockPost }) }, - endpoint: "https://test.example.com", - source: "azure-ai-foundry", - })), + completePortalLlm: vi.fn(async (request: { + messages: Array<{ role: string; content: string }>; + model: string; + temperature: number; + max_tokens: number; + }, explicitModel?: string) => { + const { postAdaptiveChatCompletion } = await import("./adaptive-chat-completions.js"); + const response = await postAdaptiveChatCompletion({ + endpoint: "https://test.example.com", + model: explicitModel || request.model, + messages: request.messages, + temperature: request.temperature, + maxTokens: request.max_tokens, + send: (body) => mockPost({ body }), + }); + if (response.status !== "200") { + const body = response.body as { error?: { message?: string } }; + throw new Error(`LLM request failed: ${body.error?.message || response.status}`); + } + const body = response.body as { + choices?: Array<{ message?: { content?: string } }>; + }; + const content = body.choices?.[0]?.message?.content; + if (!content) throw new Error("LLM returned empty response"); + return content; + }), })); import { generateTaskPrompt, isTaskPromptLlmAvailable } from "./task-prompt-llm.js"; diff --git a/apps/api/src/task-prompt-llm.ts b/apps/api/src/task-prompt-llm.ts index c14a7e72e..30abc2a17 100644 --- a/apps/api/src/task-prompt-llm.ts +++ b/apps/api/src/task-prompt-llm.ts @@ -1,9 +1,10 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { isUnexpected } from "@azure-rest/ai-inference"; -import { postAdaptiveChatCompletion } from "./adaptive-chat-completions.js"; -import { acquireInferenceClient, isLlmAvailable as inferenceAvailable } from "./llm-token.js"; +import { + completePortalLlm, + isLlmAvailable as inferenceAvailable, +} from "./llm-token.js"; // --------------------------------------------------------------------------- // Generate task prompt from a short description or create a variation @@ -149,15 +150,7 @@ export async function generateTaskPrompt( model?: string, ): Promise { const { description, existingPrompt } = opts; - - const { - client: llm, - endpoint, - model: foundryModel, - } = await acquireInferenceClient(); - - // Priority: explicit arg > key-specific (from Foundry blob) > env > default. - const modelName = model || foundryModel || process.env.LLM_MODEL || "gpt-4.1"; + const modelName = model || process.env.LLM_MODEL || "gpt-4.1"; const request = buildTaskPromptRequest( { description, existingPrompt }, @@ -165,26 +158,7 @@ export async function generateTaskPrompt( modelName, ); - const response = await postAdaptiveChatCompletion({ - endpoint, - model: request.model, - messages: request.messages, - temperature: request.temperature, - maxTokens: request.max_tokens, - send: (body) => llm.path("/chat/completions").post({ body }), - }); - - if (isUnexpected(response)) { - const errBody = response.body as any; - throw new Error( - `LLM request failed: ${errBody?.error?.message || response.status}`, - ); - } - - const content = response.body.choices?.[0]?.message?.content; - if (!content) { - throw new Error("LLM returned empty response"); - } + const content = await completePortalLlm(request, model); return parseTaskPromptResponse(content); } diff --git a/apps/portal/src/components/CriteriaWizardStep2.test.tsx b/apps/portal/src/components/CriteriaWizardStep2.test.tsx index ca1cbb78a..62ed70aa0 100644 --- a/apps/portal/src/components/CriteriaWizardStep2.test.tsx +++ b/apps/portal/src/components/CriteriaWizardStep2.test.tsx @@ -9,6 +9,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { CriteriaWizardStep2 } from "./CriteriaWizardStep2"; import type { CriteriaWizardState } from "@/hooks/useCriteriaWizard"; import type { CriteriaDocument } from "@/types"; +import { PORTAL_AI_REGISTRATION_GUIDANCE } from "@/lib/portal-ai-copy"; // The picker fetches the full criteria list via api.listCriteria. const CRITERIA: CriteriaDocument[] = [ @@ -43,7 +44,7 @@ function Harness({ initialChildren?: string[]; parentCandidates?: boolean; childCandidates?: boolean; - generationError?: Error; + generationError?: unknown; }) { const [dependsOn, setDependsOn] = useState(initialParents); const [acceptedChildren, setAcceptedChildren] = useState(initialChildren); @@ -174,4 +175,14 @@ describe("CriteriaWizardStep2 — generation errors", () => { ), ).toBeTruthy(); }); + + it("shows Copilot SDK registration guidance when the API error has no message", async () => { + renderStep2({ generationError: { status: 503 } }); + + expect( + await screen.findByText( + `AI generation failed — ${PORTAL_AI_REGISTRATION_GUIDANCE}`, + ), + ).toBeTruthy(); + }); }); diff --git a/apps/portal/src/components/CriteriaWizardStep2.tsx b/apps/portal/src/components/CriteriaWizardStep2.tsx index aa94d3a43..7c65e62a3 100644 --- a/apps/portal/src/components/CriteriaWizardStep2.tsx +++ b/apps/portal/src/components/CriteriaWizardStep2.tsx @@ -6,6 +6,7 @@ import { Label } from "@/components/ui/label"; import { Textarea } from "@/components/ui/textarea"; import { Badge } from "@/components/ui/badge"; import { Separator } from "@/components/ui/separator"; +import { PORTAL_AI_REGISTRATION_GUIDANCE } from "@/lib/portal-ai-copy"; import { CriteriaPicker } from "@/components/CriteriaPicker"; import { HelpTooltip } from "@/components/HelpTooltip"; import { gatesSatisfyInvariant, GATE_METADATA, orderGateIds } from "@/lib/gates"; @@ -170,7 +171,7 @@ export function CriteriaWizardStep2({ wizard }: CriteriaWizardStep2Props) {

AI generation failed — {generateMutation.error instanceof Error ? generateMutation.error.message - : "register an Azure AI Foundry or GitHub Models key at /secrets/keys/new, or write your prompt manually"} + : PORTAL_AI_REGISTRATION_GUIDANCE}

)} diff --git a/apps/portal/src/components/PromptFeatureWizard.tsx b/apps/portal/src/components/PromptFeatureWizard.tsx index 46a90db34..38fd14aa1 100644 --- a/apps/portal/src/components/PromptFeatureWizard.tsx +++ b/apps/portal/src/components/PromptFeatureWizard.tsx @@ -4,6 +4,7 @@ import { useState, useMemo, useCallback } from "react"; import { useMutation, useQueryClient } from "@tanstack/react-query"; import { api } from "@/lib/api"; +import { PORTAL_AI_REGISTRATION_GUIDANCE } from "@/lib/portal-ai-copy"; import { Button } from "@/components/ui/button"; import { Card, CardContent } from "@/components/ui/card"; import { Input } from "@/components/ui/input"; @@ -362,7 +363,7 @@ export function PromptFeatureWizard({ {generateMutation.isError && (

- AI generation failed — {generateMutation.error instanceof Error ? generateMutation.error.message : "register an Azure AI Foundry or GitHub Models key at /secrets/keys/new, or write your prompt manually"} + AI generation failed — {generateMutation.error instanceof Error ? generateMutation.error.message : PORTAL_AI_REGISTRATION_GUIDANCE}

)} diff --git a/apps/portal/src/lib/portal-ai-copy.ts b/apps/portal/src/lib/portal-ai-copy.ts new file mode 100644 index 000000000..a55f9836c --- /dev/null +++ b/apps/portal/src/lib/portal-ai-copy.ts @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +export const PORTAL_AI_REGISTRATION_GUIDANCE = + "Portal AI requires Azure AI Foundry or a classic PAT/OAuth token with Copilot SDK capability registered at /secrets/keys/new. GitHub Models is supported only as a legacy fallback; you can also write your prompt manually."; diff --git a/apps/portal/src/pages/CreateToken.test.ts b/apps/portal/src/pages/CreateToken.test.ts index 5131d8252..a8d657eed 100644 --- a/apps/portal/src/pages/CreateToken.test.ts +++ b/apps/portal/src/pages/CreateToken.test.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. import { describe, expect, it } from "vitest"; -import { buildFoundryCredentialValue } from "./CreateToken.js"; +import { buildFoundryCredentialValue, KEY_INSTRUCTIONS } from "./CreateToken.js"; describe("Foundry credential value", () => { it("stores endpoint, key, and model without request compatibility fields", () => { @@ -21,3 +21,32 @@ describe("Foundry credential value", () => { }); }); }); + +describe("Portal AI token registration guidance", () => { + it("recommends classic PAT Copilot SDK capability for Portal AI", () => { + expect(KEY_INSTRUCTIONS["github-pat-classic"].steps.join(" ")).toContain( + "enable Portal AI through the Copilot SDK", + ); + expect(KEY_INSTRUCTIONS["github-pat-classic"].note).toContain( + "recommended GitHub credential for Portal AI", + ); + }); + + it("describes GitHub Models as a legacy fallback", () => { + expect(KEY_INSTRUCTIONS["github-pat-fine-grained"].note).toContain( + "legacy GitHub Models", + ); + expect(KEY_INSTRUCTIONS["github-oauth"].note).toContain( + "GitHub Models remains a legacy fallback", + ); + }); + + it("documents Portal AI provider precedence for Foundry registration", () => { + expect(KEY_INSTRUCTIONS["azure-ai-foundry"].note).toContain( + "Foundry environment credentials take first priority", + ); + expect(KEY_INSTRUCTIONS["azure-ai-foundry"].note).toContain( + "registered Foundry keys, Copilot SDK credentials", + ); + }); +}); diff --git a/apps/portal/src/pages/CreateToken.tsx b/apps/portal/src/pages/CreateToken.tsx index f7bdfee82..309ed93e5 100644 --- a/apps/portal/src/pages/CreateToken.tsx +++ b/apps/portal/src/pages/CreateToken.tsx @@ -26,37 +26,37 @@ import { toast } from "sonner"; import { useCommandEnter } from "@/hooks/useCommandEnter"; import { KbdBadge } from "@/components/KbdBadge"; -const KEY_INSTRUCTIONS: Record = { +export const KEY_INSTRUCTIONS: Record = { "github-pat-classic": { steps: [ "Go to GitHub → Settings → Developer settings → Personal access tokens → Tokens (classic)", "Click 'Generate new token (classic)'", - "Select scopes: 'copilot' (for Copilot SDK/CLI/VS Code) and/or 'repo' as needed", + "Select the 'copilot' scope to enable Portal AI through the Copilot SDK (and Copilot CLI/VS Code); add 'repo' only if needed", "Set an expiration and click 'Generate token'", "Copy the token (starts with ghp_)", ], link: { label: "Open GitHub token settings", url: "https://github.com/settings/tokens" }, - note: "Classic PATs cannot access GitHub Models. Use a fine-grained PAT with models:read for that.", + note: "A classic PAT with an active Copilot license is the recommended GitHub credential for Portal AI. It provides the copilot-sdk capability; GitHub Models is only a legacy fallback and requires a different token type.", }, "github-pat-fine-grained": { steps: [ "Go to GitHub → Settings → Developer settings → Personal access tokens → Fine-grained tokens", "Click 'Generate new token'", "Set a token name, expiration, and resource owner", - "Under Permissions, add 'Models' → Read access (for GitHub Models)", + "Under Permissions, add 'Models' → Read access only if you need the legacy GitHub Models fallback", "Click 'Generate token'", "Copy the token (starts with github_pat_)", ], link: { label: "Open GitHub token settings", url: "https://github.com/settings/personal-access-tokens" }, - note: "Fine-grained PATs support GitHub Models via the models:read permission. They do not support Copilot SDK.", + note: "Fine-grained PATs support only the legacy GitHub Models path via models:read. They do not provide the Copilot SDK capability; use a classic PAT or OAuth token for Portal AI.", }, "github-oauth": { steps: [ "Obtain a GitHub OAuth token via an OAuth App flow (authorization code grant)", - "The token should have the 'copilot' scope for Copilot capabilities", + "Ensure the token has Copilot access so validation grants the copilot-sdk capability used by Portal AI", "Copy the OAuth access token", ], - note: "OAuth tokens typically support all GitHub capabilities including Copilot SDK, CLI, VS Code, and GitHub Models.", + note: "OAuth tokens with an active Copilot license can enable Portal AI through the Copilot SDK, as well as Copilot CLI and VS Code. GitHub Models remains a legacy fallback.", }, "github-oauth-cookie-state": { steps: [ @@ -93,7 +93,7 @@ const KEY_INSTRUCTIONS: Record = { }; export const KEY_CAPABILITY_DESCRIPTIONS: Record = { - "github-models": "Access AI models hosted on GitHub (GPT-4o, Claude, etc.)", + "github-models": "Use the legacy GitHub Models fallback for Portal AI", "github-public-api": "Read public repository contents (used for skill discovery and resolution)", "copilot-models": "List models available via the Copilot API (OAuth only, PATs rejected)", - "copilot-sdk": "Use the Copilot SDK to make LLM requests programmatically", + "copilot-sdk": "Enable Portal AI and other programmatic LLM requests through GitHub Copilot", "copilot-cli": "Run GitHub Copilot in the CLI for code suggestions", "claude-code-cli": "Run Claude Code as an agentic coding assistant", "anthropic-api": "Access the Anthropic REST API (model scanning, direct API calls)", diff --git a/docs/architecture/token-manager.md b/docs/architecture/token-manager.md index 544d09667..0123668c2 100644 --- a/docs/architecture/token-manager.md +++ b/docs/architecture/token-manager.md @@ -92,12 +92,12 @@ may contain a `requestProfile` field; the parser accepts and ignores it. | Capability | Description | |------------|-------------| -| `github-models` | Access to GitHub Models API (GPT-4o, etc.) | +| `github-models` | Access to the legacy GitHub Models fallback | | `github-public-api` | Read-only access to the GitHub REST API for public repos (skill discovery / resolution) | -| `copilot-sdk` | GitHub Copilot SDK integration | +| `copilot-sdk` | GitHub Copilot SDK integration, including Portal AI | | `copilot-cli` | GitHub Copilot CLI authentication | | `claude-code-cli` | Anthropic Claude Code CLI | -| `azure-ai-inference` | Chat-completion inference against an Azure AI Foundry deployment (used by the portal's AI features) | +| `azure-ai-inference` | Chat-completion inference against an Azure AI Foundry deployment (used by Portal AI) | `github-public-api` is granted to **any** valid GitHub bearer token (PAT classic, PAT fine-grained, OAuth, scopeless OAuth) since public-repo reads require no scopes. @@ -114,9 +114,9 @@ The API's discovery endpoint uses this chain via the `github-api-token` helper t | Token Type | Permissions / Scope | How to Obtain | Validity | GitHub Models | Copilot SDK | Copilot CLI | Claude Code CLI | VS Code Copilot | |------------|---------------------|---------------|----------|:-------------:|:-----------:|:-----------:|:---------------:|:---------------:| -| **GitHub PAT (classic)** `ghp_` | `copilot` | Settings → Tokens (classic) | No expiry or custom | ❌ | ✅¹ | ✅¹ | ❌ | ✅¹ | -| **GitHub PAT (fine-grained)** `github_pat_` | `models:read` | Settings → Fine-grained tokens | Max 1 year | ✅ | ❌ | ❌ | ❌ | ❌ | -| **GitHub OAuth** `gho_` | (all via OAuth flow) | `gh auth login` → `gh auth token` | Until revoked | ✅ | ✅¹ | ✅¹ | ❌ | ✅¹ | +| **GitHub PAT (classic)** `ghp_` | `copilot` | Settings → Tokens (classic) | No expiry or custom | ❌ | ✅¹ (Portal AI) | ✅¹ | ❌ | ✅¹ | +| **GitHub PAT (fine-grained)** `github_pat_` | `models:read` | Settings → Fine-grained tokens | Max 1 year | ✅ (legacy Portal AI fallback) | ❌ | ❌ | ❌ | ❌ | +| **GitHub OAuth** `gho_` | (all via OAuth flow) | `gh auth login` → `gh auth token` | Until revoked | ✅ (legacy fallback) | ✅¹ (Portal AI) | ✅¹ | ❌ | ✅¹ | | **GitHub OAuth cookie state** | (browser session) | Browser DevTools → cookies | Session-bound | ❌ | ❌ | ❌ | ❌ | ✅² | | **Anthropic API Key** `sk-ant-` | (full access) | console.anthropic.com | Until revoked | ❌ | ❌ | ❌ | ✅ | ❌ | @@ -250,11 +250,9 @@ if (result) { ### LLM Module Integration -The API's portal-LLM modules (`llm.ts`, `prompt-feature-llm.ts`, -`task-prompt-llm.ts`) all go through a shared -`acquireInferenceClient()` helper in `apps/api/src/llm-token.ts`. The -helper resolves a chat-completions client in this order, returning the -first source that succeeds: +The API's Portal AI modules (`llm.ts`, `prompt-feature-llm.ts`, and +`task-prompt-llm.ts`) share one provider-selection path. It selects the first +configured provider in this order: 1. **Azure AI Foundry via env vars** — `AZURE_AI_INFERENCE_ENDPOINT` + `AZURE_AI_INFERENCE_API_KEY`. @@ -266,40 +264,61 @@ first source that succeeds: (endpoint + key + model), not just the API key. The capability `azure-ai-inference` is derived from any registered `azure-ai-foundry` key. -3. **GitHub Models** — `GITHUB_MODELS_API_KEY` env var, then - `TokenManagerClient.acquireToken("github-models")`, then `GITHUB_TOKEN`. - -Each successful acquisition logs a single line: - -``` -[llm-token] inference provider: source=… via=… endpoint=… model=… -``` - -`via` distinguishes `azure-ai-foundry-env`, -`azure-ai-foundry-token-manager`, `github-models-env`, -`github-models-token-manager`, and `github-token`. - -When none of the three tiers is configured, the helper throws a single -"LLM not configured" error that the route handlers convert into a 503 -with an actionable message pointing at `/secrets/keys/new`. - -**No automatic failover at request time.** The chain only steps down -when the predecessor returns *nothing* (env var unset, no key -registered). It does **not** step down when the predecessor returns a -credential that then 4xx/5xx's on the chat-completion call — that error -propagates to the user verbatim. This is intentional: silent fallback -would mask a misconfigured higher-priority backend (e.g. a wrong Foundry -deployment name) and the operator would never realise they were paying -the slower fallback's latency. - -```typescript -import { acquireInferenceClient } from "./llm-token.js"; - -const { client, model: foundryModel } = await acquireInferenceClient(); -const modelName = explicit || foundryModel || process.env.LLM_MODEL || "gpt-4.1"; -await client.path("/chat/completions").post({ body: { messages, model: modelName, … } }); -``` +3. **GitHub Copilot SDK** — `GITHUB_TOKEN` or a registered classic PAT/OAuth + token with the `copilot-sdk` capability. This is the preferred + GitHub-backed provider. +4. **GitHub Models (legacy fallback)** — `GITHUB_MODELS_API_KEY`, a registered + `github-models` token, or the legacy `GITHUB_TOKEN` path. + +Each successful acquisition logs the selected source. GitHub Models remains +available for compatibility, but new deployments should use Foundry or Copilot +SDK credentials. + +### Copilot SDK request isolation + +Portal AI bounds Copilot SDK concurrency with a fixed-size client pool (default +maximum: two clients; minimum: zero). Pool acquisition, runtime startup, +response generation, idle reaping, and shutdown all have explicit timeouts so +requests and child processes do not wait indefinitely. A request borrows one +client, creates a **one-shot** session, sends one prompt, then disconnects and +deletes the session in `finally` before returning the client to the pool. +Session cleanup therefore runs after success, provider errors, and timeouts. + +The session is intentionally isolated from coding-agent behavior: + +- The Copilot client uses `mode: "empty"`. Its SDK session uses an empty tool + set and does not receive MCP servers, skills, custom agents, extensions, or + repository/workspace context. +- Only the system and user prompts required by the Portal AI operation are + sent. +- The Copilot CLI child process receives a sanitized environment containing + only the variables required for runtime and authentication; unrelated Scope + service secrets are not forwarded. +- The session is not reused across requests, users, or projects. + +The adapter preserves the operation's system and user prompts. Copilot model +resolution is: explicit request override → `PORTAL_COPILOT_MODEL` → `LLM_MODEL` +→ automatic selection from the authenticated account's available models. Each +pooled client discovers its models at startup and prefers `gpt-5.4-mini`, +`gpt-5.4`, `gpt-5.1`, then `gpt-5-mini`; if none is present it uses the first +listed model. It fails client startup if Copilot returns no models. Copilot +therefore does not inherit the REST-only `gpt-4.1` default when no override is +configured. + +The Copilot SDK session API does not expose the REST chat-completions +`temperature` or maximum-token controls, so those remain specific to the +Foundry and legacy GitHub Models REST paths. Those REST providers continue to +default to `gpt-4.1`. + +When no provider is configured, route handlers return HTTP 503 with actionable +registration guidance. + +**No automatic failover at request time.** Provider precedence is evaluated +only while selecting an available credential. Once a provider is selected, an +authentication error, timeout, rate limit, or inference failure is returned to +the caller; Scope does not retry the request through a lower-priority provider. +This prevents a broken Foundry or Copilot configuration from being hidden by +the legacy GitHub Models fallback. The legacy `acquireGitHubModelsToken()` helper still exists for callers -that specifically need a GitHub Models bearer token; it follows the same -1→3 chain restricted to the GitHub Models tiers. +that specifically need a GitHub Models bearer token. diff --git a/docs/responsible-ai-faq.md b/docs/responsible-ai-faq.md index d2aa48364..eb72b1ffb 100644 --- a/docs/responsible-ai-faq.md +++ b/docs/responsible-ai-faq.md @@ -44,7 +44,11 @@ Scope uses AI in several places, depending on deployment configuration: | Report generation | A report-generation worker can use an LLM to analyze completed runs and produce Markdown reports and reusable insights. | | Model discovery | Model scanners can discover available capabilities from supported providers such as Copilot and Anthropic integrations. | -For its LLM-assisted platform features (Judge, criteria/prompt/report generation), Scope routes inference through a unified backend that supports Azure AI Foundry and GitHub Models. Coding-agent surfaces reach their own model backends directly: GitHub Copilot via the GitHub Copilot SDK/APIs, and Claude Code via Anthropic APIs. The available providers depend on the deployment and registered credentials. +Portal AI provider precedence is Azure AI Foundry environment credentials, Azure AI Foundry credentials from Token Manager, GitHub Copilot SDK credentials from Token Manager, and then GitHub Models as a legacy fallback. Once a provider is selected, Scope does not fail over to another provider after an authentication, timeout, rate-limit, or inference error. Judge and report generation use their separately configured Copilot SDK integrations, while coding-agent surfaces reach their own model backends directly. + +Portal AI's Copilot SDK path uses a bounded client pool and a fresh one-shot session for each request. The client runs in empty mode; the session has no tools, MCP servers, skills, custom agents, extensions, or repository context, receives only the operation's system and user prompts, and is disconnected and deleted before its client returns to the pool. The child process receives a sanitized environment rather than the API service's complete environment. These controls reduce cross-request context and credential exposure, but generated content still requires human review. + +The Copilot SDK path preserves the Portal operation's system prompt, user prompt, and model selection. REST-specific temperature and maximum-token controls are not exposed by the SDK session API, so they apply only to the Foundry and legacy GitHub Models REST paths. ## Inputs and outputs @@ -108,6 +112,7 @@ Users should: | Insecure generated code | Scope is an evaluation tool; users remain responsible for code review, testing, linting, and security scanning before using generated code. | | Secret exposure in captured traffic | Supported HAR capture paths redact sensitive headers such as authorization, API key, cookie, and set-cookie headers before storage. | | Credential misuse | Provider credentials are managed through a Token Manager with capability-based token acquisition and Key Vault-backed storage in production-style deployments. | +| Cross-request Portal AI context or tool access | Copilot SDK requests use one-shot sessions with empty tools and no MCP, skills, or workspace context; sessions are destroyed after each request and the child process receives a sanitized environment. | | Prompt injection | Users should treat repository content, prompts, MCP data, and external inputs as untrusted. Scope’s Judge uses read-only tools, and outputs should be reviewed before action. | | Overreliance on AI-generated reports | Reports are generated from run data and should be reviewed by a human before being used for decisions. | | Cross-project data confusion | Scope uses explicit project IDs for scoped entities and fails fast when project context is missing. Deployment owners should still implement and verify access control for shared environments. | diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b792f3736..d4a29c36a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -95,6 +95,9 @@ importers: '@azure/storage-queue': specifier: ^12.24.0 version: 12.29.0 + '@github/copilot-sdk': + specifier: 1.0.1 + version: 1.0.1(typescript@5.9.3) cors: specifier: ^2.8.5 version: 2.8.6 @@ -128,6 +131,9 @@ importers: tar-stream: specifier: ^3.1.7 version: 3.1.7 + tarn: + specifier: 3.0.2 + version: 3.0.2 telemetry: specifier: workspace:* version: link:../../packages/telemetry @@ -1287,7 +1293,7 @@ packages: engines: {node: '>=6.9.0'} '@babel/runtime@7.29.7': - resolution: {integrity: sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==} + resolution: {integrity: sha1-EgIkUMRaTabY2Ch7GKT/Ldsj92g=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@babel/runtime/-/runtime-7.29.7.tgz} engines: {node: '>=6.9.0'} '@babel/template@7.28.6': @@ -1322,7 +1328,7 @@ packages: engines: {node: '>=18'} '@colors/colors@1.5.0': - resolution: {integrity: sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==} + resolution: {integrity: sha1-u1BFecHK6SPmV2pPXaQ9Jfl729k=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@colors/colors/-/colors-1.5.0.tgz} engines: {node: '>=0.1.90'} '@colors/colors@1.6.0': @@ -1333,166 +1339,166 @@ packages: resolution: {integrity: sha512-3Xgkay0Hubq1hA67IW2vM3YhX4TQgjOFW2TydB0ytAL97zOZI9xr/9vqCjo31bK1qUDNEdlKYLYHd8KR9YSCCw==} '@emnapi/core@1.9.2': - resolution: {integrity: sha512-UC+ZhH3XtczQYfOlu3lNEkdW/p4dsJ1r/bP7H8+rhao3TTTMO1ATq/4DdIi23XuGoFY+Cz0JmCbdVl0hz9jZcA==} + resolution: {integrity: sha1-OHAmXs/8c1LQHq1i2Ng9g1ii0DQ=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@emnapi/core/-/core-1.9.2.tgz} '@emnapi/runtime@1.9.2': - resolution: {integrity: sha512-3U4+MIWHImeyu1wnmVygh5WlgfYDtyf0k8AbLhMFxOipihf6nrWC4syIm/SwEeec0mNSafiiNnMJwbza/Is6Lw==} + resolution: {integrity: sha1-i0aaPbFggXytsd6QUCEanR6oT6I=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@emnapi/runtime/-/runtime-1.9.2.tgz} '@emnapi/wasi-threads@1.2.1': - resolution: {integrity: sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==} + resolution: {integrity: sha1-KP7SGhuhznl8RKBwq8lNQvOuhUg=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz} '@esbuild/aix-ppc64@0.28.1': - resolution: {integrity: sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==} + resolution: {integrity: sha1-egGo0uwvuy2seK2tCbD6eB5Agr4=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz} engines: {node: '>=18'} cpu: [ppc64] os: [aix] '@esbuild/android-arm64@0.28.1': - resolution: {integrity: sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==} + resolution: {integrity: sha1-tUCifRTkr9BYSWpNvsTT9BTbEQo=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz} engines: {node: '>=18'} cpu: [arm64] os: [android] '@esbuild/android-arm@0.28.1': - resolution: {integrity: sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==} + resolution: {integrity: sha1-cEvSl95tdi3lTqu+r79V9nVqvi8=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/android-arm/-/android-arm-0.28.1.tgz} engines: {node: '>=18'} cpu: [arm] os: [android] '@esbuild/android-x64@0.28.1': - resolution: {integrity: sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==} + resolution: {integrity: sha1-0csWbTSw+/D+irRgpVlPJKN4cB4=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/android-x64/-/android-x64-0.28.1.tgz} engines: {node: '>=18'} cpu: [x64] os: [android] '@esbuild/darwin-arm64@0.28.1': - resolution: {integrity: sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==} + resolution: {integrity: sha1-EDSyZFf8iGNo/mG70J9lP2r6jlQ=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz} engines: {node: '>=18'} cpu: [arm64] os: [darwin] '@esbuild/darwin-x64@0.28.1': - resolution: {integrity: sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==} + resolution: {integrity: sha1-ZVVqQyoeTXIDLYIYwZMvzKGkl3I=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz} engines: {node: '>=18'} cpu: [x64] os: [darwin] '@esbuild/freebsd-arm64@0.28.1': - resolution: {integrity: sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==} + resolution: {integrity: sha1-LmHgWS+QMNfj2uGO4l68U1kYrvY=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz} engines: {node: '>=18'} cpu: [arm64] os: [freebsd] '@esbuild/freebsd-x64@0.28.1': - resolution: {integrity: sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==} + resolution: {integrity: sha1-yV7CiZWe+AecTcqBeh4sS+Zrm9M=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz} engines: {node: '>=18'} cpu: [x64] os: [freebsd] '@esbuild/linux-arm64@0.28.1': - resolution: {integrity: sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==} + resolution: {integrity: sha1-QLIhdd2gYYLz7oFBGGxf8wTEpxc=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz} engines: {node: '>=18'} cpu: [arm64] os: [linux] '@esbuild/linux-arm@0.28.1': - resolution: {integrity: sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==} + resolution: {integrity: sha1-wJoPZ5F1kqwN6JKpvk04FN69Kmw=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz} engines: {node: '>=18'} cpu: [arm] os: [linux] '@esbuild/linux-ia32@0.28.1': - resolution: {integrity: sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==} + resolution: {integrity: sha1-pYD5xnZ5eDOJHlGfx6EzfIr9jbM=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz} engines: {node: '>=18'} cpu: [ia32] os: [linux] '@esbuild/linux-loong64@0.28.1': - resolution: {integrity: sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==} + resolution: {integrity: sha1-RkUs8yHcf56Rwvp4Cla7Vuec1os=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz} engines: {node: '>=18'} cpu: [loong64] os: [linux] '@esbuild/linux-mips64el@0.28.1': - resolution: {integrity: sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==} + resolution: {integrity: sha1-QhGzGE3WYI9T3LIuOfXTTuCIUsg=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz} engines: {node: '>=18'} cpu: [mips64el] os: [linux] '@esbuild/linux-ppc64@0.28.1': - resolution: {integrity: sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==} + resolution: {integrity: sha1-aXhXwqYcubC2u2ZS5AwdxeHKjl0=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz} engines: {node: '>=18'} cpu: [ppc64] os: [linux] '@esbuild/linux-riscv64@0.28.1': - resolution: {integrity: sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==} + resolution: {integrity: sha1-0ZKUPrFGpArExkl9DPe+NbmGvwg=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz} engines: {node: '>=18'} cpu: [riscv64] os: [linux] '@esbuild/linux-s390x@0.28.1': - resolution: {integrity: sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==} + resolution: {integrity: sha1-rOoDVtoODrwI+Xz3ucLkAeHmSNw=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz} engines: {node: '>=18'} cpu: [s390x] os: [linux] '@esbuild/linux-x64@0.28.1': - resolution: {integrity: sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==} + resolution: {integrity: sha1-bww84MtkxTS3DExF7LLBbTTjXf0=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz} engines: {node: '>=18'} cpu: [x64] os: [linux] '@esbuild/netbsd-arm64@0.28.1': - resolution: {integrity: sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==} + resolution: {integrity: sha1-i813B3oNzjN4tXT+2ybSolO3PTY=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz} engines: {node: '>=18'} cpu: [arm64] os: [netbsd] '@esbuild/netbsd-x64@0.28.1': - resolution: {integrity: sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==} + resolution: {integrity: sha1-5/sqAemcgwyU5mI82f77TI+1g0c=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz} engines: {node: '>=18'} cpu: [x64] os: [netbsd] '@esbuild/openbsd-arm64@0.28.1': - resolution: {integrity: sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==} + resolution: {integrity: sha1-xSkJNy24uG4sVeBaiUADO1Zgo7I=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz} engines: {node: '>=18'} cpu: [arm64] os: [openbsd] '@esbuild/openbsd-x64@0.28.1': - resolution: {integrity: sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==} + resolution: {integrity: sha1-xCe5vlpkwmL/mn63C1+7qt9EbGw=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz} engines: {node: '>=18'} cpu: [x64] os: [openbsd] '@esbuild/openharmony-arm64@0.28.1': - resolution: {integrity: sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==} + resolution: {integrity: sha1-3JsUe6yi5sSzyFVxdB70hgpIkJc=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz} engines: {node: '>=18'} cpu: [arm64] os: [openharmony] '@esbuild/sunos-x64@0.28.1': - resolution: {integrity: sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==} + resolution: {integrity: sha1-zoZtEt8TwV5MmfBzo9Rm9uBkmzo=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz} engines: {node: '>=18'} cpu: [x64] os: [sunos] '@esbuild/win32-arm64@0.28.1': - resolution: {integrity: sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==} + resolution: {integrity: sha1-dGjjaS0B1inVlB5dg4F7uA+eObQ=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz} engines: {node: '>=18'} cpu: [arm64] os: [win32] '@esbuild/win32-ia32@0.28.1': - resolution: {integrity: sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==} + resolution: {integrity: sha1-pbwAY/sryrbQ7WPyoVN5WLwmnsY=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz} engines: {node: '>=18'} cpu: [ia32] os: [win32] '@esbuild/win32-x64@0.28.1': - resolution: {integrity: sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==} + resolution: {integrity: sha1-EAZO5E9DR7kMmgK0Rrv4CpFjKxI=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz} engines: {node: '>=18'} cpu: [x64] os: [win32] @@ -1513,40 +1519,40 @@ packages: resolution: {integrity: sha512-aGTxbpbg8/b5JfU1HXSrbH3wXZuLPJcNEcZQFMxLs3oSzgtVu6nFPkbbGGUvBcUjKV2YyB9Wxxabo+HEH9tcRQ==} '@github/copilot-darwin-arm64@1.0.63': - resolution: {integrity: sha512-z6CMBxNDlKvT6bvOpqhu4M2bhb0daEbVwSe9SN9WfDUJbt7bpoL7OKKas428iyPSWHoL2WXwxSsy/FjIwSLV6w==} + resolution: {integrity: sha1-JrBj4X6yDxCJqZnJQLqJ43REL3w=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@github/copilot-darwin-arm64/-/copilot-darwin-arm64-1.0.63.tgz} cpu: [arm64] os: [darwin] hasBin: true '@github/copilot-darwin-x64@1.0.63': - resolution: {integrity: sha512-YKd7cXZgAGxhudzrtWdWh2NS35p2G5bV22Gz3jhEyBTqmq45o4sD4OwO87+UpkvM+3nZpwsHaLd3a+ILYX6OXg==} + resolution: {integrity: sha1-4FoUrHF3rwxZkI9QPFXHVyDk8WM=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@github/copilot-darwin-x64/-/copilot-darwin-x64-1.0.63.tgz} cpu: [x64] os: [darwin] hasBin: true '@github/copilot-linux-arm64@1.0.63': - resolution: {integrity: sha512-A3DOeEfmsJH9j1N+QLc7WXmESBskbezmhDyhyAJcHkw0ngRbKctuWQf/evUHFMh/kgwy1Lr/+9jXJm3NZqr0MA==} + resolution: {integrity: sha1-uwl1BhTJsbIAOBht8xC4xjsg8Z0=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@github/copilot-linux-arm64/-/copilot-linux-arm64-1.0.63.tgz} cpu: [arm64] os: [linux] libc: [glibc] hasBin: true '@github/copilot-linux-x64@1.0.63': - resolution: {integrity: sha512-OMKfZJRoDaJOV7vuWX/nFPNdLa9/H+nhajdE83v4YT9mKLXr86aWrkXE3pPoDYsKWvgQFHg4APA6oZPao0Fyow==} + resolution: {integrity: sha1-mfEe3Z6+0A7S+WjLdIy4jr3Yatk=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@github/copilot-linux-x64/-/copilot-linux-x64-1.0.63.tgz} cpu: [x64] os: [linux] libc: [glibc] hasBin: true '@github/copilot-linuxmusl-arm64@1.0.63': - resolution: {integrity: sha512-jcIo6B3uHgcOluNfUHp+6atShKKrXYBPLaRyF6aDT699lwI83gW9KTDuEvDs5FDg8qWsWFfOl+al2dkWDYD3CQ==} + resolution: {integrity: sha1-MwVeIr4C01C+A4MZAIE8vNleops=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@github/copilot-linuxmusl-arm64/-/copilot-linuxmusl-arm64-1.0.63.tgz} cpu: [arm64] os: [linux] libc: [musl] hasBin: true '@github/copilot-linuxmusl-x64@1.0.63': - resolution: {integrity: sha512-BEdBbEF3fG7VqXzuaAY4JtmbdGSkpJFeb2ZQYaMpq7OP3aS7ssGe1cCX8ehZNegcMM/eb4GC6PXNXsvl3X/PAQ==} + resolution: {integrity: sha1-yawZHApLv+Rt7d33UydDp3RWFgA=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@github/copilot-linuxmusl-x64/-/copilot-linuxmusl-x64-1.0.63.tgz} cpu: [x64] os: [linux] libc: [musl] @@ -1557,13 +1563,13 @@ packages: engines: {node: ^20.19.0 || >=22.12.0} '@github/copilot-win32-arm64@1.0.63': - resolution: {integrity: sha512-7FqUwOmtoeBoOn4zkKQqRL+WGFwektVRSr5Po2FvPAbKxGXGyFXApZTmRLqVcHhMKDRzMb8KLST1LU1TMTY/wg==} + resolution: {integrity: sha1-uVsv2JKvG4n2Rjs1Hn/UbeJ69e4=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@github/copilot-win32-arm64/-/copilot-win32-arm64-1.0.63.tgz} cpu: [arm64] os: [win32] hasBin: true '@github/copilot-win32-x64@1.0.63': - resolution: {integrity: sha512-RC/6y9KHdw/YRCrCEksF2RzbeblfBUNE7bkYZxygaQGYThuv1GeZL2YD2jVqxC2LxKzsUmWGvwEMxerfR6pmeQ==} + resolution: {integrity: sha1-TX+fgJDAF35LFEk0FTyn+u46mlc=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@github/copilot-win32-x64/-/copilot-win32-x64-1.0.63.tgz} cpu: [x64] os: [win32] hasBin: true @@ -1678,7 +1684,7 @@ packages: engines: {node: '>=18'} '@napi-rs/wasm-runtime@1.1.4': - resolution: {integrity: sha512-3NQNNgA1YSlJb/kMH1ildASP9HW7/7kYnRI2szWJaofaS1hWmbGI4H+d3+22aGzXXN9IJ+n+GiFVcGipJP18ow==} + resolution: {integrity: sha1-pGu/7cKXUbcXDF0jvB2O6MfjweE=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.4.tgz} peerDependencies: '@emnapi/core': ^1.7.1 '@emnapi/runtime': ^1.7.1 @@ -2524,143 +2530,143 @@ packages: engines: {node: ^18.19.0 || >=20.6.0} '@os-theme/darwin-arm64@0.0.8': - resolution: {integrity: sha512-gMsOs+8Ju396a5yyMWigkbA0dMTxD78U3HzG3mlpiAyn6hfd5dbyI4VGP+sfTB82KGgWLzIhWWTFX5UYY6iX0A==} + resolution: {integrity: sha1-sG3LDuYjSm2+TEIvAzfG+tgR69c=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@os-theme/darwin-arm64/-/darwin-arm64-0.0.8.tgz} cpu: [arm64] os: [darwin] '@os-theme/linux-x64@0.0.8': - resolution: {integrity: sha512-zvjmBUiSQPjM1RbhpsfCDYMJxW4eLlGmkFPnpteC/03X2lz6CjiX2hfbN2EWLxXjNnIje3Jqaen8IsqEnWrRBg==} + resolution: {integrity: sha1-3CMQdNJpXo/KYtTjEWsAGPSphME=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@os-theme/linux-x64/-/linux-x64-0.0.8.tgz} cpu: [x64] os: [linux] '@os-theme/win32-x64@0.0.8': - resolution: {integrity: sha512-N3yxKNbVl2IBa/ncDuq55QhwqwUjnYLJxDKMEmYeJbLIV950qZNojPw3scXA6PbfxPZfIiRa8iz1pzNg9XxP8w==} + resolution: {integrity: sha1-yMPomy3GVjNS29If0Uwl8WtzR5o=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@os-theme/win32-x64/-/win32-x64-0.0.8.tgz} cpu: [x64] os: [win32] '@oxc-parser/binding-android-arm-eabi@0.127.0': - resolution: {integrity: sha512-0LC7ye4hvqbIKxAzThzvswgHLFu2AURKzYLeSVvLdu2TBOYWQDmHnTqPLeA597BcUCxiLqLsS4CJ5uoI5WYWCQ==} + resolution: {integrity: sha1-t155YknuIvYy5A6UJ0bEv2SM7pI=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-parser/binding-android-arm-eabi/-/binding-android-arm-eabi-0.127.0.tgz} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [android] '@oxc-parser/binding-android-arm64@0.127.0': - resolution: {integrity: sha512-b5jtVTH6AU5CJXHNdj7Jj9IEiR9yVjjnwHzPJhGyHGPdcsZSzBCkS9GBbV33niRMvKthDwQRFRJfI4a+k4PvYg==} + resolution: {integrity: sha1-4mRGf+OfgAGPYvoNroLbC4AmBEQ=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-parser/binding-android-arm64/-/binding-android-arm64-0.127.0.tgz} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [android] '@oxc-parser/binding-darwin-arm64@0.127.0': - resolution: {integrity: sha512-obCE8B7ISKkJidjlhv9xRGJPOSDG2Yu6PRga9Ruaz35uintHxbp1Ki/Yc71wx4rj3Edrm0a1kzG1TAwit0wFpg==} + resolution: {integrity: sha1-BXbTUQnADcxidyALouyntH4H8bE=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-parser/binding-darwin-arm64/-/binding-darwin-arm64-0.127.0.tgz} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [darwin] '@oxc-parser/binding-darwin-x64@0.127.0': - resolution: {integrity: sha512-JL6Xb5IwPQT8rUzlpsX7E+AgfcdNklXNPFp8pjCQQ5MQOQo5rtEB2ui+3Hgg9Sn7Y9Egj6YOLLiHhLpdAe12Aw==} + resolution: {integrity: sha1-76G6SQdaoxj/VAocL4pEIBdBcgY=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-parser/binding-darwin-x64/-/binding-darwin-x64-0.127.0.tgz} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [darwin] '@oxc-parser/binding-freebsd-x64@0.127.0': - resolution: {integrity: sha512-SDQ/3MQFw58fqQz3Z1PhSKFF3JoCF4gmlNjziDm8X02tTahCw0qJbd7FGPDKw1i4VTBZene9JPyC3mHtSvi+wA==} + resolution: {integrity: sha1-gXujxQjXUdlNbm/Yavad2qJ9pTE=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-parser/binding-freebsd-x64/-/binding-freebsd-x64-0.127.0.tgz} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [freebsd] '@oxc-parser/binding-linux-arm-gnueabihf@0.127.0': - resolution: {integrity: sha512-Av+D1MIqzV0YMGPT9we2SIZaMKD7Cxs4CvXSx/yxaWHewZjYEjScpOf5igc8IILASViw4WTnjlwUdI1KzVtDHQ==} + resolution: {integrity: sha1-scMJbGVHcZmEgDFu8Q0eXSntx5s=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-parser/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.127.0.tgz} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [linux] '@oxc-parser/binding-linux-arm-musleabihf@0.127.0': - resolution: {integrity: sha512-Cs2fdJ8cPpFdeebj6p4dag8A4+56hPvZ0AhQQzlaLswGz1tz7bXt1nETLeorrM9+AMcWFFkqxcXwDGfTVidY8g==} + resolution: {integrity: sha1-xEqPEObJA2hYJa6/Eon8IIau1h4=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-parser/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.127.0.tgz} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [linux] '@oxc-parser/binding-linux-arm64-gnu@0.127.0': - resolution: {integrity: sha512-qdOfTcT6SY8gsJrrV92uyEUyjqMGPpIB5JZUG6QN5dukYd+7/j0kX6MwK1DgQj39jtUYixxPiaRUiEN1+0CXgQ==} + resolution: {integrity: sha1-YcJFq/q29jBFkVtcnPp9M1rXxEA=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-parser/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.127.0.tgz} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] libc: [glibc] '@oxc-parser/binding-linux-arm64-musl@0.127.0': - resolution: {integrity: sha512-EoTCZneNFU/P2qrpEM+RHmQwt+CvDkyGESG6qhr7KaegXLZwePfbrkCDfAk8/rhxbDUVGsZILX+2tqPzFtoFWA==} + resolution: {integrity: sha1-NYu9kOXIW2w1El9ab/CE4JtpTAQ=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-parser/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.127.0.tgz} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] libc: [musl] '@oxc-parser/binding-linux-ppc64-gnu@0.127.0': - resolution: {integrity: sha512-zALjmZYgxFLHjXeudcDF0xFGNydTAtkAeXAr2EuC17ywCyFxcmQra4w0BMde0Yi/re4Bi4iwEoEXtYN7l6eBLQ==} + resolution: {integrity: sha1-t+p7Ub9U20xCgZGH92DgadQz2sM=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-parser/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.127.0.tgz} engines: {node: ^20.19.0 || >=22.12.0} cpu: [ppc64] os: [linux] libc: [glibc] '@oxc-parser/binding-linux-riscv64-gnu@0.127.0': - resolution: {integrity: sha512-fPP8M6zQLS7Jz7o9d5ArUSuAuSK3e+WCYVrCpdzeCOejidtZExJ9tjhDrAd3HEPqARBCPmdpqxESPFqy44vkBQ==} + resolution: {integrity: sha1-OjsQ0WCYjfULu81jHGrznePdRR0=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-parser/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.127.0.tgz} engines: {node: ^20.19.0 || >=22.12.0} cpu: [riscv64] os: [linux] libc: [glibc] '@oxc-parser/binding-linux-riscv64-musl@0.127.0': - resolution: {integrity: sha512-7IcC4Ao02oGpfnjt+X/oF4U2mllo2qoSkw5xxiXNKL9MCTsTiAC6616beOuehdxGcnz1bRoPC1RQ2f1GQDdN+g==} + resolution: {integrity: sha1-N4fTfh0KFe4jn1FhAphQAyGzFzA=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-parser/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.127.0.tgz} engines: {node: ^20.19.0 || >=22.12.0} cpu: [riscv64] os: [linux] libc: [musl] '@oxc-parser/binding-linux-s390x-gnu@0.127.0': - resolution: {integrity: sha512-pbXIhiNFHoqWeqDNLiJ9JkpHz1IM9k4DXa66x+1GTWMG7iLxtkXgE53iiuKSXwmk3zIYmaPVfBvgcAhS583K4Q==} + resolution: {integrity: sha1-txoWy7oRWkaWSY+RSbxUzE4d+c0=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-parser/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.127.0.tgz} engines: {node: ^20.19.0 || >=22.12.0} cpu: [s390x] os: [linux] libc: [glibc] '@oxc-parser/binding-linux-x64-gnu@0.127.0': - resolution: {integrity: sha512-MYCguB9RvBvlSd6gbuNI7QwiLoCCAlGnlRJFPrzLI6U1/9wkC/WK6LtBAUln55H1Ctqw45PWmqrobKoMhsYQzQ==} + resolution: {integrity: sha1-cVJ90ChLpyfTWpPIQckRkq8+vew=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-parser/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.127.0.tgz} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] libc: [glibc] '@oxc-parser/binding-linux-x64-musl@0.127.0': - resolution: {integrity: sha512-5eY0B/bxf1xIUxb4NOTvOI3KWtBQfPWYyKAzgcrCt0mDibSZygVpO1Pz8bkeiSZ5Jj9+M09dkggG3H8I5d0Uyg==} + resolution: {integrity: sha1-FoMK+ksAHzSc67k+ErJ45yYByz8=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-parser/binding-linux-x64-musl/-/binding-linux-x64-musl-0.127.0.tgz} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] libc: [musl] '@oxc-parser/binding-openharmony-arm64@0.127.0': - resolution: {integrity: sha512-Gld0ajrFTUXNtdw20fVBuTQx66FA75nIVg+//pPfR3sXkuABB4mTBhl3r9JNzrJpgW//qiwxf0nWXUWGJSL3UQ==} + resolution: {integrity: sha1-pBxx0knLWX3DVwOOscvjznMkU/g=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-parser/binding-openharmony-arm64/-/binding-openharmony-arm64-0.127.0.tgz} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [openharmony] '@oxc-parser/binding-wasm32-wasi@0.127.0': - resolution: {integrity: sha512-T6KVD7rhLzFlwGRXMnxUFfkCZD8FHnb968wVXW1mXzgRFc5RNXOBY2mPPDZ77x5Ln76ltLMgtPg0cOkU1NSrEQ==} + resolution: {integrity: sha1-se/NtDOzDtSjrZEvoD2jg0vUhF0=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-parser/binding-wasm32-wasi/-/binding-wasm32-wasi-0.127.0.tgz} engines: {node: ^20.19.0 || >=22.12.0} cpu: [wasm32] '@oxc-parser/binding-win32-arm64-msvc@0.127.0': - resolution: {integrity: sha512-Ujvw4X+LD1CCGULcsQcvb4YNVoBGqt+JHgNNzGGaCImELiZLk477ifUH53gIbE7EKd933NdTi25JWEr9K2HwXw==} + resolution: {integrity: sha1-titeMoEmMj1Brh7nrclVN8TEQjo=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-parser/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.127.0.tgz} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [win32] '@oxc-parser/binding-win32-ia32-msvc@0.127.0': - resolution: {integrity: sha512-0cwxKO7KHQQQfo4Uf4B2SQrhgm+cJaP9OvFFhx52Tkg4bezsacu83GB2/In5bC415Ueeym+kXdnge/57rbSfTw==} + resolution: {integrity: sha1-2sMN5pcdvmOqVyK+mkzAcP08ZQ4=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-parser/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.127.0.tgz} engines: {node: ^20.19.0 || >=22.12.0} cpu: [ia32] os: [win32] '@oxc-parser/binding-win32-x64-msvc@0.127.0': - resolution: {integrity: sha512-rOrnSQSCbhI2kowr9XxE7m9a8oQXnBHjnS6j95LxxAnEZ0+Fz20WlRXG4ondQb+ejjt2KOsa65sE6++L6kUd+w==} + resolution: {integrity: sha1-ot+HmwgD9ys1CnVnNlzuW4l47fA=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-parser/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.127.0.tgz} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [win32] @@ -2669,110 +2675,110 @@ packages: resolution: {integrity: sha512-aIYXQBo4lCbO4z0R3FHeucQHpF46l2LbMdxRvqvuRuW2OxdnSkcng5B8+K12spgLDj93rtN3+J2Vac/TIO+ciQ==} '@oxc-resolver/binding-android-arm-eabi@11.19.1': - resolution: {integrity: sha512-aUs47y+xyXHUKlbhqHUjBABjvycq6YSD7bpxSW7vplUmdzAlJ93yXY6ZR0c1o1x5A/QKbENCvs3+NlY8IpIVzg==} + resolution: {integrity: sha1-xEEgqlEE6ZHkqZabsLgWJjpvS8E=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-resolver/binding-android-arm-eabi/-/binding-android-arm-eabi-11.19.1.tgz} cpu: [arm] os: [android] '@oxc-resolver/binding-android-arm64@11.19.1': - resolution: {integrity: sha512-oolbkRX+m7Pq2LNjr/kKgYeC7bRDMVTWPgxBGMjSpZi/+UskVo4jsMU3MLheZV55jL6c3rNelPl4oD60ggYmqA==} + resolution: {integrity: sha1-ushqnyr9qc1hgeodFUZEjfV5t0A=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-resolver/binding-android-arm64/-/binding-android-arm64-11.19.1.tgz} cpu: [arm64] os: [android] '@oxc-resolver/binding-darwin-arm64@11.19.1': - resolution: {integrity: sha512-nUC6d2i3R5B12sUW4O646qD5cnMXf2oBGPLIIeaRfU9doJRORAbE2SGv4eW6rMqhD+G7nf2Y8TTJTLiiO3Q/dQ==} + resolution: {integrity: sha1-a921t3nN4AA9rg1wO/c04VNpaPE=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-resolver/binding-darwin-arm64/-/binding-darwin-arm64-11.19.1.tgz} cpu: [arm64] os: [darwin] '@oxc-resolver/binding-darwin-x64@11.19.1': - resolution: {integrity: sha512-cV50vE5+uAgNcFa3QY1JOeKDSkM/9ReIcc/9wn4TavhW/itkDGrXhw9jaKnkQnGbjJ198Yh5nbX/Gr2mr4Z5jQ==} + resolution: {integrity: sha1-BVMxQ4pzsh01f975R7nAbskEYQQ=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-resolver/binding-darwin-x64/-/binding-darwin-x64-11.19.1.tgz} cpu: [x64] os: [darwin] '@oxc-resolver/binding-freebsd-x64@11.19.1': - resolution: {integrity: sha512-xZOQiYGFxtk48PBKff+Zwoym7ScPAIVp4c14lfLxizO2LTTTJe5sx9vQNGrBymrf/vatSPNMD4FgsaaRigPkqw==} + resolution: {integrity: sha1-c16+U7rX6TUlWg6wcvdKQ/+wMsQ=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-resolver/binding-freebsd-x64/-/binding-freebsd-x64-11.19.1.tgz} cpu: [x64] os: [freebsd] '@oxc-resolver/binding-linux-arm-gnueabihf@11.19.1': - resolution: {integrity: sha512-lXZYWAC6kaGe/ky2su94e9jN9t6M0/6c+GrSlCqL//XO1cxi5lpAhnJYdyrKfm0ZEr/c7RNyAx3P7FSBcBd5+A==} + resolution: {integrity: sha1-IHL2eeWoSF88D+mPO9V9/UZHoZ0=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-resolver/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-11.19.1.tgz} cpu: [arm] os: [linux] '@oxc-resolver/binding-linux-arm-musleabihf@11.19.1': - resolution: {integrity: sha512-veG1kKsuK5+t2IsO9q0DErYVSw2azvCVvWHnfTOS73WE0STdLLB7Q1bB9WR+yHPQM76ASkFyRbogWo1GR1+WbQ==} + resolution: {integrity: sha1-100KpHOMyfKvniAVy97QpdNGENw=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-resolver/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-11.19.1.tgz} cpu: [arm] os: [linux] '@oxc-resolver/binding-linux-arm64-gnu@11.19.1': - resolution: {integrity: sha512-heV2+jmXyYnUrpUXSPugqWDRpnsQcDm2AX4wzTuvgdlZfoNYO0O3W2AVpJYaDn9AG4JdM6Kxom8+foE7/BcSig==} + resolution: {integrity: sha1-BqqaMw7NpGG+aTiWnBxLZ+lpQZ4=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-resolver/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-11.19.1.tgz} cpu: [arm64] os: [linux] libc: [glibc] '@oxc-resolver/binding-linux-arm64-musl@11.19.1': - resolution: {integrity: sha512-jvo2Pjs1c9KPxMuMPIeQsgu0mOJF9rEb3y3TdpsrqwxRM+AN6/nDDwv45n5ZrUnQMsdBy5gIabioMKnQfWo9ew==} + resolution: {integrity: sha1-6VHLluf3KouD1jedGdTiYk/KjW4=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-resolver/binding-linux-arm64-musl/-/binding-linux-arm64-musl-11.19.1.tgz} cpu: [arm64] os: [linux] libc: [musl] '@oxc-resolver/binding-linux-ppc64-gnu@11.19.1': - resolution: {integrity: sha512-vLmdNxWCdN7Uo5suays6A/+ywBby2PWBBPXctWPg5V0+eVuzsJxgAn6MMB4mPlshskYbppjpN2Zg83ArHze9gQ==} + resolution: {integrity: sha1-tzo9lbm3p02KqV3e/Aa2q3PYr8Y=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-resolver/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-11.19.1.tgz} cpu: [ppc64] os: [linux] libc: [glibc] '@oxc-resolver/binding-linux-riscv64-gnu@11.19.1': - resolution: {integrity: sha512-/b+WgR+VTSBxzgOhDO7TlMXC1ufPIMR6Vj1zN+/x+MnyXGW7prTLzU9eW85Aj7Th7CCEG9ArCbTeqxCzFWdg2w==} + resolution: {integrity: sha1-qdKbfdw1GCTKJcSqnebNRc/7XR8=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-resolver/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-11.19.1.tgz} cpu: [riscv64] os: [linux] libc: [glibc] '@oxc-resolver/binding-linux-riscv64-musl@11.19.1': - resolution: {integrity: sha512-YlRdeWb9j42p29ROh+h4eg/OQ3dTJlpHSa+84pUM9+p6i3djtPz1q55yLJhgW9XfDch7FN1pQ/Vd6YP+xfRIuw==} + resolution: {integrity: sha1-D8u4/woJ4cYcvNKggDlGrsDLmzs=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-resolver/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-11.19.1.tgz} cpu: [riscv64] os: [linux] libc: [musl] '@oxc-resolver/binding-linux-s390x-gnu@11.19.1': - resolution: {integrity: sha512-EDpafVOQWF8/MJynsjOGFThcqhRHy417sRyLfQmeiamJ8qVhSKAn2Dn2VVKUGCjVB9C46VGjhNo7nOPUi1x6uA==} + resolution: {integrity: sha1-G34y32O/Mj5ex2X1NtK+FPulF4c=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-resolver/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-11.19.1.tgz} cpu: [s390x] os: [linux] libc: [glibc] '@oxc-resolver/binding-linux-x64-gnu@11.19.1': - resolution: {integrity: sha512-NxjZe+rqWhr+RT8/Ik+5ptA3oz7tUw361Wa5RWQXKnfqwSSHdHyrw6IdcTfYuml9dM856AlKWZIUXDmA9kkiBQ==} + resolution: {integrity: sha1-SrJ1TxuVIaPQ8AyyUdi2YDIi8vQ=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-resolver/binding-linux-x64-gnu/-/binding-linux-x64-gnu-11.19.1.tgz} cpu: [x64] os: [linux] libc: [glibc] '@oxc-resolver/binding-linux-x64-musl@11.19.1': - resolution: {integrity: sha512-cM/hQwsO3ReJg5kR+SpI69DMfvNCp+A/eVR4b4YClE5bVZwz8rh2Nh05InhwI5HR/9cArbEkzMjcKgTHS6UaNw==} + resolution: {integrity: sha1-kcOumGAEExcmx4uprvYVTaqcI44=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-resolver/binding-linux-x64-musl/-/binding-linux-x64-musl-11.19.1.tgz} cpu: [x64] os: [linux] libc: [musl] '@oxc-resolver/binding-openharmony-arm64@11.19.1': - resolution: {integrity: sha512-QF080IowFB0+9Rh6RcD19bdgh49BpQHUW5TajG1qvWHvmrQznTZZjYlgE2ltLXyKY+qs4F/v5xuX1XS7Is+3qA==} + resolution: {integrity: sha1-MF/maEP0uiSZ/azxqsADQbWWgZg=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-resolver/binding-openharmony-arm64/-/binding-openharmony-arm64-11.19.1.tgz} cpu: [arm64] os: [openharmony] '@oxc-resolver/binding-wasm32-wasi@11.19.1': - resolution: {integrity: sha512-w8UCKhX826cP/ZLokXDS6+milN8y4X7zidsAttEdWlVoamTNf6lhBJldaWr3ukTDiye7s4HRcuPEPOXNC432Vg==} + resolution: {integrity: sha1-Dohesf1ugFgs99+3VmR/vEJ8zhs=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-resolver/binding-wasm32-wasi/-/binding-wasm32-wasi-11.19.1.tgz} engines: {node: '>=14.0.0'} cpu: [wasm32] '@oxc-resolver/binding-win32-arm64-msvc@11.19.1': - resolution: {integrity: sha512-nJ4AsUVZrVKwnU/QRdzPCCrO0TrabBqgJ8pJhXITdZGYOV28TIYystV1VFLbQ7DtAcaBHpocT5/ZJnF78YJPtQ==} + resolution: {integrity: sha1-LhSHHGB1Ug6/0xLrnGoV51Mje5A=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-resolver/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-11.19.1.tgz} cpu: [arm64] os: [win32] '@oxc-resolver/binding-win32-ia32-msvc@11.19.1': - resolution: {integrity: sha512-EW+ND5q2Tl+a3pH81l1QbfgbF3HmqgwLfDfVithRFheac8OTcnbXt/JxqD2GbDkb7xYEqy1zNaVFRr3oeG8npA==} + resolution: {integrity: sha1-toSZLdD8bo+IBTv6hjJ7ky5MxIY=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-resolver/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-11.19.1.tgz} cpu: [ia32] os: [win32] '@oxc-resolver/binding-win32-x64-msvc@11.19.1': - resolution: {integrity: sha512-6hIU3RQu45B+VNTY4Ru8ppFwjVS/S5qwYyGhBotmjxfEKk41I2DlGtRfGJndZ5+6lneE2pwloqunlOyZuX/XAw==} + resolution: {integrity: sha1-pI3M3LCDPaSVdXmw4xRmZAeZA2Q=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@oxc-resolver/binding-win32-x64-msvc/-/binding-win32-x64-msvc-11.19.1.tgz} cpu: [x64] os: [win32] @@ -2780,7 +2786,7 @@ packages: resolution: {integrity: sha512-XO7cAxhnTZl0Yggq6jOgjiOHhbgcO4NqFqwSmQpjK3b6TEE6Uj/jfSk6wzYyemh3+I0sHirKSetjQwn5cZktFw==} '@pkgjs/parseargs@0.11.0': - resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==} + resolution: {integrity: sha1-p36nQvqyV3UUVDTrHSMoz1ATrDM=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@pkgjs/parseargs/-/parseargs-0.11.0.tgz} engines: {node: '>=14'} '@protobufjs/aspromise@1.1.2': @@ -3484,140 +3490,140 @@ packages: optional: true '@rollup/rollup-android-arm-eabi@4.60.1': - resolution: {integrity: sha512-d6FinEBLdIiK+1uACUttJKfgZREXrF0Qc2SmLII7W2AD8FfiZ9Wjd+rD/iRuf5s5dWrr1GgwXCvPqOuDquOowA==} + resolution: {integrity: sha1-BD8UVxYjRSkFLvnhzh2Ef/vp5nQ=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.60.1.tgz} cpu: [arm] os: [android] '@rollup/rollup-android-arm64@4.60.1': - resolution: {integrity: sha512-YjG/EwIDvvYI1YvYbHvDz/BYHtkY4ygUIXHnTdLhG+hKIQFBiosfWiACWortsKPKU/+dUwQQCKQM3qrDe8c9BA==} + resolution: {integrity: sha1-Aj4b0UbnUZCH39nosp5M+fjs01w=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.60.1.tgz} cpu: [arm64] os: [android] '@rollup/rollup-darwin-arm64@4.60.1': - resolution: {integrity: sha512-mjCpF7GmkRtSJwon+Rq1N8+pI+8l7w5g9Z3vWj4T7abguC4Czwi3Yu/pFaLvA3TTeMVjnu3ctigusqWUfjZzvw==} + resolution: {integrity: sha1-Vcy1SHwCQZlUxXp6gGAohdYW4e4=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.60.1.tgz} cpu: [arm64] os: [darwin] '@rollup/rollup-darwin-x64@4.60.1': - resolution: {integrity: sha512-haZ7hJ1JT4e9hqkoT9R/19XW2QKqjfJVv+i5AGg57S+nLk9lQnJ1F/eZloRO3o9Scy9CM3wQ9l+dkXtcBgN5Ew==} + resolution: {integrity: sha1-JUtlQEsUSIyDIl6IuIGTdq1xp4Q=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.60.1.tgz} cpu: [x64] os: [darwin] '@rollup/rollup-freebsd-arm64@4.60.1': - resolution: {integrity: sha512-czw90wpQq3ZsAVBlinZjAYTKduOjTywlG7fEeWKUA7oCmpA8xdTkxZZlwNJKWqILlq0wehoZcJYfBvOyhPTQ6w==} + resolution: {integrity: sha1-Y3f/OMBSx2/K/7eyco0xcv5nb+Y=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.60.1.tgz} cpu: [arm64] os: [freebsd] '@rollup/rollup-freebsd-x64@4.60.1': - resolution: {integrity: sha512-KVB2rqsxTHuBtfOeySEyzEOB7ltlB/ux38iu2rBQzkjbwRVlkhAGIEDiiYnO2kFOkJp+Z7pUXKyrRRFuFUKt+g==} + resolution: {integrity: sha1-ujkCMJ0Ijq9xObkW8JtxQLKLQG0=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.60.1.tgz} cpu: [x64] os: [freebsd] '@rollup/rollup-linux-arm-gnueabihf@4.60.1': - resolution: {integrity: sha512-L+34Qqil+v5uC0zEubW7uByo78WOCIrBvci69E7sFASRl0X7b/MB6Cqd1lky/CtcSVTydWa2WZwFuWexjS5o6g==} + resolution: {integrity: sha1-4BG5oUY4Jn5TtEYoboONva9T8Wc=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.60.1.tgz} cpu: [arm] os: [linux] libc: [glibc] '@rollup/rollup-linux-arm-musleabihf@4.60.1': - resolution: {integrity: sha512-n83O8rt4v34hgFzlkb1ycniJh7IR5RCIqt6mz1VRJD6pmhRi0CXdmfnLu9dIUS6buzh60IvACM842Ffb3xd6Gg==} + resolution: {integrity: sha1-C86c6aAJSQq9KP2SLdl+1SExGv4=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.60.1.tgz} cpu: [arm] os: [linux] libc: [musl] '@rollup/rollup-linux-arm64-gnu@4.60.1': - resolution: {integrity: sha512-Nql7sTeAzhTAja3QXeAI48+/+GjBJ+QmAH13snn0AJSNL50JsDqotyudHyMbO2RbJkskbMbFJfIJKWA6R1LCJQ==} + resolution: {integrity: sha1-b2z7vzJPu0zv8hOr338yL9RdJf8=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.60.1.tgz} cpu: [arm64] os: [linux] libc: [glibc] '@rollup/rollup-linux-arm64-musl@4.60.1': - resolution: {integrity: sha512-+pUymDhd0ys9GcKZPPWlFiZ67sTWV5UU6zOJat02M1+PiuSGDziyRuI/pPue3hoUwm2uGfxdL+trT6Z9rxnlMA==} + resolution: {integrity: sha1-98s+7K6pwVHvdzQq8F84rpJL95U=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.60.1.tgz} cpu: [arm64] os: [linux] libc: [musl] '@rollup/rollup-linux-loong64-gnu@4.60.1': - resolution: {integrity: sha512-VSvgvQeIcsEvY4bKDHEDWcpW4Yw7BtlKG1GUT4FzBUlEKQK0rWHYBqQt6Fm2taXS+1bXvJT6kICu5ZwqKCnvlQ==} + resolution: {integrity: sha1-SZv6xrtmn9iLtmQ1e/a+mWoouS8=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.60.1.tgz} cpu: [loong64] os: [linux] libc: [glibc] '@rollup/rollup-linux-loong64-musl@4.60.1': - resolution: {integrity: sha512-4LqhUomJqwe641gsPp6xLfhqWMbQV04KtPp7/dIp0nzPxAkNY1AbwL5W0MQpcalLYk07vaW9Kp1PBhdpZYYcEw==} + resolution: {integrity: sha1-En36wIdkdkOWu+BEU8VF04o6tRg=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.60.1.tgz} cpu: [loong64] os: [linux] libc: [musl] '@rollup/rollup-linux-ppc64-gnu@4.60.1': - resolution: {integrity: sha512-tLQQ9aPvkBxOc/EUT6j3pyeMD6Hb8QF2BTBnCQWP/uu1lhc9AIrIjKnLYMEroIz/JvtGYgI9dF3AxHZNaEH0rw==} + resolution: {integrity: sha1-anL02VhSqsGDJsW/cIOT6POkG3A=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.60.1.tgz} cpu: [ppc64] os: [linux] libc: [glibc] '@rollup/rollup-linux-ppc64-musl@4.60.1': - resolution: {integrity: sha512-RMxFhJwc9fSXP6PqmAz4cbv3kAyvD1etJFjTx4ONqFP9DkTkXsAMU4v3Vyc5BgzC+anz7nS/9tp4obsKfqkDHg==} + resolution: {integrity: sha1-uoZ0ZmsA1vkGbLmldxqEMMNNLeY=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.60.1.tgz} cpu: [ppc64] os: [linux] libc: [musl] '@rollup/rollup-linux-riscv64-gnu@4.60.1': - resolution: {integrity: sha512-QKgFl+Yc1eEk6MmOBfRHYF6lTxiiiV3/z/BRrbSiW2I7AFTXoBFvdMEyglohPj//2mZS4hDOqeB0H1ACh3sBbg==} + resolution: {integrity: sha1-F8w4sqceMCVHytKbz3jQ2yYYySI=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.60.1.tgz} cpu: [riscv64] os: [linux] libc: [glibc] '@rollup/rollup-linux-riscv64-musl@4.60.1': - resolution: {integrity: sha512-RAjXjP/8c6ZtzatZcA1RaQr6O1TRhzC+adn8YZDnChliZHviqIjmvFwHcxi4JKPSDAt6Uhf/7vqcBzQJy0PDJg==} + resolution: {integrity: sha1-42pB4ti9JHMxvVz8E7jJUdM0VKI=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.60.1.tgz} cpu: [riscv64] os: [linux] libc: [musl] '@rollup/rollup-linux-s390x-gnu@4.60.1': - resolution: {integrity: sha512-wcuocpaOlaL1COBYiA89O6yfjlp3RwKDeTIA0hM7OpmhR1Bjo9j31G1uQVpDlTvwxGn2nQs65fBFL5UFd76FcQ==} + resolution: {integrity: sha1-FocmXx9L3qBybHYaWMLbmTNgnWg=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.60.1.tgz} cpu: [s390x] os: [linux] libc: [glibc] '@rollup/rollup-linux-x64-gnu@4.60.1': - resolution: {integrity: sha512-77PpsFQUCOiZR9+LQEFg9GClyfkNXj1MP6wRnzYs0EeWbPcHs02AXu4xuUbM1zhwn3wqaizle3AEYg5aeoohhg==} + resolution: {integrity: sha1-Vqag2QdvKgWpdgMUk7JKIN3MDnc=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.60.1.tgz} cpu: [x64] os: [linux] libc: [glibc] '@rollup/rollup-linux-x64-musl@4.60.1': - resolution: {integrity: sha512-5cIATbk5vynAjqqmyBjlciMJl1+R/CwX9oLk/EyiFXDWd95KpHdrOJT//rnUl4cUcskrd0jCCw3wpZnhIHdD9w==} + resolution: {integrity: sha1-vCQOu1uf2NQcqKgMtFhFLowYfg8=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.60.1.tgz} cpu: [x64] os: [linux] libc: [musl] '@rollup/rollup-openbsd-x64@4.60.1': - resolution: {integrity: sha512-cl0w09WsCi17mcmWqqglez9Gk8isgeWvoUZ3WiJFYSR3zjBQc2J5/ihSjpl+VLjPqjQ/1hJRcqBfLjssREQILw==} + resolution: {integrity: sha1-b4DUigBsSy/6dyTpWj4z9pdYcq8=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.60.1.tgz} cpu: [x64] os: [openbsd] '@rollup/rollup-openharmony-arm64@4.60.1': - resolution: {integrity: sha512-4Cv23ZrONRbNtbZa37mLSueXUCtN7MXccChtKpUnQNgF010rjrjfHx3QxkS2PI7LqGT5xXyYs1a7LbzAwT0iCA==} + resolution: {integrity: sha1-j2229w0KSKvYM7JjzW3T5xmcTA4=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.60.1.tgz} cpu: [arm64] os: [openharmony] '@rollup/rollup-win32-arm64-msvc@4.60.1': - resolution: {integrity: sha512-i1okWYkA4FJICtr7KpYzFpRTHgy5jdDbZiWfvny21iIKky5YExiDXP+zbXzm3dUcFpkEeYNHgQ5fuG236JPq0g==} + resolution: {integrity: sha1-tomJv6gV0LPU4wLs2QvadEQ4sXc=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.60.1.tgz} cpu: [arm64] os: [win32] '@rollup/rollup-win32-ia32-msvc@4.60.1': - resolution: {integrity: sha512-u09m3CuwLzShA0EYKMNiFgcjjzwqtUMLmuCJLeZWjjOYA3IT2Di09KaxGBTP9xVztWyIWjVdsB2E9goMjZvTQg==} + resolution: {integrity: sha1-wJjkUzjFDyLxsohHY1TwJbdGKFs=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.60.1.tgz} cpu: [ia32] os: [win32] '@rollup/rollup-win32-x64-gnu@4.60.1': - resolution: {integrity: sha512-k+600V9Zl1CM7eZxJgMyTUzmrmhB/0XZnF4pRypKAlAgxmedUA+1v9R+XOFv56W4SlHEzfeMtzujLJD22Uz5zg==} + resolution: {integrity: sha1-LJ4VvhVbedBZmZU7FzeykDhC6QM=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.60.1.tgz} cpu: [x64] os: [win32] '@rollup/rollup-win32-x64-msvc@4.60.1': - resolution: {integrity: sha512-lWMnixq/QzxyhTV6NjQJ4SFo1J6PvOX8vUx5Wb4bBPsEb+8xZ89Bz6kOXpfXj9ak9AHTQVQzlgzBEc1SyM27xQ==} + resolution: {integrity: sha1-I7hgET6fh+6gFdH6OkJApStC/NQ=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.60.1.tgz} cpu: [x64] os: [win32] @@ -3713,7 +3719,7 @@ packages: react: ^18 || ^19 '@testing-library/dom@10.4.1': - resolution: {integrity: sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==} + resolution: {integrity: sha1-1ET4qInppG6aO087iOD8s++2z5U=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@testing-library/dom/-/dom-10.4.1.tgz} engines: {node: '>=18'} '@testing-library/jest-dom@6.9.1': @@ -3742,13 +3748,13 @@ packages: '@testing-library/dom': '>=7.21.4' '@tybys/wasm-util@0.10.2': - resolution: {integrity: sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg==} + resolution: {integrity: sha1-ErOhsz2x+crU3f8fYEq33QC/Rk4=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@tybys/wasm-util/-/wasm-util-0.10.2.tgz} '@types/adm-zip@0.5.7': resolution: {integrity: sha512-DNEs/QvmyRLurdQPChqq0Md4zGvPwHerAJYWk9l2jCbD1VPpnzRJorOdiq4zsw09NFbYnhfsoEhWtxIzXpn2yw==} '@types/aria-query@5.0.4': - resolution: {integrity: sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==} + resolution: {integrity: sha1-GjHD03iFDSd42rtjdNA23LpLpwg=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@types/aria-query/-/aria-query-5.0.4.tgz} '@types/aws-lambda@8.10.162': resolution: {integrity: sha1-WJz+zdo6mW6b3yCnOiaggRyvtUk=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@types/aws-lambda/-/aws-lambda-8.10.162.tgz} @@ -4114,7 +4120,7 @@ packages: engines: {node: '>=8'} ansi-styles@5.2.0: - resolution: {integrity: sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==} + resolution: {integrity: sha1-B0SWkK1Fd30ZJKwquy/IiV26g2s=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/ansi-styles/-/ansi-styles-5.2.0.tgz} engines: {node: '>=10'} ansi-styles@6.2.3: @@ -4228,7 +4234,7 @@ packages: optional: true bare-fs@4.7.2: - resolution: {integrity: sha512-aTvMFUWkBmjzKtEQMDGGDNF8bkfpD5N1b/FCwt7A3wrU4t1o/e/85Wzkluh6JlODCjqVESYCkQCdTXqZ9G7VFg==} + resolution: {integrity: sha1-D1mzF+W9vsahSJtRmgaiA80/4DU=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/bare-fs/-/bare-fs-4.7.2.tgz} engines: {bare: '>=1.16.0'} peerDependencies: bare-buffer: '*' @@ -4241,7 +4247,7 @@ packages: engines: {bare: '>=1.14.0'} bare-path@3.0.1: - resolution: {integrity: sha512-ghj2DSK/2e99a1anTVPCV4m4YIYtrbXhfM7V3D7XZLOTsybnYyaJloymGqssQc8l/or0UoDyRtNQkmkEF/ysgQ==} + resolution: {integrity: sha1-wSyBtSeTa2UOh8XQAmTVnvRYCCw=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/bare-path/-/bare-path-3.0.1.tgz} bare-stream@2.13.1: resolution: {integrity: sha512-Vp0cnjYyrEC4whYTymQ+YZi6pBpfiICZO3cfRG8sy67ZNWe951urv1x4eW1BKNngw3U+3fPYb5JQvHbCtxH7Ow==} @@ -4539,7 +4545,7 @@ packages: engines: {node: '>= 0.10'} cpu-features@0.0.10: - resolution: {integrity: sha512-9IkYqtX3YHPCzoVg1Py+o9057a3i0fp7S530UWokCSaFVTc7CwXPRiOjRjBQQ18ZCNafx78YfnG+HALxtVmOGA==} + resolution: {integrity: sha1-mq5TbbJxDHJU1+1nyzy8fSmtecU=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/cpu-features/-/cpu-features-0.0.10.tgz} engines: {node: '>=10.0.0'} crc-32@1.2.2: @@ -4759,7 +4765,7 @@ packages: engines: {node: '>=6.0.0'} dom-accessibility-api@0.5.16: - resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==} + resolution: {integrity: sha1-WnQp5gZus2ZNkR4z+w5F3o6whFM=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz} dom-accessibility-api@0.6.3: resolution: {integrity: sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==} @@ -5010,12 +5016,12 @@ packages: resolution: {integrity: sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==} fsevents@2.3.2: - resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==} + resolution: {integrity: sha1-ilJveLj99GI7cJ4Ll1xSwkwC/Ro=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/fsevents/-/fsevents-2.3.2.tgz} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} os: [darwin] fsevents@2.3.3: - resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + resolution: {integrity: sha1-ysZAd4XQNnWipeGlMFxpezR9kNY=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/fsevents/-/fsevents-2.3.3.tgz} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} os: [darwin] @@ -5459,7 +5465,7 @@ packages: react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0 lz-string@1.5.0: - resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==} + resolution: {integrity: sha1-watQ93iHtxJiEgG6n9Tjpu0JmUE=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/lz-string/-/lz-string-1.5.0.tgz} hasBin: true magic-string@0.30.21: @@ -5767,7 +5773,7 @@ packages: resolution: {integrity: sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==} nan@2.25.0: - resolution: {integrity: sha512-0M90Ag7Xn5KMLLZ7zliPWP3rT90P6PN+IzVFS0VqmnPktBk3700xUVv8Ikm9EUaUE5SDWdp/BIxdENzVznpm1g==} + resolution: {integrity: sha1-k37TReY9lIE2KnlC1JxIYNJ+6r0=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/nan/-/nan-2.25.0.tgz} nanoid@3.3.15: resolution: {integrity: sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA==} @@ -6012,7 +6018,7 @@ packages: engines: {node: '>=0.10.0'} pretty-format@27.5.1: - resolution: {integrity: sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==} + resolution: {integrity: sha1-IYGHn96lGnpYUfs52SD6pj8B2I4=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/pretty-format/-/pretty-format-27.5.1.tgz} engines: {node: ^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0} process-nextick-args@2.0.1: @@ -6092,7 +6098,7 @@ packages: resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==} react-is@17.0.2: - resolution: {integrity: sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==} + resolution: {integrity: sha1-5pHUqOnHiTZWVVOas3J2Kw77VPA=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/react-is/-/react-is-17.0.2.tgz} react-is@18.3.1: resolution: {integrity: sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==} @@ -6576,6 +6582,10 @@ packages: resolution: {integrity: sha512-56adEpPMouktRlBLXiaYFFzZ/3+JXa8P9n7WbR+ibIjtviN55mEaOkiysCnPnWm+7kkui1Dn8J9l+g6zV8731w==} engines: {node: '>=18'} + tarn@3.0.2: + resolution: {integrity: sha1-c7YUD7uIG3FVnE+L/ePZpLPSdpM=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/tarn/-/tarn-3.0.2.tgz} + engines: {node: '>=8.0.0'} + teex@1.0.1: resolution: {integrity: sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg==} @@ -6702,7 +6712,7 @@ packages: hasBin: true uglify-js@3.19.3: - resolution: {integrity: sha512-v3Xu+yuwBXisp6QYTcH4UbH+xYJXqnq2m/LtQVWKWzYc1iehYnLixoQDN9FH6/j9/oybfd6W9Ghwkl8+UMKTKQ==} + resolution: {integrity: sha1-gjFem7xvKyWIiFis0f/4RBA1t38=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/uglify-js/-/uglify-js-3.19.3.tgz} engines: {node: '>=0.8.0'} hasBin: true @@ -13436,6 +13446,8 @@ snapshots: minizlib: 3.1.0 yallist: 5.0.0 + tarn@3.0.2: {} + teex@1.0.1: dependencies: streamx: 2.27.0 From 15f5c8d366da8429f74c0d7f9f667bc94cccab6e Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Sun, 11 Oct 2026 18:25:35 +0200 Subject: [PATCH 038/210] docs: clarify Copilot SDK production tradeoffs Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: ff08bace-4f82-42b3-9451-4063717e348f --- ENV_VARIABLES.md | 14 ++++++++++++++ docs/architecture/token-manager.md | 18 ++++++++++++++++-- docs/responsible-ai-faq.md | 2 ++ 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/ENV_VARIABLES.md b/ENV_VARIABLES.md index ebdaee4e8..094576278 100644 --- a/ENV_VARIABLES.md +++ b/ENV_VARIABLES.md @@ -61,6 +61,14 @@ Foundry, the GitHub Copilot SDK, and a legacy GitHub Models fallback. The **first source that returns a credential wins**; later sources are not consulted. +The Copilot SDK provider is primarily a **desktop and simple self-hosting +convenience**: a GitHub OAuth flow can enable Portal AI without provisioning a +separate inference resource. The SDK runs a Copilot CLI child process and Scope +must maintain a bounded pool of those processes. For production deployments, +prefer Azure AI Foundry or another direct chat-completions endpoint, which +avoids subprocess lifecycle and pool-capacity overhead and exposes native +inference controls. + | # | Source | Trigger | `via` log tag | |---|--------|---------|---------------| | 1 | Azure AI Foundry via env vars | `AZURE_AI_INFERENCE_ENDPOINT` + `AZURE_AI_INFERENCE_API_KEY` both set | `azure-ai-foundry-env` | @@ -100,6 +108,12 @@ sanitized environment with only the runtime and authentication variables it needs; the API service's unrelated credentials are not forwarded. Sessions are never reused across Portal AI requests. +These controls make the SDK path practical for desktop use and smaller +self-hosted installations, but they do not remove the cost of running child +processes in the API container. Production operators should normally configure +Foundry or a direct completion endpoint instead of sizing and operating a +Copilot runtime pool. + The Copilot SDK adapter preserves the Portal operation's system prompt and user prompt. Its model resolves independently from the REST default, in this order: an explicit request override, `PORTAL_COPILOT_MODEL`, `LLM_MODEL`, then automatic diff --git a/docs/architecture/token-manager.md b/docs/architecture/token-manager.md index 0123668c2..e96bde501 100644 --- a/docs/architecture/token-manager.md +++ b/docs/architecture/token-manager.md @@ -265,8 +265,10 @@ configured provider in this order: `azure-ai-inference` is derived from any registered `azure-ai-foundry` key. 3. **GitHub Copilot SDK** — `GITHUB_TOKEN` or a registered classic PAT/OAuth - token with the `copilot-sdk` capability. This is the preferred - GitHub-backed provider. + token with the `copilot-sdk` capability. This is a convenience path for + desktop and straightforward self-hosted installations: the same GitHub + OAuth flow can enable Portal AI without a separately provisioned inference + endpoint. 4. **GitHub Models (legacy fallback)** — `GITHUB_MODELS_API_KEY`, a registered `github-models` token, or the legacy `GITHUB_TOKEN` path. @@ -274,6 +276,12 @@ Each successful acquisition logs the selected source. GitHub Models remains available for compatibility, but new deployments should use Foundry or Copilot SDK credentials. +For production deployments, prefer Foundry or another direct chat-completions +endpoint over Copilot SDK. The SDK launches Copilot CLI child processes and +requires Scope to operate a bounded client pool, whereas a direct endpoint +avoids subprocess lifecycle and pool-capacity overhead and exposes native +inference controls. + ### Copilot SDK request isolation Portal AI bounds Copilot SDK concurrency with a fixed-size client pool (default @@ -284,6 +292,12 @@ client, creates a **one-shot** session, sends one prompt, then disconnects and deletes the session in `finally` before returning the client to the pool. Session cleanup therefore runs after success, provider errors, and timeouts. +The pool exists because the SDK runtime is not in-process: every pooled client +owns a Copilot CLI child process. This tradeoff streamlines desktop setup, but +production capacity planning must account for the child processes' memory, +startup, health-check, and idle-eviction behavior. A direct inference endpoint +is therefore the recommended production architecture. + The session is intentionally isolated from coding-agent behavior: - The Copilot client uses `mode: "empty"`. Its SDK session uses an empty tool diff --git a/docs/responsible-ai-faq.md b/docs/responsible-ai-faq.md index eb72b1ffb..441dd9ea4 100644 --- a/docs/responsible-ai-faq.md +++ b/docs/responsible-ai-faq.md @@ -46,6 +46,8 @@ Scope uses AI in several places, depending on deployment configuration: Portal AI provider precedence is Azure AI Foundry environment credentials, Azure AI Foundry credentials from Token Manager, GitHub Copilot SDK credentials from Token Manager, and then GitHub Models as a legacy fallback. Once a provider is selected, Scope does not fail over to another provider after an authentication, timeout, rate-limit, or inference error. Judge and report generation use their separately configured Copilot SDK integrations, while coding-agent surfaces reach their own model backends directly. +The Portal AI Copilot SDK provider is intended as a convenience for desktop and simple self-hosted Scope installations: users can enable assistance through a GitHub OAuth flow without first provisioning an inference resource. Because the SDK launches Copilot CLI child processes and requires a bounded client pool, production deployments should prefer Azure AI Foundry or another direct completion endpoint with native inference controls and no subprocess-pool overhead. + Portal AI's Copilot SDK path uses a bounded client pool and a fresh one-shot session for each request. The client runs in empty mode; the session has no tools, MCP servers, skills, custom agents, extensions, or repository context, receives only the operation's system and user prompts, and is disconnected and deleted before its client returns to the pool. The child process receives a sanitized environment rather than the API service's complete environment. These controls reduce cross-request context and credential exposure, but generated content still requires human review. The Copilot SDK path preserves the Portal operation's system prompt, user prompt, and model selection. REST-specific temperature and maximum-token controls are not exposed by the SDK session API, so they apply only to the Foundry and legacy GitHub Models REST paths. From 8f30583dda7387f0a9cf7be396f746c20bfee633 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Sun, 11 Oct 2026 18:42:05 +0200 Subject: [PATCH 039/210] fix(api): harden Copilot pool startup Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: ff08bace-4f82-42b3-9451-4063717e348f --- apps/api/src/copilot-client-pool.test.ts | 27 ++++++++++++--- apps/api/src/copilot-client-pool.ts | 44 +++++++++++++++++------- apps/api/src/llm-token.test.ts | 12 +++++++ 3 files changed, 66 insertions(+), 17 deletions(-) diff --git a/apps/api/src/copilot-client-pool.test.ts b/apps/api/src/copilot-client-pool.test.ts index 5a557757f..3445a76ad 100644 --- a/apps/api/src/copilot-client-pool.test.ts +++ b/apps/api/src/copilot-client-pool.test.ts @@ -20,6 +20,7 @@ const mocks = vi.hoisted(() => ({ mkdtemp: vi.fn(), rm: vi.fn(), ping: vi.fn(), + models: [{ id: "test-default-model", name: "Test Default", capabilities: {} }], sessionFactory: vi.fn(), })); @@ -35,9 +36,7 @@ vi.mock("@github/copilot-sdk", () => ({ CopilotClient: class implements MockClient { start = vi.fn(async () => undefined); ping = vi.fn((message: string) => mocks.ping(message)); - listModels = vi.fn(async () => [ - { id: "test-default-model", name: "Test Default", capabilities: {} }, - ]); + listModels = vi.fn(async () => mocks.models); createSession = vi.fn((options: Record) => mocks.sessionFactory(options), ); @@ -67,7 +66,10 @@ vi.mock("shared", () => ({ withRetry: (operation: () => Promise) => operation(), })); -import { PortalCopilotClientPool } from "./copilot-client-pool.js"; +import { + CopilotCredentialUnavailableError, + PortalCopilotClientPool, +} from "./copilot-client-pool.js"; const pools: PortalCopilotClientPool[] = []; let sessionNumber = 0; @@ -109,6 +111,9 @@ beforeEach(() => { vi.clearAllMocks(); mocks.clientOptions.length = 0; mocks.clients.length = 0; + mocks.models = [ + { id: "test-default-model", name: "Test Default", capabilities: {} }, + ]; pools.length = 0; sessionNumber = 0; vi.stubEnv("PORTAL_COPILOT_POOL_SIZE", "1"); @@ -253,4 +258,18 @@ describe("PortalCopilotClientPool", () => { "Copilot SDK pool is shutting down", ); }); + + it("treats an account with no Copilot models as an unavailable credential", async () => { + mocks.models = []; + const pool = makePool(); + + await expect(complete(pool)).rejects.toBeInstanceOf( + CopilotCredentialUnavailableError, + ); + expect(mocks.clients[0].forceStop).toHaveBeenCalledOnce(); + expect(mocks.rm).toHaveBeenCalledWith( + "/scope-tests/runtime", + { recursive: true, force: true }, + ); + }); }); diff --git a/apps/api/src/copilot-client-pool.ts b/apps/api/src/copilot-client-pool.ts index 0734a81f6..4ab99ea1e 100644 --- a/apps/api/src/copilot-client-pool.ts +++ b/apps/api/src/copilot-client-pool.ts @@ -129,6 +129,19 @@ function isRetryableCopilotError(error: unknown): boolean { ].some((pattern) => text.includes(pattern)); } +function isCopilotCredentialFailure(error: unknown): boolean { + const text = errorText(error).toLowerCase(); + return [ + "authentication", + "unauthorized", + "forbidden", + "invalid token", + "not entitled", + "copilot license", + "no available models", + ].some((pattern) => text.includes(pattern)); +} + async function withTimeout( operation: Promise, timeoutMs: number, @@ -184,7 +197,12 @@ export class PortalCopilotClientPool { min: 0, max, acquireTimeoutMillis, - createTimeoutMillis: this.startupTimeoutMs, + // createResource owns the startup deadline and force-stops a partial + // client before rejecting. Keep Tarn's outer deadline longer so it never + // abandons a creator that is still cleaning up and starts a replacement + // beyond the configured pool maximum. + createTimeoutMillis: + this.startupTimeoutMs + this.shutdownTimeoutMs + 1_000, destroyTimeoutMillis: this.shutdownTimeoutMs, idleTimeoutMillis: positiveInt( "PORTAL_COPILOT_IDLE_TIMEOUT_MS", @@ -308,20 +326,14 @@ export class PortalCopilotClientPool { this.resourcesCreated += 1; try { - await withTimeout( - client.start(), - this.startupTimeoutMs, - `Copilot CLI did not start within ${this.startupTimeoutMs}ms`, - ); - await withTimeout( - client.ping("scope-portal-ai-ready"), - this.startupTimeoutMs, - `Copilot CLI did not respond within ${this.startupTimeoutMs}ms`, - ); const models = await withTimeout( - client.listModels(), + (async () => { + await client.start(); + await client.ping("scope-portal-ai-ready"); + return client.listModels(); + })(), this.startupTimeoutMs, - `Copilot model discovery did not finish within ${this.startupTimeoutMs}ms`, + `Copilot CLI startup did not finish within ${this.startupTimeoutMs}ms`, ); const preferred = [ "gpt-5.4-mini", @@ -343,6 +355,12 @@ export class PortalCopilotClientPool { } catch (error) { resource.healthy = false; await this.destroyResource(resource, true); + if (isCopilotCredentialFailure(error)) { + throw new CopilotCredentialUnavailableError( + `Copilot SDK credential cannot provide Portal AI completions: ${errorText(error)}`, + { cause: error }, + ); + } throw error; } } diff --git a/apps/api/src/llm-token.test.ts b/apps/api/src/llm-token.test.ts index f274756ab..39553c2dd 100644 --- a/apps/api/src/llm-token.test.ts +++ b/apps/api/src/llm-token.test.ts @@ -156,6 +156,18 @@ describe("completePortalLlm provider resolution", () => { expect(mocks.modelPost).toHaveBeenCalledOnce(); }); + it("uses an explicit GitHub Models key when no Copilot credential is configured", async () => { + vi.stubEnv("GITHUB_MODELS_API_KEY", "github-models-key"); + mocks.modelPost.mockResolvedValue(completion("from-github-models-env")); + + await expect(completePortalLlm(request)).resolves.toBe( + "from-github-models-env", + ); + + expect(mocks.copilotComplete).not.toHaveBeenCalled(); + expect(mocks.modelPost).toHaveBeenCalledOnce(); + }); + it("does not hide an inference failure by falling through to another provider", async () => { vi.stubEnv("AZURE_AI_INFERENCE_ENDPOINT", "https://foundry.example.test/models"); vi.stubEnv("AZURE_AI_INFERENCE_API_KEY", "foundry-key"); From 4b284135a7b638b27b0d7759482b8d9243098487 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Sun, 11 Oct 2026 18:42:26 +0200 Subject: [PATCH 040/210] fix(api): bound Copilot force-stop cleanup Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: ff08bace-4f82-42b3-9451-4063717e348f --- apps/api/src/copilot-client-pool.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/apps/api/src/copilot-client-pool.ts b/apps/api/src/copilot-client-pool.ts index 4ab99ea1e..dd8a29409 100644 --- a/apps/api/src/copilot-client-pool.ts +++ b/apps/api/src/copilot-client-pool.ts @@ -480,7 +480,13 @@ export class PortalCopilotClientPool { try { if (force) { - await resource.client.forceStop().catch(() => undefined); + await withTimeout( + resource.client.forceStop(), + this.shutdownTimeoutMs, + `Copilot CLI force-stop did not finish within ${this.shutdownTimeoutMs}ms`, + ).catch((error) => { + console.warn(`[portal-copilot-pool] force-stop failed: ${errorText(error)}`); + }); } else { const errors = await withTimeout( resource.client.stop(), @@ -495,7 +501,11 @@ export class PortalCopilotClientPool { } } catch (error) { console.warn(`[portal-copilot-pool] stop failed: ${errorText(error)}`); - await resource.client.forceStop().catch(() => undefined); + await withTimeout( + resource.client.forceStop(), + this.shutdownTimeoutMs, + `Copilot CLI force-stop did not finish within ${this.shutdownTimeoutMs}ms`, + ).catch(() => undefined); } finally { await rm(resource.rootDirectory, { recursive: true, force: true }).catch((error) => { console.warn(`[portal-copilot-pool] temp cleanup failed: ${errorText(error)}`); From a1612d4bf7d3a77d6a6d91e6c30d0a367a411a61 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Tue, 13 Oct 2026 16:26:21 +0200 Subject: [PATCH 041/210] feat(submissions): add attempt state foundation Introduce stable submission identities, deterministic request/run vectors, resumable CAS rollover with immutable history, named-handler dependency evaluation, Cosmos-safe indexes, and attempt-scoped worker claim/completion helpers. Align the observation handler identity with the pp-observations dependency contract. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 99f84f04-d3b0-40f1-a254-4dfbd21e4d87 --- apps/judge/src/agent-trajectory.test.ts | 2 +- ...observation-trajectory.integration.test.ts | 2 +- apps/portal/src/lib/enrichment.test.ts | 28 +- apps/portal/src/lib/enrichment.ts | 10 +- apps/scheduler/src/handler-dispatcher.ts | 69 +- apps/workers/post-processor/Dockerfile | 2 +- .../post-processor/handler.taxonomy.yaml | 6 +- .../src/handlers/taxonomy-handler.test.ts | 6 +- .../src/handlers/taxonomy-handler.ts | 6 +- docker-compose.yml | 4 +- docs/architecture/criteria-provider.md | 2 +- docs/architecture/post-processing.md | 37 +- .../src/034-create-submission-indexes.test.ts | 52 ++ .../034-create-submission-indexes.ts | 67 ++ .../db-migrations/src/required-migrations.ts | 1 + .../shared/src/criteria/criteria-store.ts | 2 +- packages/shared/src/index.ts | 1 + packages/shared/src/judge/judge-client.ts | 4 +- packages/shared/src/schemas/index.ts | 1 + packages/shared/src/schemas/request.ts | 4 + packages/shared/src/schemas/submission.ts | 182 +++++ .../shared/src/scripts/register-handler.ts | 30 +- packages/shared/src/submissions/index.ts | 5 + .../submission-coordinator.test.ts | 693 ++++++++++++++++++ .../src/submissions/submission-coordinator.ts | 573 +++++++++++++++ .../src/submissions/submission-state.test.ts | 155 ++++ .../src/submissions/submission-state.ts | 184 +++++ packages/shared/src/types/types.ts | 130 +++- 28 files changed, 2167 insertions(+), 91 deletions(-) create mode 100644 packages/db-migrations/src/034-create-submission-indexes.test.ts create mode 100644 packages/db-migrations/src/migrations/034-create-submission-indexes.ts create mode 100644 packages/shared/src/schemas/submission.ts create mode 100644 packages/shared/src/submissions/index.ts create mode 100644 packages/shared/src/submissions/submission-coordinator.test.ts create mode 100644 packages/shared/src/submissions/submission-coordinator.ts create mode 100644 packages/shared/src/submissions/submission-state.test.ts create mode 100644 packages/shared/src/submissions/submission-state.ts diff --git a/apps/judge/src/agent-trajectory.test.ts b/apps/judge/src/agent-trajectory.test.ts index 8bb870184..ac4d713b8 100644 --- a/apps/judge/src/agent-trajectory.test.ts +++ b/apps/judge/src/agent-trajectory.test.ts @@ -48,7 +48,7 @@ async function call( /** * Realistic ATIF blob: system + user step, then agent steps that install, - * use, and uninstall `left-pad`. Mirrors the real ATIF shape pp-taxonomy + * use, and uninstall `left-pad`. Mirrors the real ATIF shape pp-observations * downloads (steps carry their own tool_calls AND the matching * observation.results, paired by source_call_id === tool_call_id). */ diff --git a/apps/judge/src/observation-trajectory.integration.test.ts b/apps/judge/src/observation-trajectory.integration.test.ts index 066c40da3..d8b89150d 100644 --- a/apps/judge/src/observation-trajectory.integration.test.ts +++ b/apps/judge/src/observation-trajectory.integration.test.ts @@ -34,7 +34,7 @@ const hasToken = !!process.env.GITHUB_TOKEN; const JUDGE_MODEL = process.env.JUDGE_MODEL || "gpt-5.4-mini"; /** - * Realistic ATIF trajectory (the exact shape pp-taxonomy downloads and forwards + * Realistic ATIF trajectory (the exact shape pp-observations downloads and forwards * via `fromAtif`): a system + user step, then agent steps that install * `left-pad`, use it, and uninstall it before finishing. Each agent step pairs * its `tool_calls[]` with the matching same-step `observation.results[]` by diff --git a/apps/portal/src/lib/enrichment.test.ts b/apps/portal/src/lib/enrichment.test.ts index 879bc5b11..9e4b19024 100644 --- a/apps/portal/src/lib/enrichment.test.ts +++ b/apps/portal/src/lib/enrichment.test.ts @@ -33,59 +33,59 @@ describe("deriveEnrichmentStatus", () => { expect(deriveEnrichmentStatus(run, false)).toBe("done"); }); - it("does NOT flip to done after pp-atif while pp-taxonomy is still pending (the bug)", () => { - // Observations configured, pp-atif done, pp-taxonomy not yet dispatched. + it("does NOT flip to done after pp-atif while pp-observations is still pending (the bug)", () => { + // Observations configured, pp-atif done, pp-observations not yet dispatched. const beforeDispatch = makeRun({ postProcessorStatus: "done", // legacy scalar already flipped — must be ignored handlerStatus: { "pp-atif": { status: "done" } }, }); expect(deriveEnrichmentStatus(beforeDispatch, true)).toBe("processing"); - // pp-taxonomy queued. + // pp-observations queued. const queued = makeRun({ postProcessorStatus: "done", - handlerStatus: { "pp-atif": { status: "done" }, "pp-taxonomy": { status: "queued" } }, + handlerStatus: { "pp-atif": { status: "done" }, "pp-observations": { status: "queued" } }, }); expect(deriveEnrichmentStatus(queued, true)).toBe("processing"); - // pp-taxonomy processing. + // pp-observations processing. const processing = makeRun({ postProcessorStatus: "done", - handlerStatus: { "pp-atif": { status: "done" }, "pp-taxonomy": { status: "processing" } }, + handlerStatus: { "pp-atif": { status: "done" }, "pp-observations": { status: "processing" } }, }); expect(deriveEnrichmentStatus(processing, true)).toBe("processing"); }); - it("flips to done only once both pp-atif and pp-taxonomy are done", () => { + it("flips to done only once both pp-atif and pp-observations are done", () => { const run = makeRun({ - handlerStatus: { "pp-atif": { status: "done" }, "pp-taxonomy": { status: "done" } }, + handlerStatus: { "pp-atif": { status: "done" }, "pp-observations": { status: "done" } }, }); expect(deriveEnrichmentStatus(run, true)).toBe("done"); }); it("reports failed when a handler failed and nothing is still in flight", () => { const run = makeRun({ - handlerStatus: { "pp-atif": { status: "done" }, "pp-taxonomy": { status: "failed" } }, + handlerStatus: { "pp-atif": { status: "done" }, "pp-observations": { status: "failed" } }, }); expect(deriveEnrichmentStatus(run, true)).toBe("failed"); }); it("prefers processing over failed while another handler is still running", () => { const run = makeRun({ - handlerStatus: { "pp-atif": { status: "processing" }, "pp-taxonomy": { status: "failed" } }, + handlerStatus: { "pp-atif": { status: "processing" }, "pp-observations": { status: "failed" } }, }); expect(deriveEnrichmentStatus(run, true)).toBe("processing"); }); - it("treats a no-op pp-taxonomy (no observations) as part of the DAG", () => { - // No observations configured, but pp-taxonomy still runs as a no-op handler. + it("treats a no-op pp-observations (no observations) as part of the DAG", () => { + // No observations configured, but pp-observations still runs as a no-op handler. const stillRunning = makeRun({ - handlerStatus: { "pp-atif": { status: "done" }, "pp-taxonomy": { status: "processing" } }, + handlerStatus: { "pp-atif": { status: "done" }, "pp-observations": { status: "processing" } }, }); expect(deriveEnrichmentStatus(stillRunning, false)).toBe("processing"); const allDone = makeRun({ - handlerStatus: { "pp-atif": { status: "done" }, "pp-taxonomy": { status: "done" } }, + handlerStatus: { "pp-atif": { status: "done" }, "pp-observations": { status: "done" } }, }); expect(deriveEnrichmentStatus(allDone, false)).toBe("done"); }); diff --git a/apps/portal/src/lib/enrichment.ts b/apps/portal/src/lib/enrichment.ts index 99f5bfebc..756a510d9 100644 --- a/apps/portal/src/lib/enrichment.ts +++ b/apps/portal/src/lib/enrichment.ts @@ -12,14 +12,14 @@ export type PostProcessorStatus = "queued" | "processing" | "done" | "failed"; * * Each post-processor handler overwrites that scalar on its own completion, so * it flips to "done" as soon as the FIRST handler (pp-atif) finishes — even - * while pp-taxonomy is still computing observations. The "Enriched" badge (and + * while pp-observations is still computing observations. The "Enriched" badge (and * the run-detail poller) must instead stay "Enriching…" until every handler in * the DAG is terminal. * - * Known topology: pp-atif always runs; pp-taxonomy is expected whenever the run + * Known topology: pp-atif always runs; pp-observations is expected whenever the run * has configured observations. We treat taxonomy as still-pending until - * pp-taxonomy reaches a terminal state, which also covers the brief window - * after pp-atif finishes but before the scheduler has dispatched pp-taxonomy + * pp-observations reaches a terminal state, which also covers the brief window + * after pp-atif finishes but before the scheduler has dispatched pp-observations * (so it isn't yet present in `handlerStatus`). * * Falls back to the legacy `postProcessorStatus` scalar for runs that predate @@ -36,7 +36,7 @@ export function deriveEnrichmentStatus( return run.postProcessorStatus; } const statuses = Object.values(handlerStatus).map((h) => h?.status); - const taxonomyStatus = handlerStatus["pp-taxonomy"]?.status; + const taxonomyStatus = handlerStatus["pp-observations"]?.status; const taxonomyPending = hasConfiguredObservations && taxonomyStatus !== "done" && taxonomyStatus !== "failed"; if (taxonomyPending || statuses.some((s) => s === "queued" || s === "processing")) { diff --git a/apps/scheduler/src/handler-dispatcher.ts b/apps/scheduler/src/handler-dispatcher.ts index 4ff1f8275..d744092c3 100644 --- a/apps/scheduler/src/handler-dispatcher.ts +++ b/apps/scheduler/src/handler-dispatcher.ts @@ -3,8 +3,13 @@ import { Collection, Db } from "mongodb"; import { QueueClient } from "@azure/storage-queue"; -import type { RequestDocument, HandlerServiceDocument, HandlerRunStatus } from "shared"; -import { DependencyGraph, withRetry } from "shared"; +import type { + RequestDocument, + HandlerServiceDocument, + HandlerRunStatus, + ServiceHandlerDocument, +} from "shared"; +import { DependencyGraph, isHandlerDagDrained, withRetry } from "shared"; import type { RetryOptions } from "shared"; import type { NotifyHandler } from "./notify-routes.js"; @@ -151,7 +156,27 @@ export class HandlerDispatcher implements NotifyHandler { await this.maybeTriggerReports(requestId, runId); } - async registerHandler(doc: HandlerServiceDocument): Promise { + async registerHandler(doc: ServiceHandlerDocument): Promise { + if (doc.type === "submission-handler") { + const postProcessHandlers = await this.loadHandlers(true); + for (const dependency of doc.dependsOn) { + if (!postProcessHandlers.some((handler) => handler._id === dependency)) { + throw new Error( + `Submission handler '${doc._id}' depends on unknown run handler '${dependency}'`, + ); + } + } + const { _id, ...fields } = doc; + await this.db.collection("services").updateOne( + { _id } as any, + { $set: { ...fields, dependsOn: [...fields.dependsOn], updatedAt: new Date() } } as any, + { upsert: true }, + ); + console.log( + `[HandlerDispatcher] Registered submission handler ${_id} (version=${doc.version}, queue=${doc.queue}, dependsOn=[${doc.dependsOn.join(", ")}])`, + ); + return; + } // Validate the resulting topology has no cycles before persisting. Read // fresh (bypass the cache) so validation reflects any concurrent registrations. const existing = await this.loadHandlers(true); @@ -183,43 +208,12 @@ export class HandlerDispatcher implements NotifyHandler { // ── Report trigger on DAG drain ───────────────────────────────────── - /** - * A handler is "terminal" for a run when it can produce no further work: - * it has succeeded (`done`), failed (`failed`), or is permanently blocked - * because one of its transitive dependencies failed (so it can never run). - */ - private isHandlerTerminal( - handlerId: string, - graph: DependencyGraph, - handlerStatus: Record | undefined, - ): boolean { - const status = handlerStatus?.[handlerId]?.status; - if (status === "done" || status === "failed") return true; - - // Not yet dispatched/processed — terminal only if blocked by a failed - // ancestor (any transitive dependency that failed). - if (status === undefined) { - for (const ancestorId of graph.getAncestors(handlerId)) { - if (handlerStatus?.[ancestorId]?.status === "failed") return true; - } - } - - // "queued" or "processing" — still active. - return false; - } - - /** - * The DAG is drained for a run when every registered handler is terminal. - * Vacuously true when there are no handlers. - */ private isDagDrained( handlers: HandlerServiceDocument[], - graph: DependencyGraph, + _graph: DependencyGraph, handlerStatus: Record | undefined, ): boolean { - return handlers.every((h) => - this.isHandlerTerminal(h._id, graph, handlerStatus), - ); + return isHandlerDagDrained(handlers, handlerStatus); } /** @@ -239,12 +233,11 @@ export class HandlerDispatcher implements NotifyHandler { if ((run as any).reportsTriggeredAt) return; const handlers = await this.loadHandlers(); - const graph = this.buildGraph(handlers); const handlerStatus = (run as any).handlerStatus as | Record | undefined; - if (!this.isDagDrained(handlers, graph, handlerStatus)) return; + if (!this.isDagDrained(handlers, this.buildGraph(handlers), handlerStatus)) return; // Atomically claim the trigger so concurrent notify/poll paths fire once. const claimed = await this.collection.findOneAndUpdate( diff --git a/apps/workers/post-processor/Dockerfile b/apps/workers/post-processor/Dockerfile index 50f1c7a7c..2f5427cfe 100644 --- a/apps/workers/post-processor/Dockerfile +++ b/apps/workers/post-processor/Dockerfile @@ -24,7 +24,7 @@ COPY packages/telemetry/src ./packages/telemetry/src/ COPY apps/workers/post-processor/tsconfig.json ./apps/workers/post-processor/ COPY apps/workers/post-processor/src ./apps/workers/post-processor/src/ # Copy every handler manifest (handler.yaml = pp-atif, handler.taxonomy.yaml = -# pp-taxonomy, plus any future handlers). The registration jobs read these by +# pp-observations, plus any future handlers). The registration jobs read these by # HANDLER_YAML_PATH, so all must be present in the image. COPY apps/workers/post-processor/handler*.yaml ./apps/workers/post-processor/ diff --git a/apps/workers/post-processor/handler.taxonomy.yaml b/apps/workers/post-processor/handler.taxonomy.yaml index 37411625f..849568456 100644 --- a/apps/workers/post-processor/handler.taxonomy.yaml +++ b/apps/workers/post-processor/handler.taxonomy.yaml @@ -2,16 +2,16 @@ # Read by the generic register-handler script and POSTed to the # scheduler's POST /handlers/register endpoint on deploy. # -# pp-taxonomy records per-iteration boolean observations (kind:"observation" +# pp-observations records boolean observations (kind:"observation" # criteria) by reusing the judge. It depends on pp-atif so each turn's ATIF # trajectory is available, giving the judge codebase (snapshot) + trajectory # (ATIF) access. Shares the post-processor-queue with pp-atif (same worker). # See issue #1156. -_id: pp-taxonomy +_id: pp-observations type: post-process-handler version: 1 queue: post-processor-queue -selector: taxonomy +selector: observations autoBackfill: true dependsOn: - pp-atif diff --git a/apps/workers/post-processor/src/handlers/taxonomy-handler.test.ts b/apps/workers/post-processor/src/handlers/taxonomy-handler.test.ts index 1f191caa9..1aeb0b2ec 100644 --- a/apps/workers/post-processor/src/handlers/taxonomy-handler.test.ts +++ b/apps/workers/post-processor/src/handlers/taxonomy-handler.test.ts @@ -32,7 +32,7 @@ function makeCtx( } as any; } -const msg: PostProcessorMessage = { type: "taxonomy", requestId: "req-1", runId: "run-1" }; +const msg: PostProcessorMessage = { type: "observations", requestId: "req-1", runId: "run-1" }; describe("TaxonomyHandler", () => { let judge: { evaluate: ReturnType }; @@ -41,8 +41,8 @@ describe("TaxonomyHandler", () => { judge = { evaluate: vi.fn() }; }); - it("has type 'taxonomy'", () => { - expect(new TaxonomyHandler(judge as unknown as JudgeClient).type).toBe("taxonomy"); + it("has type 'observations'", () => { + expect(new TaxonomyHandler(judge as unknown as JudgeClient).type).toBe("observations"); }); it("no-ops when no observations are selected", async () => { diff --git a/apps/workers/post-processor/src/handlers/taxonomy-handler.ts b/apps/workers/post-processor/src/handlers/taxonomy-handler.ts index 62cf41a85..2baa81365 100644 --- a/apps/workers/post-processor/src/handlers/taxonomy-handler.ts +++ b/apps/workers/post-processor/src/handlers/taxonomy-handler.ts @@ -26,7 +26,7 @@ interface CriterionMeta { } /** - * Taxonomy Handler (pp-taxonomy): records boolean observations. + * Taxonomy Handler (pp-observations): records boolean observations. * * Each selected observation criterion is routed by its `subject` (#1156): * @@ -40,12 +40,12 @@ interface CriterionMeta { * behavior (e.g. a dependency added in one turn and removed in another) visible. * * Reuses the judge service; never gates, never steers the agent. Empty/absent - * `observations` → no-op. pp-taxonomy is dispatched exactly once per run (the + * `observations` → no-op. pp-observations is dispatched exactly once per run (the * scheduler never sets `message.iteration`), so the run-subject branch runs once * with no idempotency guard. */ export class TaxonomyHandler implements PostProcessHandler { - readonly type = "taxonomy"; + readonly type = "observations"; readonly version = POST_PROCESSOR_VERSION; readonly autoBackfill = true; private readonly judge: JudgeClient; diff --git a/docker-compose.yml b/docker-compose.yml index 027888cd2..221dd5c03 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -886,7 +886,7 @@ services: restart: "no" entrypoint: ["npx", "tsx", "packages/shared/src/scripts/register-handler.ts"] - # Registers the pp-taxonomy handler (observation evaluator) — shares the + # Registers the pp-observations handler (observation evaluator) — shares the # post-processor worker + post-processor-queue, depends on pp-atif. Issue #1156. register-handler-taxonomy: build: @@ -918,7 +918,7 @@ services: AZURE_STORAGE_QUEUE_POSTPROCESSOR: post-processor-queue SCOPE_MT_API_URL: http://api:80 SCHEDULER_URL: http://scheduler:8080 - # pp-taxonomy (issue #1156) calls the judge service to evaluate + # pp-observations (issue #1156) calls the judge service to evaluate # observation criteria. Without this the JudgeClient falls back to # localhost:3002 and cannot reach the judge container. JUDGE_SERVICE_URL: http://judge:80 diff --git a/docs/architecture/criteria-provider.md b/docs/architecture/criteria-provider.md index af6db54f6..23ae0d8ec 100644 --- a/docs/architecture/criteria-provider.md +++ b/docs/architecture/criteria-provider.md @@ -181,7 +181,7 @@ bypassed or drift between callers: default): `kind:"observation"` ⇒ `"run"`, `kind:"gate"`/legacy ⇒ `"iteration"`. Gate criteria are rejected if `subject:"run"` is supplied — `"iteration"` is their only legal value. The field is threaded through `create`/`update`/`find` and both provider backends - so the `pp-taxonomy` worker and the CLI/Portal can read it. + so the `pp-observations` worker and the CLI/Portal can read it. - **Referential integrity on delete** — deleting a criterion that still has dependents is rejected. diff --git a/docs/architecture/post-processing.md b/docs/architecture/post-processing.md index dbeec1301..4518ef391 100644 --- a/docs/architecture/post-processing.md +++ b/docs/architecture/post-processing.md @@ -56,9 +56,9 @@ Two paths trigger post-processing: The `iteration` query parameter is mandatory for the ATIF endpoints. ATIF files are also included in archive exports as `iteration-{N}.atif.trajectory.json`. -## Taxonomy Observations (`pp-taxonomy`) +## Taxonomy Observations (`pp-observations`) -The `pp-taxonomy` handler records **observation criteria** — boolean outcomes + +The `pp-observations` handler records **observation criteria** — boolean outcomes + evidence about the codebase and the agent's trajectory, **without gating or steering** the coding agent (issue #1156). It is a DAG node `dependsOn: [pp-atif]`, because some observations are only derivable from the trajectory (ATIF), not the final snapshot. @@ -89,8 +89,8 @@ Gate criteria are always `subject: "iteration"` (the API rejects `"run"` for gat 4. **Run-subject:** evaluates **once** with `snapshotUrl` = final turn's snapshot, `atifUrls` = every turn's `atifUrl` (the judge downloads + merges them into one `AgentTrajectory`), and the full `conversationHistory`. Writes the verdicts to **`run.observationResults`** (run level). - In all judge calls there is no persona, no gate, no taxonomyElementId (the classifier lives on the criterion). ATIF supersedes per-turn `toolCallsUrl`, so only ATIF is sent. - Result shape/storage mirrors gate `criteriaResults`. No new blob, no `run.taxonomyUrl`. - - **Runs exactly once per run:** the scheduler dispatches `pp-taxonomy` a single time (it never sets `message.iteration`), so the run-subject branch needs no idempotency guard. -5. Stamps `run.handlerStatus["pp-taxonomy"] = { status: "done", version: N }` and notifies the scheduler. + - **Runs exactly once per run:** the scheduler dispatches `pp-observations` a single time (it never sets `message.iteration`), so the run-subject branch needs no idempotency guard. +5. Stamps `run.handlerStatus["pp-observations"] = { status: "done", version: N }` and notifies the scheduler. Dimension grouping is **derived at read time** by joining each result's `criterionId` → criterion `taxonomyElementId` (the three R&A Readout dimensions; unset = unclassified). It never feeds back to the agent and never affects pass/fail. (#1053 later extends this worker with a richer scorecard artifact.) @@ -203,7 +203,34 @@ flowchart LR **Where it runs:** - **Docker Compose:** one `register-handler-` init service per handler (e.g. `pp-atif`) runs the generic script via `tsx`, gated on the scheduler being up. The worker waits for its registration service to complete. -- **Kubernetes:** a `register-handler-post-processor` Job runs the compiled script (`node packages/shared/dist/scripts/register-handler.js`) on each deploy. `pp-atif` and `pp-taxonomy` are registered in K8s via their respective registration Jobs (`register-handler-taxonomy` points its `HANDLER_YAML_PATH` at `handler.taxonomy.yaml`). The scheduler exposes a `Service` (`scheduler.scoped.svc.cluster.local:8080`) so Jobs and workers can reach `/handlers/register` and the notify endpoints. +- **Kubernetes:** a `register-handler-post-processor` Job runs the compiled script (`node packages/shared/dist/scripts/register-handler.js`) on each deploy. `pp-atif` and `pp-observations` are registered in K8s via their respective registration Jobs (`register-handler-taxonomy` points its `HANDLER_YAML_PATH` at `handler.taxonomy.yaml`). The scheduler exposes a `Service` (`scheduler.scoped.svc.cluster.local:8080`) so Jobs and workers can reach `/handlers/register` and the notify endpoints. + +## Submission handlers + +Submission handlers use the same `services` registration endpoint but declare +`type: submission-handler` and `dependencyMode: all-runs`. Their dependencies +name run-level DAG handlers, not other submission handlers. The scheduler +reconciles each submission's exact request/run vector, projects those named +dependencies, and enqueues only the current embedded submission attempt. + +The first consumer is `pp-readout`, which depends on `pp-observations` for every +run in the vector. Its queue contract is: + +```json +{ + "type": "readout", + "submissionId": "…", + "submissionRunId": "…" +} +``` + +Workers must use the shared `claimSubmissionHandler`, +`isCurrentSubmissionRun`, and `completeSubmissionHandler` helpers. These helpers +scope every mutation to both identifiers, providing stale-message discard, +cooperative supersession checks, and stale completion rejection. Queue delivery +remains at-least-once; the embedded current attempt is the only dispatchable +state, and the scheduler poll repairs missed notifications, stale projections, +request-vector drift, and interrupted rollover/finalization. To **add or change a handler**, edit its `handler.yaml` (bump `version`, adjust `dependsOn`, etc.) — no code or migration changes are needed for registration. diff --git a/packages/db-migrations/src/034-create-submission-indexes.test.ts b/packages/db-migrations/src/034-create-submission-indexes.test.ts new file mode 100644 index 000000000..1fd59c8bd --- /dev/null +++ b/packages/db-migrations/src/034-create-submission-indexes.test.ts @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import type { Db } from "mongodb"; +import { describe, expect, it, vi } from "vitest"; +import { CreateSubmissionIndexes } from "./migrations/034-create-submission-indexes.js"; + +function collection() { + return { + createIndex: vi.fn(async () => "index"), + }; +} + +describe("migration 034: CreateSubmissionIndexes", () => { + it("creates submission, history, dispatch, and recovery indexes", async () => { + const submissions = collection(); + const submissionRuns = collection(); + const requests = collection(); + const db = { + collection: vi.fn((name: string) => { + if (name === "submissions") return submissions; + if (name === "submission-runs") return submissionRuns; + if (name === "requests") return requests; + throw new Error(`Unexpected collection ${name}`); + }), + } as unknown as Db; + + await new CreateSubmissionIndexes().up(db); + + expect(submissions.createIndex).toHaveBeenCalledWith( + { projectId: 1, createdAt: -1, _id: -1 }, + {}, + ); + expect(submissions.createIndex).toHaveBeenCalledWith( + { "run.handlerStatus.pp-readout.status": 1 }, + {}, + ); + expect(submissionRuns.createIndex).toHaveBeenCalledWith( + { submissionId: 1, attemptNumber: -1 }, + {}, + ); + expect(requests.createIndex).toHaveBeenCalledWith( + { submissionFinalizedAt: 1 }, + {}, + ); + expect(requests.createIndex).toHaveBeenCalledWith( + { submissionId: 1, projectId: 1, submissionRequestIndex: 1, _id: 1 }, + {}, + ); + }); +}); + diff --git a/packages/db-migrations/src/migrations/034-create-submission-indexes.ts b/packages/db-migrations/src/migrations/034-create-submission-indexes.ts new file mode 100644 index 000000000..8ceb836e9 --- /dev/null +++ b/packages/db-migrations/src/migrations/034-create-submission-indexes.ts @@ -0,0 +1,67 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import type { Db } from "mongodb"; +import type { MigrationInterface } from "mongo-migrate-ts"; +import { ensureIndex } from "../cosmos-index-helpers.js"; + +const TAG = "034"; + +export class CreateSubmissionIndexes implements MigrationInterface { + async up(db: Db): Promise { + const submissions = db.collection("submissions"); + await ensureIndex( + submissions, + { projectId: 1, createdAt: -1, _id: -1 }, + {}, + "submissions", + TAG, + ); + await ensureIndex( + submissions, + { "run.handlerStatus.pp-readout.status": 1 }, + {}, + "submissions", + TAG, + ); + + const submissionRuns = db.collection("submission-runs"); + await ensureIndex( + submissionRuns, + { submissionId: 1 }, + {}, + "submission-runs", + TAG, + ); + await ensureIndex( + submissionRuns, + { submissionId: 1, attemptNumber: -1 }, + {}, + "submission-runs", + TAG, + ); + + const requests = db.collection("requests"); + await ensureIndex( + requests, + { submissionFinalizedAt: 1 }, + {}, + "requests", + TAG, + ); + await ensureIndex( + requests, + { submissionId: 1, projectId: 1, submissionRequestIndex: 1, _id: 1 }, + {}, + "requests", + TAG, + ); + console.log(`[${TAG}] Submission indexes complete`); + } + + async down(_db: Db): Promise { + console.log( + `[${TAG}-down] Skipping index changes - drop submission indexes manually if needed`, + ); + } +} diff --git a/packages/db-migrations/src/required-migrations.ts b/packages/db-migrations/src/required-migrations.ts index 4d0e54062..bee754391 100644 --- a/packages/db-migrations/src/required-migrations.ts +++ b/packages/db-migrations/src/required-migrations.ts @@ -46,6 +46,7 @@ export const REQUIRED_MIGRATIONS: readonly string[] = [ "031-migrate-services-to-handler-dag.ts", "032-add-handler-status-index.ts", "033-backfill-handler-status.ts", + "034-create-submission-indexes.ts", "021-backfill-criteria-kind.ts", "022-backfill-criteria-subject.ts", ]; diff --git a/packages/shared/src/criteria/criteria-store.ts b/packages/shared/src/criteria/criteria-store.ts index 7413449c9..0b47231b4 100644 --- a/packages/shared/src/criteria/criteria-store.ts +++ b/packages/shared/src/criteria/criteria-store.ts @@ -439,7 +439,7 @@ export class CriteriaStore { /** * Resolve observation-criteria ids, asserting each is an active - * kind:"observation" criterion. Used by submit validation + pp-taxonomy. + * kind:"observation" criterion. Used by submit validation + pp-observations. * Throws CriteriaValidationError on a missing or non-observation id. */ async resolveObservations(ids: string[]): Promise { diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index a6febdece..fae65d02f 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -20,6 +20,7 @@ export * from "./codebases/index.js"; export * from "./resources/index.js"; export * from "./extensions/index.js"; export * from "./projects/index.js"; +export * from "./submissions/index.js"; export * from "./agent-version.js"; export * from "./resolve-agent-version.js"; export * from "./resolve-agent-target.js"; diff --git a/packages/shared/src/judge/judge-client.ts b/packages/shared/src/judge/judge-client.ts index 7a5f85850..633fd6e8f 100644 --- a/packages/shared/src/judge/judge-client.ts +++ b/packages/shared/src/judge/judge-client.ts @@ -18,11 +18,11 @@ export interface JudgeEvaluateRequest { /** Blob URL of this iteration's captured tool calls/outputs (build/test/run output). */ toolCallsUrl?: string; /** Blob URL of this iteration's ATIF trajectory JSON. Normalized superset of - * tool calls; sent by pp-taxonomy in place of toolCallsUrl so observations + * tool calls; sent by pp-observations in place of toolCallsUrl so observations * can be evaluated against the full agent trajectory. See issue #1156. */ atifUrl?: string; /** Blob URLs of EVERY iteration's ATIF trajectory JSON, in iteration order. - * Sent by pp-taxonomy for `subject:"run"` observations so the judge merges + * Sent by pp-observations for `subject:"run"` observations so the judge merges * them into one whole-run trajectory (cross-iteration behavior is visible in a * single evaluation). Takes precedence over `atifUrl`. See issue #1156. */ atifUrls?: string[]; diff --git a/packages/shared/src/schemas/index.ts b/packages/shared/src/schemas/index.ts index cb1df8b4c..52a7bed3f 100644 --- a/packages/shared/src/schemas/index.ts +++ b/packages/shared/src/schemas/index.ts @@ -22,3 +22,4 @@ export * from "./account.js"; export * from "./feature-flag.js"; export * from "./profile.js"; export * from "./project.js"; +export * from "./submission.js"; diff --git a/packages/shared/src/schemas/request.ts b/packages/shared/src/schemas/request.ts index 5271582a5..5aefb2466 100644 --- a/packages/shared/src/schemas/request.ts +++ b/packages/shared/src/schemas/request.ts @@ -181,6 +181,10 @@ export const RequestResponseSchema = z profileId: z.string().optional(), profileVersionId: z.string().optional(), submissionId: z.string().optional(), + submissionExpectedRequestCount: z.number().int().min(1).optional(), + submissionRequestIndex: z.number().int().min(0).optional(), + submissionInitialRunId: z.string().optional(), + submissionFinalizedAt: z.coerce.date().optional(), priority: z.number().int().default(0), gates: z.array(GateConfigSchema).optional(), observations: z.array(z.string()).optional(), diff --git a/packages/shared/src/schemas/submission.ts b/packages/shared/src/schemas/submission.ts new file mode 100644 index 000000000..3558ae603 --- /dev/null +++ b/packages/shared/src/schemas/submission.ts @@ -0,0 +1,182 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { z } from "zod"; +import { extendZodWithOpenApi } from "@asteasolutions/zod-to-openapi"; + +extendZodWithOpenApi(z); + +export const SubmissionRequestRefSchema = z + .object({ + requestId: z.string(), + runId: z.string(), + }) + .openapi("SubmissionRequestRef"); + +export const SubmissionDependencyStateSchema = z.enum([ + "waiting", + "ready", + "failed", + "blocked", +]); + +export const SubmissionDependencyProjectionSchema = z + .object({ + requestId: z.string(), + runId: z.string(), + handlerId: z.string(), + state: SubmissionDependencyStateSchema, + version: z.number().optional(), + updatedAt: z.coerce.date().optional(), + error: z.string().optional(), + }) + .openapi("SubmissionDependencyProjection"); + +export const SubmissionBlockingDetailSchema = z + .object({ + requestId: z.string(), + runId: z.string(), + handlerId: z.string(), + reason: z.enum([ + "request-missing", + "run-changed", + "dependency-not-ready", + "dependency-failed", + "dependency-blocked", + ]), + error: z.string().optional(), + }) + .openapi("SubmissionBlockingDetail"); + +export const SubmissionHandlerStatusSchema = z + .object({ + status: z.enum(["queued", "processing", "done", "failed"]), + version: z.number().optional(), + updatedAt: z.coerce.date().optional(), + error: z.string().optional(), + }) + .openapi("SubmissionHandlerStatus"); + +export const SubmissionReportPointerSchema = z + .object({ + reportId: z.string().optional(), + url: z.string().optional(), + updatedAt: z.coerce.date().optional(), + }) + .openapi("SubmissionReportPointer"); + +export const SubmissionRolloverClaimSchema = z.object({ + nextSubmissionRunId: z.string(), + vectorFingerprint: z.string(), + requests: z.array(SubmissionRequestRefSchema), + reason: z.enum(["request-vector-changed", "manual-retry"]), + claimedAt: z.coerce.date(), +}); + +export const SubmissionRunStateSchema = z + .object({ + _id: z.string(), + attemptNumber: z.number().int().min(1), + vectorFingerprint: z.string(), + requests: z.array(SubmissionRequestRefSchema), + createdAt: z.coerce.date(), + updatedAt: z.coerce.date().optional(), + startedAt: z.coerce.date().optional(), + finishedAt: z.coerce.date().optional(), + dependencyProjection: z.array(SubmissionDependencyProjectionSchema).default([]), + handlerStatus: z.record(z.string(), SubmissionHandlerStatusSchema).optional(), + blocking: z.array(SubmissionBlockingDetailSchema).default([]), + report: SubmissionReportPointerSchema.optional(), + reconcileAfter: z.coerce.date().optional(), + rollover: SubmissionRolloverClaimSchema.optional(), + supersededAt: z.coerce.date().optional(), + supersededBySubmissionRunId: z.string().optional(), + supersededReason: z.enum(["request-vector-changed", "manual-retry"]).optional(), + }) + .openapi("SubmissionRunState"); + +export const SubmissionDocumentSchema = z + .object({ + _id: z.string(), + submissionId: z.string(), + projectId: z.string(), + requestIds: z.array(z.string()).min(1), + createdAt: z.coerce.date(), + updatedAt: z.coerce.date().optional(), + run: SubmissionRunStateSchema, + }) + .openapi("SubmissionDocument"); + +export const SubmissionRunHistoryDocumentSchema = SubmissionRunStateSchema.extend({ + submissionId: z.string(), + projectId: z.string(), +}).openapi("SubmissionRunHistoryDocument"); + +export const SubmissionRunResponseSchema = SubmissionRunStateSchema.omit({ + reconcileAfter: true, + rollover: true, +}) + .extend({ + submissionId: z.string().optional(), + projectId: z.string().optional(), + }) + .openapi("SubmissionRunResponse"); + +export const SubmissionReadinessSchema = z.enum([ + "waiting", + "ready", + "blocked", + "processing", + "done", + "failed", +]); + +export const SubmissionRequestSummarySchema = z + .object({ + requestId: z.string(), + runId: z.string(), + task: z.string(), + status: z.string(), + outcome: z.string().optional(), + workerType: z.string(), + model: z.string().optional(), + profileId: z.string().optional(), + }) + .openapi("SubmissionRequestSummary"); + +export const SubmissionResponseSchema = z + .object({ + submissionId: z.string(), + projectId: z.string(), + requestIds: z.array(z.string()), + createdAt: z.coerce.date(), + updatedAt: z.coerce.date().optional(), + submissionRunId: z.string(), + attemptNumber: z.number().int(), + readiness: SubmissionReadinessSchema, + requests: z.array(SubmissionRequestSummarySchema), + dependencyProjection: z.array(SubmissionDependencyProjectionSchema), + blocking: z.array(SubmissionBlockingDetailSchema), + handlerProgress: z.record(z.string(), SubmissionHandlerStatusSchema).optional(), + report: SubmissionReportPointerSchema.optional(), + supersededAt: z.coerce.date().optional(), + supersededBySubmissionRunId: z.string().optional(), + supersededReason: z.enum(["request-vector-changed", "manual-retry"]).optional(), + }) + .openapi("SubmissionResponse"); + +export const SubmissionListResponseSchema = z + .object({ + submissions: z.array(SubmissionResponseSchema), + }) + .openapi("SubmissionListResponse"); + +export const SubmissionRetryResponseSchema = z + .object({ + submissionId: z.string(), + submissionRunId: z.string(), + attemptNumber: z.number().int(), + readiness: SubmissionReadinessSchema, + blocking: z.array(SubmissionBlockingDetailSchema), + }) + .openapi("SubmissionRetryResponse"); diff --git a/packages/shared/src/scripts/register-handler.ts b/packages/shared/src/scripts/register-handler.ts index c585e9eb1..730b860f6 100644 --- a/packages/shared/src/scripts/register-handler.ts +++ b/packages/shared/src/scripts/register-handler.ts @@ -21,7 +21,7 @@ */ import { readFile } from "node:fs/promises"; import { parse as parseYaml } from "yaml"; -import type { HandlerServiceDocument } from "../types/types.js"; +import type { ServiceHandlerDocument } from "../types/types.js"; const HEALTH_RETRIES = 30; const HEALTH_DELAY_MS = 3_000; @@ -33,7 +33,7 @@ function isNonEmptyString(value: unknown): value is string { } /** Validate the parsed YAML conforms to the HandlerServiceDocument shape. */ -export function parseHandlerDocument(raw: unknown): HandlerServiceDocument { +export function parseHandlerDocument(raw: unknown): ServiceHandlerDocument { if (typeof raw !== "object" || raw === null) { throw new Error("handler.yaml must contain a mapping"); } @@ -42,8 +42,10 @@ export function parseHandlerDocument(raw: unknown): HandlerServiceDocument { if (!isNonEmptyString(doc._id)) { throw new Error("handler.yaml: '_id' is required"); } - if (doc.type !== "post-process-handler") { - throw new Error("handler.yaml: 'type' must be 'post-process-handler'"); + if (doc.type !== "post-process-handler" && doc.type !== "submission-handler") { + throw new Error( + "handler.yaml: 'type' must be 'post-process-handler' or 'submission-handler'", + ); } if (typeof doc.version !== "number" || !Number.isFinite(doc.version)) { throw new Error("handler.yaml: 'version' must be a number"); @@ -62,15 +64,27 @@ export function parseHandlerDocument(raw: unknown): HandlerServiceDocument { throw new Error("handler.yaml: 'dependsOn' must be an array of strings"); } - return { + const common = { _id: doc._id, - type: "post-process-handler", version: doc.version, queue: doc.queue, selector: doc.selector, autoBackfill: doc.autoBackfill, dependsOn: dependsOn as string[], }; + if (doc.type === "submission-handler") { + if (doc.dependencyMode !== "all-runs") { + throw new Error( + "handler.yaml: submission handlers require dependencyMode: 'all-runs'", + ); + } + return { + ...common, + type: "submission-handler", + dependencyMode: "all-runs", + }; + } + return { ...common, type: "post-process-handler" }; } async function delay(ms: number): Promise { @@ -97,7 +111,7 @@ async function waitForScheduler(schedulerUrl: string): Promise { async function postRegistration( schedulerUrl: string, - doc: HandlerServiceDocument, + doc: ServiceHandlerDocument, ): Promise { for (let attempt = 1; attempt <= POST_RETRIES; attempt++) { try { @@ -128,7 +142,7 @@ async function postRegistration( export async function registerHandlerFromYaml( yamlPath: string, schedulerUrl: string, -): Promise { +): Promise { const content = await readFile(yamlPath, "utf-8"); const doc = parseHandlerDocument(parseYaml(content)); diff --git a/packages/shared/src/submissions/index.ts b/packages/shared/src/submissions/index.ts new file mode 100644 index 000000000..5aa35026a --- /dev/null +++ b/packages/shared/src/submissions/index.ts @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +export * from "./submission-state.js"; +export * from "./submission-coordinator.js"; diff --git a/packages/shared/src/submissions/submission-coordinator.test.ts b/packages/shared/src/submissions/submission-coordinator.test.ts new file mode 100644 index 000000000..d44b4c12e --- /dev/null +++ b/packages/shared/src/submissions/submission-coordinator.test.ts @@ -0,0 +1,693 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { describe, expect, it, vi } from "vitest"; +import type { Collection } from "mongodb"; +import type { + RequestDocument, + ServiceHandlerDocument, + SubmissionDocument, + SubmissionRunHistoryDocument, +} from "../types/types.js"; +import { + SubmissionCoordinator, + claimSubmissionHandler, + completeSubmissionHandler, + ensureNativeSubmission, +} from "./submission-coordinator.js"; + +function queryResult(items: T[]) { + return { + project: () => queryResult(items), + sort: () => queryResult(items), + limit: () => queryResult(items), + toArray: async () => items, + }; +} + +describe("submission coordinator persistence", () => { + it("creates a native submission idempotently with the exact initial vector", async () => { + let stored: SubmissionDocument | null = null; + const updateOne = vi.fn(async ( + _filter: unknown, + update: { $setOnInsert: SubmissionDocument }, + ) => { + stored ??= update.$setOnInsert; + return { matchedCount: stored ? 1 : 0, modifiedCount: 0 }; + }); + const findOne = vi.fn(async () => stored); + const submissions = { + updateOne, + findOne, + } as unknown as Collection; + + const first = await ensureNativeSubmission({ + collections: { submissions }, + submissionId: "submission-1", + projectId: "project-1", + requests: [ + { requestId: "request-1", runId: "run-1" }, + { requestId: "request-2", runId: "run-2" }, + ], + createdAt: new Date("2026-01-01T00:00:00Z"), + }); + const second = await ensureNativeSubmission({ + collections: { submissions }, + submissionId: "submission-1", + projectId: "project-1", + requests: [ + { requestId: "request-1", runId: "run-1" }, + { requestId: "request-2", runId: "run-2" }, + ], + createdAt: new Date("2026-01-01T00:00:00Z"), + }); + + expect(first).toEqual(second); + expect(first.requestIds).toEqual(["request-1", "request-2"]); + expect(first.run.requests).toEqual([ + { requestId: "request-1", runId: "run-1" }, + { requestId: "request-2", runId: "run-2" }, + ]); + expect(first.run._id).toBe(second.run._id); + expect(updateOne).toHaveBeenCalledTimes(2); + }); + + it("rejects an idempotency key reused with a different immutable vector", async () => { + const stored: SubmissionDocument = { + _id: "submission-1", + submissionId: "submission-1", + projectId: "project-1", + requestIds: ["request-1"], + createdAt: new Date(), + run: { + _id: "submission-run-1", + attemptNumber: 1, + vectorFingerprint: "fingerprint", + requests: [{ requestId: "request-1", runId: "run-1" }], + createdAt: new Date(), + dependencyProjection: [], + blocking: [], + }, + }; + const submissions = { + updateOne: vi.fn(async () => ({ matchedCount: 1, modifiedCount: 0 })), + findOne: vi.fn(async () => stored), + } as unknown as Collection; + + await expect( + ensureNativeSubmission({ + collections: { submissions }, + submissionId: "submission-1", + projectId: "project-1", + requests: [{ requestId: "request-1", runId: "different-run" }], + }), + ).rejects.toThrow("different immutable request vector"); + }); + + it("scopes claims and completions to the exact embedded submission run", async () => { + const findOneAndUpdate = vi.fn(async (_filter: unknown, _update: unknown) => null); + const updateOne = vi.fn(async (_filter: unknown, _update: unknown) => ({ + modifiedCount: 0, + })); + const submissions = { + findOneAndUpdate, + updateOne, + } as unknown as Collection; + + expect( + await claimSubmissionHandler({ + submissions, + submissionId: "submission-1", + submissionRunId: "stale-run", + handlerId: "pp-readout", + version: 1, + }), + ).toBeNull(); + expect(findOneAndUpdate.mock.calls[0]?.[0]).toMatchObject({ + _id: "submission-1", + "run._id": "stale-run", + "run.rollover": { $exists: false }, + }); + + expect( + await completeSubmissionHandler({ + submissions, + submissionId: "submission-1", + submissionRunId: "stale-run", + handlerId: "pp-readout", + status: "done", + version: 1, + }), + ).toBe(false); + expect(updateOne.mock.calls[0]?.[0]).toMatchObject({ + _id: "submission-1", + "run._id": "stale-run", + "run.rollover": { $exists: false }, + "run.handlerStatus.pp-readout.status": "processing", + }); + }); + + it("defers reconciliation while a bulk retry replaces its request vector", async () => { + const submission: SubmissionDocument = { + _id: "submission-1", + submissionId: "submission-1", + projectId: "project-1", + requestIds: ["request-1"], + createdAt: new Date(), + run: { + _id: "submission-run-1", + attemptNumber: 1, + vectorFingerprint: "old-vector", + requests: [{ requestId: "request-1", runId: "run-1" }], + createdAt: new Date(), + reconcileAfter: new Date(Date.now() + 60_000), + dependencyProjection: [], + blocking: [], + }, + }; + const requestsFind = vi.fn(); + const archiveInsert = vi.fn(); + const coordinator = new SubmissionCoordinator({ + requests: { + find: requestsFind, + } as unknown as Collection, + submissions: { + findOne: vi.fn(async () => submission), + } as unknown as Collection, + submissionRuns: { + insertOne: archiveInsert, + } as unknown as Collection, + services: {} as Collection, + }); + + const result = await coordinator.reconcile("submission-1"); + + expect(result?.rolled).toBe(false); + expect(requestsFind).not.toHaveBeenCalled(); + expect(archiveInsert).not.toHaveBeenCalled(); + }); + + it("resumes an interrupted drift rollover without double-rolling a manual retry", async () => { + const requestDocs: RequestDocument[] = [ + { + _id: "request-1", + projectId: "project-1", + scenario: { task: "Task", criteria: ["criterion"] }, + workerType: "worker", + createdAt: new Date(), + priority: 0, + submissionId: "submission-1", + run: { + _id: "run-2", + attemptNumber: 2, + status: "done", + outcome: "failed", + handlerStatus: { + "pp-observations": { status: "done", version: 2 }, + unrelated: { status: "failed" }, + }, + }, + }, + ]; + let submission: SubmissionDocument = { + _id: "submission-1", + submissionId: "submission-1", + projectId: "project-1", + requestIds: ["request-1"], + createdAt: new Date(), + run: { + _id: "submission-run-1", + attemptNumber: 1, + vectorFingerprint: "old-vector", + requests: [{ requestId: "request-1", runId: "run-1" }], + createdAt: new Date(), + dependencyProjection: [], + blocking: [], + }, + }; + const history: SubmissionRunHistoryDocument[] = []; + const services: ServiceHandlerDocument[] = [ + { + _id: "pp-atif", + type: "post-process-handler", + version: 1, + queue: "post-processor", + selector: "atif", + autoBackfill: true, + dependsOn: [], + }, + { + _id: "pp-observations", + type: "post-process-handler", + version: 2, + queue: "post-processor", + selector: "observations", + autoBackfill: true, + dependsOn: ["pp-atif"], + }, + { + _id: "pp-readout", + type: "submission-handler", + version: 1, + queue: "readout", + selector: "readout", + autoBackfill: false, + dependsOn: ["pp-observations"], + dependencyMode: "all-runs", + }, + ]; + const submissions = { + findOne: vi.fn(async () => structuredClone(submission)), + updateOne: vi.fn(async () => ({ matchedCount: 1, modifiedCount: 1 })), + findOneAndUpdate: vi.fn(async ( + filter: Record, + update: { $set: Record }, + ) => { + if (filter["run._id"] && filter["run._id"] !== submission.run._id) return null; + if (update.$set["run.rollover"]) { + submission = { + ...submission, + updatedAt: update.$set.updatedAt as Date, + run: { + ...submission.run, + rollover: update.$set[ + "run.rollover" + ] as SubmissionDocument["run"]["rollover"], + updatedAt: update.$set["run.updatedAt"] as Date, + }, + }; + } else if (update.$set.run) { + rollAttempts++; + if (rollAttempts === 1) return null; + submission = { + ...submission, + run: update.$set.run as SubmissionDocument["run"], + updatedAt: update.$set.updatedAt as Date, + }; + } else { + submission = { + ...submission, + updatedAt: update.$set.updatedAt as Date, + run: { + ...submission.run, + dependencyProjection: update.$set[ + "run.dependencyProjection" + ] as SubmissionDocument["run"]["dependencyProjection"], + blocking: update.$set[ + "run.blocking" + ] as SubmissionDocument["run"]["blocking"], + updatedAt: update.$set["run.updatedAt"] as Date, + }, + }; + } + return structuredClone(submission); + }), + } as unknown as Collection; + let rollAttempts = 0; + const enqueue = vi.fn(async ( + _service: ServiceHandlerDocument, + _message: { submissionId: string; submissionRunId: string; type: string }, + ) => undefined); + const archiveUpdate = vi.fn(async ( + _filter: unknown, + update: { $setOnInsert: SubmissionRunHistoryDocument }, + ) => { + if (!history.some((item) => item._id === update.$setOnInsert._id)) { + history.push(update.$setOnInsert); + } + return { matchedCount: 1, modifiedCount: 1 }; + }); + const coordinator = new SubmissionCoordinator( + { + requests: { + find: vi.fn(() => queryResult(requestDocs)), + } as unknown as Collection, + submissions, + submissionRuns: { + updateOne: archiveUpdate, + } as unknown as Collection, + services: { + find: vi.fn(() => + queryResult(services.filter((service) => service.type === "post-process-handler")), + ), + findOne: vi.fn(async () => + services.find((service) => service._id === "pp-readout") ?? null, + ), + } as unknown as Collection, + }, + enqueue, + ); + + const result = await coordinator.retryCurrent( + "submission-1", + "submission-run-1", + ); + + expect(result?.rolled).toBe(true); + expect(result?.submission.run.attemptNumber).toBe(2); + expect(result?.submission.run.requests).toEqual([ + { requestId: "request-1", runId: "run-2" }, + ]); + expect(result?.submission.run.dependencyProjection[0]).toMatchObject({ + runId: "run-2", + state: "ready", + version: 2, + }); + expect(history).toHaveLength(1); + expect(archiveUpdate).toHaveBeenCalledTimes(2); + expect(history[0]).toMatchObject({ + _id: "submission-run-1", + supersededBySubmissionRunId: result?.submission.run._id, + supersededReason: "request-vector-changed", + }); + expect(enqueue).toHaveBeenCalledTimes(1); + expect(enqueue.mock.calls[0]?.[1]).toMatchObject({ + submissionId: "submission-1", + submissionRunId: result?.submission.run._id, + }); + }); + + it("links immutable history only to CAS-winning successors under concurrent vector drift", async () => { + const request = (runId: string, attemptNumber: number): RequestDocument => ({ + _id: "request-1", + projectId: "project-1", + scenario: { task: "Task", criteria: ["criterion"] }, + workerType: "worker", + createdAt: new Date(), + priority: 0, + submissionId: "submission-1", + run: { + _id: runId, + attemptNumber, + status: "done", + }, + }); + let submission: SubmissionDocument = { + _id: "submission-1", + submissionId: "submission-1", + projectId: "project-1", + requestIds: ["request-1"], + createdAt: new Date(), + run: { + _id: "submission-run-1", + attemptNumber: 1, + vectorFingerprint: "initial", + requests: [{ requestId: "request-1", runId: "run-1" }], + createdAt: new Date(), + dependencyProjection: [], + blocking: [], + }, + }; + const history = new Map(); + const submissions = { + findOne: vi.fn(async () => structuredClone(submission)), + updateOne: vi.fn(async () => ({ matchedCount: 1, modifiedCount: 1 })), + findOneAndUpdate: vi.fn(async ( + filter: Record, + update: { $set: Record }, + ) => { + if (filter["run._id"] !== submission.run._id) return null; + if (update.$set["run.rollover"]) { + if (submission.run.rollover) return null; + submission = { + ...submission, + run: { + ...submission.run, + rollover: update.$set[ + "run.rollover" + ] as SubmissionDocument["run"]["rollover"], + }, + }; + } else if (update.$set.run) { + if ( + filter["run.rollover.nextSubmissionRunId"] !== + submission.run.rollover?.nextSubmissionRunId + ) { + return null; + } + submission = { + ...submission, + run: update.$set.run as SubmissionDocument["run"], + }; + } else { + submission = { + ...submission, + run: { + ...submission.run, + dependencyProjection: update.$set[ + "run.dependencyProjection" + ] as SubmissionDocument["run"]["dependencyProjection"], + blocking: update.$set[ + "run.blocking" + ] as SubmissionDocument["run"]["blocking"], + }, + }; + } + return structuredClone(submission); + }), + } as unknown as Collection; + const submissionRuns = { + updateOne: vi.fn(async ( + filter: { _id: string }, + update: { $setOnInsert: SubmissionRunHistoryDocument }, + ) => { + if (!history.has(filter._id)) { + history.set(filter._id, structuredClone(update.$setOnInsert)); + } + return { matchedCount: 1, modifiedCount: 1 }; + }), + } as unknown as Collection; + const services = { + find: vi.fn(() => queryResult([])), + findOne: vi.fn(async () => null), + } as unknown as Collection; + let firstCoordinatorReads = 0; + const coordinatorA = new SubmissionCoordinator({ + requests: { + find: vi.fn(() => + queryResult([ + firstCoordinatorReads++ === 0 + ? request("run-2", 2) + : request("run-3", 3), + ]), + ), + } as unknown as Collection, + submissions, + submissionRuns, + services, + }); + const coordinatorB = new SubmissionCoordinator({ + requests: { + find: vi.fn(() => queryResult([request("run-3", 3)])), + } as unknown as Collection, + submissions, + submissionRuns, + services, + }); + + await Promise.all([ + coordinatorA.reconcile("submission-1"), + coordinatorB.reconcile("submission-1"), + ]); + + expect(submission.run.requests).toEqual([ + { requestId: "request-1", runId: "run-3" }, + ]); + expect(submission.run.rollover).toBeUndefined(); + expect(history.size).toBe(2); + const knownRunIds = new Set([...history.keys(), submission.run._id]); + for (const archived of history.values()) { + expect(knownRunIds.has(archived.supersededBySubmissionRunId!)).toBe(true); + } + }); + + it("repairs an interrupted claimed rollover on the next polling reconciliation", async () => { + const requestDocument: RequestDocument = { + _id: "request-1", + projectId: "project-1", + scenario: { task: "Task", criteria: ["criterion"] }, + workerType: "worker", + createdAt: new Date(), + priority: 0, + submissionId: "submission-1", + run: { + _id: "run-2", + attemptNumber: 2, + status: "done", + }, + }; + let submission: SubmissionDocument = { + _id: "submission-1", + submissionId: "submission-1", + projectId: "project-1", + requestIds: ["request-1"], + createdAt: new Date(), + run: { + _id: "submission-run-1", + attemptNumber: 1, + vectorFingerprint: "initial", + requests: [{ requestId: "request-1", runId: "run-1" }], + createdAt: new Date(), + dependencyProjection: [], + blocking: [], + }, + }; + const history = new Map(); + let interruptReplacement = true; + const submissions = { + findOne: vi.fn(async () => structuredClone(submission)), + updateOne: vi.fn(async () => ({ matchedCount: 1, modifiedCount: 1 })), + findOneAndUpdate: vi.fn(async ( + filter: Record, + update: { $set: Record }, + ) => { + if (filter["run._id"] !== submission.run._id) return null; + if (update.$set["run.rollover"]) { + if (submission.run.rollover) return null; + submission = { + ...submission, + run: { + ...submission.run, + rollover: update.$set[ + "run.rollover" + ] as SubmissionDocument["run"]["rollover"], + }, + }; + } else if (update.$set.run) { + if (interruptReplacement) { + interruptReplacement = false; + throw new Error("simulated process interruption"); + } + submission = { + ...submission, + run: update.$set.run as SubmissionDocument["run"], + }; + } else { + submission = { + ...submission, + run: { + ...submission.run, + dependencyProjection: update.$set[ + "run.dependencyProjection" + ] as SubmissionDocument["run"]["dependencyProjection"], + blocking: update.$set[ + "run.blocking" + ] as SubmissionDocument["run"]["blocking"], + }, + }; + } + return structuredClone(submission); + }), + } as unknown as Collection; + const submissionRuns = { + updateOne: vi.fn(async ( + filter: { _id: string }, + update: { $setOnInsert: SubmissionRunHistoryDocument }, + ) => { + if (!history.has(filter._id)) { + history.set(filter._id, structuredClone(update.$setOnInsert)); + } + return { matchedCount: 1, modifiedCount: 1 }; + }), + } as unknown as Collection; + const collections = { + requests: { + find: vi.fn(() => queryResult([requestDocument])), + } as unknown as Collection, + submissions, + submissionRuns, + services: { + find: vi.fn(() => queryResult([])), + findOne: vi.fn(async () => null), + } as unknown as Collection, + }; + + await expect( + new SubmissionCoordinator(collections).reconcile("submission-1"), + ).rejects.toThrow("simulated process interruption"); + expect(submission.run.rollover).toBeDefined(); + expect(history.size).toBe(1); + + const repaired = await new SubmissionCoordinator(collections).reconcile( + "submission-1", + ); + + expect(repaired?.submission.run.attemptNumber).toBe(2); + expect(repaired?.submission.run.requests).toEqual([ + { requestId: "request-1", runId: "run-2" }, + ]); + expect(repaired?.submission.run.rollover).toBeUndefined(); + expect(history.get("submission-run-1")?.supersededBySubmissionRunId).toBe( + repaired?.submission.run._id, + ); + }); + + it("recovers an interrupted final submission write only for complete native request groups", async () => { + const requests: RequestDocument[] = [ + { + _id: "request-1", + projectId: "project-1", + scenario: { task: "Task", criteria: ["criterion"] }, + workerType: "worker", + createdAt: new Date(), + priority: 0, + submissionId: "submission-1", + submissionExpectedRequestCount: 2, + submissionRequestIndex: 0, + submissionInitialRunId: "run-1", + run: { _id: "retried-run", attemptNumber: 2, status: "pending" }, + }, + { + _id: "request-2", + projectId: "project-1", + scenario: { task: "Task", criteria: ["criterion"] }, + workerType: "worker", + createdAt: new Date(), + priority: 0, + submissionId: "submission-1", + submissionExpectedRequestCount: 2, + submissionRequestIndex: 1, + submissionInitialRunId: "run-2", + run: { _id: "run-2", attemptNumber: 1, status: "pending" }, + }, + ]; + let stored: SubmissionDocument | null = null; + const updateMany = vi.fn(async () => ({ modifiedCount: 2 })); + const coordinator = new SubmissionCoordinator({ + requests: { + find: vi.fn(() => queryResult(requests)), + updateMany, + } as unknown as Collection, + submissions: { + findOne: vi.fn(async () => stored), + updateOne: vi.fn(async ( + _filter: unknown, + update: { $setOnInsert: SubmissionDocument }, + ) => { + stored ??= update.$setOnInsert; + return { upsertedCount: 1 }; + }), + } as unknown as Collection, + submissionRuns: {} as Collection, + services: {} as Collection, + }); + + expect(await coordinator.recoverMissingNativeSubmissions()).toBe(1); + expect(stored).not.toBeNull(); + const recovered = stored as SubmissionDocument | null; + expect(recovered?.requestIds).toEqual(["request-1", "request-2"]); + expect(recovered?.run.requests).toEqual([ + { requestId: "request-1", runId: "run-1" }, + { requestId: "request-2", runId: "run-2" }, + ]); + expect(await coordinator.recoverMissingNativeSubmissions()).toBe(1); + expect(updateMany).toHaveBeenCalledTimes(2); + expect(updateMany).toHaveBeenCalledWith( + expect.objectContaining({ + submissionId: "submission-1", + submissionFinalizedAt: { $exists: false }, + }), + expect.objectContaining({ $set: { submissionFinalizedAt: expect.any(Date) } }), + ); + }); +}); diff --git a/packages/shared/src/submissions/submission-coordinator.ts b/packages/shared/src/submissions/submission-coordinator.ts new file mode 100644 index 000000000..5720a744a --- /dev/null +++ b/packages/shared/src/submissions/submission-coordinator.ts @@ -0,0 +1,573 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { v5 as uuidv5 } from "uuid"; +import type { Collection, Document } from "mongodb"; +import type { + HandlerServiceDocument, + RequestDocument, + SubmissionDocument, + SubmissionHandlerServiceDocument, + SubmissionQueueMessagePayload, + SubmissionReportPointer, + SubmissionRunHistoryDocument, + SubmissionRunState, + ServiceHandlerDocument, +} from "../types/types.js"; +import { + OBSERVATIONS_HANDLER_ID, + READOUT_HANDLER_ID, + computeSubmissionVectorFingerprint, + deriveSubmissionReadiness, + projectSubmissionDependency, +} from "./submission-state.js"; + +const SUBMISSION_RUN_NAMESPACE = "6b0f8a6a-5cda-4cb4-bcc4-79bb0ac7f54d"; + +export interface SubmissionCollections { + requests: Collection; + submissions: Collection; + submissionRuns: Collection; + services: Collection; +} + +export type EnqueueSubmission = ( + service: SubmissionHandlerServiceDocument, + message: SubmissionQueueMessagePayload, +) => Promise; + +export interface ReconcileSubmissionResult { + submission: SubmissionDocument; + readiness: ReturnType; + rolled: boolean; + dispatched: boolean; +} + +function submissionRunId( + submissionId: string, + attemptNumber: number, + vectorFingerprint: string, +): string { + return uuidv5( + `${submissionId}:${attemptNumber}:${vectorFingerprint}`, + SUBMISSION_RUN_NAMESPACE, + ); +} + +function initialSubmissionRun( + submissionId: string, + requests: Array<{ requestId: string; runId: string }>, + createdAt: Date, +): SubmissionRunState { + const vectorFingerprint = computeSubmissionVectorFingerprint(requests); + return { + _id: submissionRunId(submissionId, 1, vectorFingerprint), + attemptNumber: 1, + vectorFingerprint, + requests, + createdAt, + dependencyProjection: [], + blocking: [], + }; +} + +export async function ensureNativeSubmission(input: { + collections: Pick; + submissionId: string; + projectId: string; + requests: Array<{ requestId: string; runId: string }>; + createdAt?: Date; +}): Promise { + const requestIds = input.requests.map((request) => request.requestId); + const createdAt = input.createdAt ?? new Date(); + const doc: SubmissionDocument = { + _id: input.submissionId, + submissionId: input.submissionId, + projectId: input.projectId, + requestIds, + createdAt, + run: initialSubmissionRun(input.submissionId, input.requests, createdAt), + }; + await input.collections.submissions.updateOne( + { _id: input.submissionId } as Document, + { $setOnInsert: doc } as Document, + { upsert: true }, + ); + const persisted = await input.collections.submissions.findOne({ + _id: input.submissionId, + } as Document); + if (!persisted) { + throw new Error(`Submission ${input.submissionId} was not persisted`); + } + const sameProject = persisted.projectId === input.projectId; + const sameRequests = + persisted.requestIds.length === requestIds.length && + persisted.requestIds.every((requestId, index) => requestId === requestIds[index]); + const sameInitialVector = + persisted.run.attemptNumber > 1 || + (persisted.run.requests.length === input.requests.length && + persisted.run.requests.every((request, index) => { + const expected = input.requests[index]; + return ( + request.requestId === expected?.requestId && + request.runId === expected.runId + ); + })); + if (!sameProject || !sameRequests || !sameInitialVector) { + throw new Error( + `Submission ${input.submissionId} already exists with a different immutable request vector`, + ); + } + return persisted; +} + +async function loadPostProcessHandlers( + services: Collection, +): Promise { + const documents = await services + .find({ type: "post-process-handler" }) + .toArray(); + return documents.filter( + (document): document is HandlerServiceDocument => + document.type === "post-process-handler", + ); +} + +async function loadReadoutService( + services: Collection, +): Promise { + const document = await services.findOne({ + _id: READOUT_HANDLER_ID, + type: "submission-handler", + }); + return document?.type === "submission-handler" ? document : null; +} + +async function archiveAndRoll(input: { + collections: SubmissionCollections; + submission: SubmissionDocument; + requests: Array<{ requestId: string; runId: string }>; + reason: "request-vector-changed" | "manual-retry"; +}): Promise { + let claimed = input.submission; + if (!claimed.run.rollover) { + const claimedAt = new Date(); + const nextAttemptNumber = claimed.run.attemptNumber + 1; + const vectorFingerprint = computeSubmissionVectorFingerprint(input.requests); + const nextSubmissionRunId = submissionRunId( + claimed._id, + nextAttemptNumber, + vectorFingerprint, + ); + const claimedDocument = await input.collections.submissions.findOneAndUpdate( + { + _id: claimed._id, + "run._id": claimed.run._id, + "run.vectorFingerprint": claimed.run.vectorFingerprint, + "run.rollover": { $exists: false }, + } as Document, + { + $set: { + "run.rollover": { + nextSubmissionRunId, + vectorFingerprint, + requests: input.requests, + reason: input.reason, + claimedAt, + }, + "run.updatedAt": claimedAt, + updatedAt: claimedAt, + }, + } as Document, + { returnDocument: "after" }, + ); + if (!claimedDocument) return null; + claimed = claimedDocument; + } + const rollover = claimed.run.rollover; + if (!rollover) return null; + const { rollover: _rollover, reconcileAfter: _reconcileAfter, ...archivedRun } = + claimed.run; + const archived: SubmissionRunHistoryDocument = { + ...archivedRun, + submissionId: claimed._id, + projectId: claimed.projectId, + supersededAt: rollover.claimedAt, + supersededBySubmissionRunId: rollover.nextSubmissionRunId, + supersededReason: rollover.reason, + }; + await input.collections.submissionRuns.updateOne( + { _id: archived._id } as Document, + { $setOnInsert: archived } as Document, + { upsert: true }, + ); + + const nextRun: SubmissionRunState = { + _id: rollover.nextSubmissionRunId, + attemptNumber: claimed.run.attemptNumber + 1, + vectorFingerprint: rollover.vectorFingerprint, + requests: rollover.requests, + createdAt: rollover.claimedAt, + dependencyProjection: [], + blocking: [], + }; + const updated = await input.collections.submissions.findOneAndUpdate( + { + _id: claimed._id, + "run._id": claimed.run._id, + "run.rollover.nextSubmissionRunId": rollover.nextSubmissionRunId, + } as Document, + { + $set: { + run: nextRun, + updatedAt: rollover.claimedAt, + }, + } as Document, + { returnDocument: "after" }, + ); + return updated; +} + +export class SubmissionCoordinator { + private recoveryAfterRequestId: string | null = null; + + constructor( + private readonly collections: SubmissionCollections, + private readonly enqueue?: EnqueueSubmission, + ) {} + + async recoverMissingNativeSubmissions(limit = 30): Promise { + const filter: Document = { + submissionId: { $exists: true }, + submissionExpectedRequestCount: { $exists: true }, + submissionFinalizedAt: { $exists: false }, + deletedAt: { $exists: false }, + ...(this.recoveryAfterRequestId + ? { _id: { $gt: this.recoveryAfterRequestId } } + : {}), + }; + const candidates = await this.collections.requests + .find(filter) + .project({ + _id: 1, + projectId: 1, + submissionId: 1, + submissionExpectedRequestCount: 1, + submissionRequestIndex: 1, + submissionInitialRunId: 1, + "run._id": 1, + createdAt: 1, + }) + .sort({ _id: 1 }) + .limit(limit) + .toArray(); + this.recoveryAfterRequestId = + candidates.length === limit ? candidates.at(-1)?._id ?? null : null; + let recovered = 0; + const visited = new Set(); + for (const candidate of candidates) { + const submissionId = candidate.submissionId; + const expected = candidate.submissionExpectedRequestCount; + if (!submissionId || !expected || visited.has(submissionId)) continue; + visited.add(submissionId); + const requests = await this.collections.requests + .find({ + submissionId, + projectId: candidate.projectId, + submissionExpectedRequestCount: expected, + deletedAt: { $exists: false }, + } as Document) + .sort({ submissionRequestIndex: 1, _id: 1 }) + .toArray(); + if ( + requests.length !== expected || + requests.some( + (request, index) => + request.submissionRequestIndex !== index || + !request.submissionInitialRunId, + ) + ) { + continue; + } + await ensureNativeSubmission({ + collections: this.collections, + submissionId, + projectId: candidate.projectId, + requests: requests.map((request) => ({ + requestId: request._id, + runId: request.submissionInitialRunId!, + })), + createdAt: requests[0]?.createdAt, + }); + await this.collections.requests.updateMany( + { + submissionId, + projectId: candidate.projectId, + submissionExpectedRequestCount: expected, + submissionFinalizedAt: { $exists: false }, + } as Document, + { $set: { submissionFinalizedAt: new Date() } } as Document, + ); + recovered++; + } + return recovered; + } + + async reconcile(submissionId: string): Promise { + let rolled = false; + for (let attempt = 0; attempt < 4; attempt++) { + const submission = await this.collections.submissions.findOne({ + _id: submissionId, + } as Document); + if (!submission) return null; + if ( + submission.run.reconcileAfter && + submission.run.reconcileAfter.getTime() > Date.now() + ) { + return { + submission, + readiness: deriveSubmissionReadiness(submission.run), + rolled, + dispatched: false, + }; + } + if (submission.run.reconcileAfter) { + await this.collections.submissions.updateOne( + { _id: submissionId, "run._id": submission.run._id } as Document, + { + $unset: { "run.reconcileAfter": "" }, + $set: { updatedAt: new Date() }, + } as Document, + ); + delete submission.run.reconcileAfter; + } + if (submission.run.rollover) { + const updated = await archiveAndRoll({ + collections: this.collections, + submission, + requests: submission.run.rollover.requests, + reason: submission.run.rollover.reason, + }); + rolled = true; + if (!updated) continue; + continue; + } + + const requestDocs = await this.collections.requests + .find({ + _id: { $in: submission.requestIds }, + projectId: submission.projectId, + deletedAt: { $exists: false }, + } as Document) + .toArray(); + const byId = new Map(requestDocs.map((request) => [request._id, request])); + const latestVector = submission.requestIds.flatMap((requestId) => { + const runId = byId.get(requestId)?.run?._id; + return runId ? [{ requestId, runId }] : []; + }); + const latestFingerprint = + latestVector.length === submission.requestIds.length + ? computeSubmissionVectorFingerprint(latestVector) + : submission.run.vectorFingerprint; + + if ( + latestVector.length === submission.requestIds.length && + latestFingerprint !== submission.run.vectorFingerprint + ) { + const updated = await archiveAndRoll({ + collections: this.collections, + submission, + requests: latestVector, + reason: "request-vector-changed", + }); + rolled = true; + if (!updated) continue; + continue; + } + + const handlers = await loadPostProcessHandlers(this.collections.services); + const projected = submission.run.requests.map((ref) => + projectSubmissionDependency({ + requestId: ref.requestId, + expectedRunId: ref.runId, + run: byId.get(ref.requestId)?.run, + handlers, + handlerId: OBSERVATIONS_HANDLER_ID, + }), + ); + const dependencyProjection = projected.map((result) => result.projection); + const blocking = projected.flatMap((result) => + result.blocking ? [result.blocking] : [], + ); + const now = new Date(); + const refreshed = await this.collections.submissions.findOneAndUpdate( + { _id: submissionId, "run._id": submission.run._id } as Document, + { + $set: { + "run.dependencyProjection": dependencyProjection, + "run.blocking": blocking, + "run.updatedAt": now, + updatedAt: now, + }, + } as Document, + { returnDocument: "after" }, + ); + if (!refreshed) continue; + + let dispatched = false; + const readiness = deriveSubmissionReadiness(refreshed.run); + if (readiness === "ready" && this.enqueue) { + const service = await loadReadoutService(this.collections.services); + const existing = refreshed.run.handlerStatus?.[READOUT_HANDLER_ID]; + const eligible = + service && + (!existing || + (service.autoBackfill && + existing.status === "done" && + (existing.version ?? 0) < service.version)); + if (service && eligible) { + await this.enqueue(service, { + type: service.selector, + submissionId, + submissionRunId: refreshed.run._id, + }); + const queuedAt = new Date(); + const marked = await this.collections.submissions.updateOne( + { + _id: submissionId, + "run._id": refreshed.run._id, + [`run.handlerStatus.${READOUT_HANDLER_ID}.status`]: { + $nin: ["queued", "processing", "failed"], + }, + } as Document, + { + $set: { + [`run.handlerStatus.${READOUT_HANDLER_ID}`]: { + status: "queued", + version: service.version, + updatedAt: queuedAt, + }, + "run.updatedAt": queuedAt, + updatedAt: queuedAt, + }, + } as Document, + ); + dispatched = marked.modifiedCount === 1; + } + } + const finalSubmission = dispatched + ? await this.collections.submissions.findOne({ _id: submissionId } as Document) + : refreshed; + if (!finalSubmission) return null; + return { + submission: finalSubmission, + readiness: deriveSubmissionReadiness(finalSubmission.run), + rolled, + dispatched, + }; + } + throw new Error(`Submission ${submissionId} could not be reconciled after concurrent updates`); + } + + async retryCurrent( + submissionId: string, + expectedSubmissionRunId: string, + ): Promise { + const reconciled = await this.reconcile(submissionId); + if (!reconciled) return null; + if (reconciled.submission.run._id !== expectedSubmissionRunId) { + return reconciled; + } + if (reconciled.readiness === "blocked" || reconciled.readiness === "waiting") { + return reconciled; + } + const rolled = await archiveAndRoll({ + collections: this.collections, + submission: reconciled.submission, + requests: reconciled.submission.run.requests, + reason: "manual-retry", + }); + if (!rolled) return this.reconcile(submissionId); + return this.reconcile(submissionId); + } +} + +export async function claimSubmissionHandler(input: { + submissions: Collection; + submissionId: string; + submissionRunId: string; + handlerId: string; + version: number; +}): Promise { + const now = new Date(); + return input.submissions.findOneAndUpdate( + { + _id: input.submissionId, + "run._id": input.submissionRunId, + "run.rollover": { $exists: false }, + [`run.handlerStatus.${input.handlerId}.status`]: { $in: ["queued"] }, + } as Document, + { + $set: { + [`run.handlerStatus.${input.handlerId}`]: { + status: "processing", + version: input.version, + updatedAt: now, + }, + "run.startedAt": now, + "run.updatedAt": now, + updatedAt: now, + }, + } as Document, + { returnDocument: "after" }, + ); +} + +export async function isCurrentSubmissionRun(input: { + submissions: Collection; + submissionId: string; + submissionRunId: string; +}): Promise { + return Boolean( + await input.submissions.findOne({ + _id: input.submissionId, + "run._id": input.submissionRunId, + "run.rollover": { $exists: false }, + } as Document), + ); +} + +export async function completeSubmissionHandler(input: { + submissions: Collection; + submissionId: string; + submissionRunId: string; + handlerId: string; + status: "done" | "failed"; + version: number; + error?: string; + report?: SubmissionReportPointer; +}): Promise { + const now = new Date(); + const set: Record = { + [`run.handlerStatus.${input.handlerId}`]: { + status: input.status, + version: input.version, + updatedAt: now, + ...(input.error ? { error: input.error } : {}), + }, + "run.updatedAt": now, + "run.finishedAt": now, + updatedAt: now, + }; + if (input.report) set["run.report"] = input.report; + const result = await input.submissions.updateOne( + { + _id: input.submissionId, + "run._id": input.submissionRunId, + "run.rollover": { $exists: false }, + [`run.handlerStatus.${input.handlerId}.status`]: "processing", + } as Document, + { $set: set } as Document, + ); + return result.modifiedCount === 1; +} diff --git a/packages/shared/src/submissions/submission-state.test.ts b/packages/shared/src/submissions/submission-state.test.ts new file mode 100644 index 000000000..854558c68 --- /dev/null +++ b/packages/shared/src/submissions/submission-state.test.ts @@ -0,0 +1,155 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { describe, expect, it } from "vitest"; +import type { HandlerServiceDocument, RunState, SubmissionRunState } from "../types/types.js"; +import { + OBSERVATIONS_HANDLER_ID, + READOUT_HANDLER_ID, + computeSubmissionVectorFingerprint, + deriveSubmissionReadiness, + evaluateNamedHandlerState, + isHandlerDagDrained, + projectSubmissionDependency, +} from "./submission-state.js"; + +const handlers: HandlerServiceDocument[] = [ + { + _id: "pp-atif", + type: "post-process-handler", + version: 1, + queue: "post-processor", + selector: "atif", + autoBackfill: true, + dependsOn: [], + }, + { + _id: OBSERVATIONS_HANDLER_ID, + type: "post-process-handler", + version: 1, + queue: "post-processor", + selector: "observations", + autoBackfill: true, + dependsOn: ["pp-atif"], + }, +]; + +function run(handlerStatus: RunState["handlerStatus"]): RunState { + return { + _id: "run-1", + attemptNumber: 1, + status: "done", + outcome: "failed", + handlerStatus, + observationResults: [ + { criterionId: "observation-1", passed: false, feedback: "evidence", evaluated: true }, + ], + }; +} + +describe("submission state helpers", () => { + it("fingerprints vectors deterministically independent of request order", () => { + expect( + computeSubmissionVectorFingerprint([ + { requestId: "b", runId: "2" }, + { requestId: "a", runId: "1" }, + ]), + ).toBe( + computeSubmissionVectorFingerprint([ + { requestId: "a", runId: "1" }, + { requestId: "b", runId: "2" }, + ]), + ); + }); + + it("treats completed observations as ready even for failed coding outcomes and passed:false evidence", () => { + const result = projectSubmissionDependency({ + requestId: "request-1", + expectedRunId: "run-1", + run: run({ + [OBSERVATIONS_HANDLER_ID]: { status: "done", version: 1 }, + unrelated: { status: "failed", error: "ignored" }, + }), + handlers, + }); + + expect(result).toEqual({ + projection: { + requestId: "request-1", + runId: "run-1", + handlerId: OBSERVATIONS_HANDLER_ID, + state: "ready", + version: 1, + }, + drifted: false, + }); + }); + + it("blocks when observations fail or are blocked by a failed dependency", () => { + expect( + evaluateNamedHandlerState( + OBSERVATIONS_HANDLER_ID, + handlers, + { [OBSERVATIONS_HANDLER_ID]: { status: "failed" } }, + ), + ).toBe("failed"); + expect( + evaluateNamedHandlerState( + OBSERVATIONS_HANDLER_ID, + handlers, + { "pp-atif": { status: "failed" } }, + ), + ).toBe("blocked"); + }); + + it("reuses named-handler DAG semantics for existing report triggering", () => { + expect( + isHandlerDagDrained(handlers, { + "pp-atif": { status: "failed" }, + }), + ).toBe(true); + expect( + isHandlerDagDrained(handlers, { + "pp-atif": { status: "processing" }, + }), + ).toBe(false); + }); + + it("detects exact run drift", () => { + const result = projectSubmissionDependency({ + requestId: "request-1", + expectedRunId: "old-run", + run: run({ [OBSERVATIONS_HANDLER_ID]: { status: "done" } }), + handlers, + }); + expect(result.drifted).toBe(true); + expect(result.blocking?.reason).toBe("run-changed"); + }); + + it("derives submission readiness from dependencies and readout progress", () => { + const base: SubmissionRunState = { + _id: "submission-run-1", + attemptNumber: 1, + vectorFingerprint: "fingerprint", + requests: [{ requestId: "request-1", runId: "run-1" }], + createdAt: new Date(), + dependencyProjection: [{ + requestId: "request-1", + runId: "run-1", + handlerId: OBSERVATIONS_HANDLER_ID, + state: "ready", + }], + blocking: [], + }; + + expect(deriveSubmissionReadiness(base)).toBe("ready"); + expect(deriveSubmissionReadiness({ + ...base, + handlerStatus: { [READOUT_HANDLER_ID]: { status: "processing" } }, + })).toBe("processing"); + expect(deriveSubmissionReadiness({ + ...base, + handlerStatus: { [READOUT_HANDLER_ID]: { status: "done" } }, + })).toBe("done"); + }); +}); diff --git a/packages/shared/src/submissions/submission-state.ts b/packages/shared/src/submissions/submission-state.ts new file mode 100644 index 000000000..cbaf44452 --- /dev/null +++ b/packages/shared/src/submissions/submission-state.ts @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import type { + HandlerRunStatus, + HandlerServiceDocument, + RunState, + SubmissionBlockingDetail, + SubmissionDependencyProjection, + SubmissionHandlerState, + SubmissionReadiness, + SubmissionRequestRef, + SubmissionRunState, +} from "../types/types.js"; +import { DependencyGraph } from "../graph/dependency-graph.js"; + +export const OBSERVATIONS_HANDLER_ID = "pp-observations"; +export const READOUT_HANDLER_ID = "pp-readout"; + +export function computeSubmissionVectorFingerprint( + requests: readonly SubmissionRequestRef[], +): string { + const canonical = [...requests] + .sort((left, right) => left.requestId.localeCompare(right.requestId)) + .map(({ requestId, runId }) => `${requestId}:${runId}`) + .join("\n"); + let hash = 0xcbf29ce484222325n; + for (let index = 0; index < canonical.length; index++) { + hash ^= BigInt(canonical.charCodeAt(index)); + hash = BigInt.asUintN(64, hash * 0x100000001b3n); + } + return hash.toString(16).padStart(16, "0"); +} + +export function evaluateNamedHandlerState( + handlerId: string, + handlers: readonly HandlerServiceDocument[], + handlerStatus: Record | undefined, +): SubmissionHandlerState { + const status = handlerStatus?.[handlerId]; + if (status?.status === "done") return "ready"; + if (status?.status === "failed") return "failed"; + + const graph = new DependencyGraph( + handlers.map((handler) => ({ + id: handler._id, + dependsOn: handler.dependsOn, + })), + ); + + if (!handlers.some((handler) => handler._id === handlerId)) { + return "waiting"; + } + + for (const ancestorId of graph.getAncestors(handlerId)) { + if (handlerStatus?.[ancestorId]?.status === "failed") return "blocked"; + } + return "waiting"; +} + +function isTerminalHandlerState( + handlerId: string, + graph: DependencyGraph, + handlerStatus: Record | undefined, +): boolean { + const status = handlerStatus?.[handlerId]?.status; + if (status === "done" || status === "failed") return true; + if (status !== undefined) return false; + for (const ancestorId of graph.getAncestors(handlerId)) { + if (handlerStatus?.[ancestorId]?.status === "failed") return true; + } + return false; +} + +export function isHandlerDagDrained( + handlers: readonly HandlerServiceDocument[], + handlerStatus: Record | undefined, +): boolean { + const graph = new DependencyGraph( + handlers.map((handler) => ({ + id: handler._id, + dependsOn: handler.dependsOn, + })), + ); + return handlers.every((handler) => + isTerminalHandlerState(handler._id, graph, handlerStatus), + ); +} + +export function projectSubmissionDependency(input: { + requestId: string; + expectedRunId: string; + run?: RunState; + handlers: readonly HandlerServiceDocument[]; + handlerId?: string; +}): { + projection: SubmissionDependencyProjection; + blocking?: SubmissionBlockingDetail; + drifted: boolean; +} { + const handlerId = input.handlerId ?? OBSERVATIONS_HANDLER_ID; + if (!input.run) { + return { + projection: { + requestId: input.requestId, + runId: input.expectedRunId, + handlerId, + state: "blocked", + }, + blocking: { + requestId: input.requestId, + runId: input.expectedRunId, + handlerId, + reason: "request-missing", + }, + drifted: false, + }; + } + if (input.run._id !== input.expectedRunId) { + return { + projection: { + requestId: input.requestId, + runId: input.expectedRunId, + handlerId, + state: "blocked", + }, + blocking: { + requestId: input.requestId, + runId: input.expectedRunId, + handlerId, + reason: "run-changed", + }, + drifted: true, + }; + } + + const source = input.run.handlerStatus?.[handlerId]; + const state = evaluateNamedHandlerState( + handlerId, + input.handlers, + input.run.handlerStatus, + ); + const projection: SubmissionDependencyProjection = { + requestId: input.requestId, + runId: input.expectedRunId, + handlerId, + state, + ...(source?.version !== undefined ? { version: source.version } : {}), + ...(source?.updatedAt ? { updatedAt: source.updatedAt } : {}), + ...(source?.error ? { error: source.error } : {}), + }; + if (state !== "failed" && state !== "blocked") { + return { projection, drifted: false }; + } + return { + projection, + blocking: { + requestId: input.requestId, + runId: input.expectedRunId, + handlerId, + reason: state === "failed" ? "dependency-failed" : "dependency-blocked", + ...(source?.error ? { error: source.error } : {}), + }, + drifted: false, + }; +} + +export function deriveSubmissionReadiness(run: SubmissionRunState): SubmissionReadiness { + const readout = run.handlerStatus?.[READOUT_HANDLER_ID]; + if (readout?.status === "done") return "done"; + if (readout?.status === "failed") return "failed"; + if (readout?.status === "queued" || readout?.status === "processing") { + return "processing"; + } + if (run.blocking.length > 0) return "blocked"; + if ( + run.requests.length > 0 && + run.dependencyProjection.length === run.requests.length && + run.dependencyProjection.every((dependency) => dependency.state === "ready") + ) { + return "ready"; + } + return "waiting"; +} diff --git a/packages/shared/src/types/types.ts b/packages/shared/src/types/types.ts index f12651b0b..5f8315307 100644 --- a/packages/shared/src/types/types.ts +++ b/packages/shared/src/types/types.ts @@ -204,7 +204,7 @@ export interface ConversationTurn { timestamp: Date; criteriaResults?: CriterionResult[]; // Per-criterion breakdown from DAG evaluation /** Per-iteration observation results (kind:"observation" criteria), recorded - * by the pp-taxonomy post-processor. Same shape as criteriaResults but never + * by the pp-observations post-processor. Same shape as criteriaResults but never * gates the agent. Empty/absent when no observations were selected. #1156. */ observationResults?: CriterionResult[]; harUrl?: string; // Blob storage URL to the HAR file for this turn @@ -385,6 +385,18 @@ export interface RequestDocument { profileId?: string; // FK → ProfileDocument._id (the profile lineage) profileVersionId?: string; // FK → ProfileVersionDocument._id (exact version used) submissionId?: string; // FK → SubmissionDocument._id + /** Expected native request count for interrupted SubmissionDocument finalization. + * Historical/imported requests omit it and remain view-only if their parent + * submission document is missing. */ + submissionExpectedRequestCount?: number; + /** Stable position within the native submission's immutable request vector. */ + submissionRequestIndex?: number; + /** Run id minted for the submission's first attempt. It remains unchanged + * across request retries so recovery can rebuild the exact initial vector. */ + submissionInitialRunId?: string; + /** Set after the parent SubmissionDocument has been idempotently finalized. + * Missing on interrupted native writes so the scheduler can recover them. */ + submissionFinalizedAt?: Date; /** Scheduling priority. Higher = processed first. Default: 0. */ priority: number; /** @@ -396,7 +408,7 @@ export interface RequestDocument { gates?: GateConfig[]; /** * Observation-criteria ids (kind:"observation") selected at submit. The - * pp-taxonomy post-processor evaluates exactly this set after the run + * pp-observations post-processor evaluates exactly this set after the run * completes and writes per-turn `observationResults`. Empty/absent = none. * See issue #1156. */ @@ -532,7 +544,7 @@ export interface RunState { handlerStatus?: Record; /** Whole-run observation results — one entry per selected `subject:"run"` * observation criterion, evaluated once against the final snapshot + the - * merged trajectory across all iterations by pp-taxonomy. Per-iteration + * merged trajectory across all iterations by pp-observations. Per-iteration * (`subject:"iteration"`) observations live on `turn.observationResults` * instead. Empty/absent when no run-subject observations were selected. #1156. */ observationResults?: CriterionResult[]; @@ -567,6 +579,118 @@ export interface HandlerServiceDocument { dependsOn: string[]; } +export interface SubmissionHandlerServiceDocument { + _id: string; + type: "submission-handler"; + version: number; + queue: string; + selector: string; + autoBackfill: boolean; + dependsOn: string[]; + dependencyMode: "all-runs"; +} + +export type ServiceHandlerDocument = + | HandlerServiceDocument + | SubmissionHandlerServiceDocument; + +export interface SubmissionRequestRef { + requestId: string; + runId: string; +} + +export type SubmissionHandlerState = "waiting" | "ready" | "failed" | "blocked"; + +export interface SubmissionDependencyProjection { + requestId: string; + runId: string; + handlerId: string; + state: SubmissionHandlerState; + version?: number; + updatedAt?: Date; + error?: string; +} + +export interface SubmissionBlockingDetail { + requestId: string; + runId: string; + handlerId: string; + reason: + | "request-missing" + | "run-changed" + | "dependency-not-ready" + | "dependency-failed" + | "dependency-blocked"; + error?: string; +} + +export interface SubmissionReportPointer { + reportId?: string; + url?: string; + updatedAt?: Date; +} + +export interface SubmissionRolloverClaim { + nextSubmissionRunId: string; + vectorFingerprint: string; + requests: SubmissionRequestRef[]; + reason: "request-vector-changed" | "manual-retry"; + claimedAt: Date; +} + +export interface SubmissionRunState { + _id: string; + attemptNumber: number; + vectorFingerprint: string; + requests: SubmissionRequestRef[]; + createdAt: Date; + updatedAt?: Date; + startedAt?: Date; + finishedAt?: Date; + dependencyProjection: SubmissionDependencyProjection[]; + handlerStatus?: Record; + blocking: SubmissionBlockingDetail[]; + report?: SubmissionReportPointer; + /** Internal scheduler hold used by bulk request retry so one completed + * replacement batch produces one vector rollover. Expiry self-heals crashes. */ + reconcileAfter?: Date; + /** Internal resumable rollover claim. Its CAS winner exclusively determines + * the immutable archive's successor metadata. */ + rollover?: SubmissionRolloverClaim; + supersededAt?: Date; + supersededBySubmissionRunId?: string; + supersededReason?: "request-vector-changed" | "manual-retry"; +} + +export interface SubmissionDocument { + _id: string; + submissionId: string; + projectId: string; + requestIds: string[]; + createdAt: Date; + updatedAt?: Date; + run: SubmissionRunState; +} + +export interface SubmissionRunHistoryDocument extends SubmissionRunState { + submissionId: string; + projectId: string; +} + +export type SubmissionReadiness = + | "waiting" + | "ready" + | "blocked" + | "processing" + | "done" + | "failed"; + +export interface SubmissionQueueMessagePayload { + type: string; + submissionId: string; + submissionRunId: string; +} + /** * Field names whose values move from `RequestDocument` (top-level, legacy * shape) into `RequestDocument.run: RunState` (new shape introduced for From 36fb2247b036104b2acf62a1ceead4d671e01942 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Tue, 13 Oct 2026 16:26:26 +0200 Subject: [PATCH 042/210] feat(submissions): orchestrate native submission attempts Finalize every native submit as an exact submission vector, recover interrupted final writes, reconcile and archive vector drift, dispatch only current attempts, and expose project-scoped submission detail, history, and retry APIs with polling repair. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 99f84f04-d3b0-40f1-a254-4dfbd21e4d87 --- apps/api/src/endpoints.test.ts | 64 +++++ apps/api/src/index.ts | 14 ++ apps/api/src/route-context.ts | 6 + apps/api/src/routes/requests/index.ts | 97 +++++++- apps/api/src/routes/submissions.test.ts | 253 ++++++++++++++++++++ apps/api/src/routes/submissions.ts | 245 +++++++++++++++++++ apps/api/src/test-helpers.ts | 34 ++- apps/scheduler/src/index.ts | 44 +++- apps/scheduler/src/notify-routes.ts | 22 +- apps/scheduler/src/submission-dispatcher.ts | 112 +++++++++ docs/architecture/app-design.md | 76 +++++- docs/architecture/overview.md | 10 +- website/src/openapi/scope-openapi.json | 2 +- 13 files changed, 959 insertions(+), 20 deletions(-) create mode 100644 apps/api/src/routes/submissions.test.ts create mode 100644 apps/api/src/routes/submissions.ts create mode 100644 apps/scheduler/src/submission-dispatcher.ts diff --git a/apps/api/src/endpoints.test.ts b/apps/api/src/endpoints.test.ts index 6af7b8cb5..c105562c7 100644 --- a/apps/api/src/endpoints.test.ts +++ b/apps/api/src/endpoints.test.ts @@ -1955,6 +1955,44 @@ describe("API Endpoints", () => { expect(res.status).toBe(201); const doc = (mocks.collection.insertOne as any).mock.calls[0][0]; expect(doc).toHaveProperty("reasoningEffort", "high"); + expect(doc).toHaveProperty("submissionExpectedRequestCount", 1); + const submissionInsert = (mocks.submissionCollection.updateOne as any).mock.calls[0][1].$setOnInsert; + expect(submissionInsert.requestIds).toEqual([doc._id]); + expect(submissionInsert.run.requests).toEqual([ + { requestId: doc._id, runId: doc.run._id }, + ]); + }); + + it("creates one complete submission vector for count fan-out", async () => { + const res = await request(testServer()) + .post(`/api/v1/requests?worker=coder-acp-copilot&projectId=${TEST_PROJECT_ID}`) + .send({ + scenario: { task: "Build something", criteria: ["works"] }, + count: 3, + }); + + expect(res.status).toBe(201); + const docs = (mocks.collection.insertMany as any).mock.calls[0][0]; + expect(docs).toHaveLength(3); + expect(docs.every((doc: { submissionExpectedRequestCount: number }) => + doc.submissionExpectedRequestCount === 3)).toBe(true); + expect( + docs.map((doc: { submissionRequestIndex: number }) => doc.submissionRequestIndex), + ).toEqual([0, 1, 2]); + expect( + docs.every( + (doc: { submissionInitialRunId: string; run: { _id: string } }) => + doc.submissionInitialRunId === doc.run._id, + ), + ).toBe(true); + const submissionInsert = (mocks.submissionCollection.updateOne as any).mock.calls[0][1].$setOnInsert; + expect(submissionInsert.requestIds).toEqual(docs.map((doc: { _id: string }) => doc._id)); + expect(submissionInsert.run.requests).toEqual( + docs.map((doc: { _id: string; run: { _id: string } }) => ({ + requestId: doc._id, + runId: doc.run._id, + })), + ); }); it("profile reasoningEffort takes precedence over client-provided effort", async () => { @@ -2259,6 +2297,7 @@ describe("API Endpoints", () => { new Set(["base-profile", "var-profile"]), ); for (const doc of docs) { + expect(doc.submissionExpectedRequestCount).toBe(2); expect(Array.isArray(doc.gates)).toBe(true); const selectGate = doc.gates.find((g: { gate: string }) => g.gate === "select"); const buildGate = doc.gates.find((g: { gate: string }) => g.gate === "build"); @@ -2269,6 +2308,10 @@ describe("API Endpoints", () => { expect(buildGate.promptId).toBe("tp-build"); expect(buildGate.promptText).toBeUndefined(); } + const submissionInsert = (mocks.submissionCollection.updateOne as any).mock.calls[0][1].$setOnInsert; + expect(submissionInsert.requestIds).toEqual( + docs.map((doc: { _id: string }) => doc._id), + ); // Response surfaces the configured gate count. expect(res.body.gates).toBe(2); }); @@ -2426,6 +2469,9 @@ describe("API Endpoints", () => { expect(insertCall[0]).toHaveProperty("taskPromptId", "tp-123"); expect(insertCall[0]).toHaveProperty("model", "gpt-4o"); expect(insertCall[0]).toHaveProperty("maxIterations", 5); + expect(insertCall[0]).toHaveProperty("submissionExpectedRequestCount", 1); + const submissionInsert = (mocks.submissionCollection.updateOne as any).mock.calls[0][1].$setOnInsert; + expect(submissionInsert.requestIds).toEqual([insertCall[0]._id]); }); it("applies profile override: uses profile fields for worker, model, mcpServers, skillRevisions, extensions", async () => { @@ -2802,11 +2848,13 @@ describe("API Endpoints", () => { it("retries eligible requests and skips non-terminal ones", async () => { const doc1 = { _id: "req-1", + submissionId: "submission-1", workerType: "coder-acp-copilot", run: { _id: "run-1", attemptNumber: 1, status: "done", outcome: "failed" }, }; const doc2 = { _id: "req-2", + submissionId: "submission-1", workerType: "coder-acp-copilot", run: { _id: "run-2", attemptNumber: 1, status: "processing" }, }; @@ -2832,6 +2880,22 @@ describe("API Endpoints", () => { $set: expect.objectContaining({ agentVersion: "1.0.0" }), }), ); + expect(mocks.submissionCollection.updateMany).toHaveBeenNthCalledWith( + 1, + { _id: { $in: ["submission-1"] } }, + expect.objectContaining({ + $set: expect.objectContaining({ + "run.reconcileAfter": expect.any(Date), + }), + }), + ); + expect(mocks.submissionCollection.updateMany).toHaveBeenNthCalledWith( + 2, + { _id: { $in: ["submission-1"] } }, + expect.objectContaining({ + $unset: { "run.reconcileAfter": "" }, + }), + ); }); it("returns 400 when ids array is empty", async () => { diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index 9803a0581..7f95ab2f5 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -47,6 +47,7 @@ import { registerInsightsRoutes } from "./routes/insights.js"; import { registerSecretsRoutes } from "./routes/secrets.js"; import { registerProfilesRoutes } from "./routes/profiles.js"; import { registerProjectsRoutes } from "./routes/projects.js"; +import { registerSubmissionsRoutes } from "./routes/submissions.js"; import { ProjectScopeError } from "./utils/project-scope.js"; import { registerUsersRoutes } from "./routes/users.js"; import { shutdownPortalCopilotClientPool } from "./copilot-client-pool.js"; @@ -59,6 +60,8 @@ import type { InsightDocument, RequestDocument, RunHistoryDocument, + SubmissionDocument, + SubmissionRunHistoryDocument, CodingAgentDocument, ModelDocument, McpServerDocument, @@ -97,6 +100,8 @@ let mongoClient: MongoClient; let db: Db; let collection: Collection; let runsCol: Collection; +let submissionCollection: Collection; +let submissionRunsCollection: Collection; let projectCollection: Collection; let projectStore: ProjectStore; let criteriaCollection: Collection; @@ -144,6 +149,8 @@ async function initializeClients(): Promise { db = mongoClient.db(mongoDatabase); collection = db.collection(mongoCollection); runsCol = db.collection("runs"); + submissionCollection = db.collection("submissions"); + submissionRunsCollection = db.collection("submission-runs"); projectCollection = db.collection("projects"); projectStore = new ProjectStore(projectCollection); criteriaCollection = db.collection("criteria"); @@ -277,6 +284,8 @@ const routeCtx: RouteContext = { get db() { return db; }, get requestCollection() { return collection; }, get runsCollection() { return runsCol; }, + get submissionCollection() { return submissionCollection; }, + get submissionRunsCollection() { return submissionRunsCollection; }, get projectCollection() { return projectCollection; }, get criteriaCollection() { return criteriaCollection; }, get promptFeatureCollection() { return promptFeatureCollection; }, @@ -338,6 +347,7 @@ app.use(createUserAccessMiddleware(() => userAccessResolver)); registerSecretsRoutes(routeCtx); registerSystemRoutes(routeCtx); registerProjectsRoutes(routeCtx); +registerSubmissionsRoutes(routeCtx); registerRequestsRoutes(routeCtx); registerRequestsCancelRoutes(routeCtx); registerRequestsLogsRoutes(routeCtx); @@ -424,6 +434,8 @@ export interface TestDependencies { db?: Db; collection?: Collection; runsCollection?: Collection; + submissionCollection?: Collection; + submissionRunsCollection?: Collection; criteriaCollection?: Collection; promptFeatureCollection?: Collection; reportCollection?: Collection; @@ -465,6 +477,8 @@ export function _injectTestDependencies(deps: TestDependencies): void { if (deps.db) db = deps.db; if (deps.collection) collection = deps.collection; if (deps.runsCollection) runsCol = deps.runsCollection; + if (deps.submissionCollection) submissionCollection = deps.submissionCollection; + if (deps.submissionRunsCollection) submissionRunsCollection = deps.submissionRunsCollection; if (deps.criteriaCollection) criteriaCollection = deps.criteriaCollection; if (deps.promptFeatureCollection) promptFeatureCollection = deps.promptFeatureCollection; if (deps.reportCollection) reportCollection = deps.reportCollection; diff --git a/apps/api/src/route-context.ts b/apps/api/src/route-context.ts index 580eae160..b675e8b9f 100644 --- a/apps/api/src/route-context.ts +++ b/apps/api/src/route-context.ts @@ -52,6 +52,8 @@ import type { ReportTemplateResponseSchema, RequestResponseSchema, RunHistoryDocumentSchema, + SubmissionDocumentSchema, + SubmissionRunHistoryDocumentSchema, } from "shared"; // ─── Document types (inferred from Zod schemas) ───────────────────────────── @@ -74,6 +76,8 @@ export type ReportTrigger = z.infer; export type ReportTemplateDocument = Omit, "_id">; export type RequestDocument = z.infer; export type RunHistoryDocument = z.infer; +export type SubmissionDocument = z.infer; +export type SubmissionRunHistoryDocument = z.infer; export type WorkerType = string; @@ -92,6 +96,8 @@ export interface RouteContext { db: Db; requestCollection: Collection; runsCollection: Collection; + submissionCollection: Collection; + submissionRunsCollection: Collection; projectCollection: Collection; criteriaCollection: Collection; promptFeatureCollection: Collection; diff --git a/apps/api/src/routes/requests/index.ts b/apps/api/src/routes/requests/index.ts index ffb48667d..070a583f3 100644 --- a/apps/api/src/routes/requests/index.ts +++ b/apps/api/src/routes/requests/index.ts @@ -37,6 +37,7 @@ import { isCriterionCompatibleWithGate, orderGates, computeTaskPromptId, + ensureNativeSubmission, } from "shared"; import type { ProfileDocument, @@ -844,6 +845,7 @@ apiRoute(ctx.app, ctx.registry, { const variationResults: Array<{ profileId: string; label?: string; ids: string[] }> = []; const agentsMdPromptId = await resolveAgentsMdPromptId(); const agentsMdFields = buildAgentsMdFields(agentsMdPromptId); + const expectedRequestCount = resolved.length * count; for (const r of resolved) { const newIds: string[] = []; @@ -878,6 +880,9 @@ apiRoute(ctx.app, ctx.registry, { profileVersionId: r.profileVersion.ref ?? r.profileVersion._id, ...(persistedVariationGates ? { gates: persistedVariationGates } : {}), submissionId, + submissionExpectedRequestCount: expectedRequestCount, + submissionRequestIndex: newDocs.length, + submissionInitialRunId: runId, ...agentsMdFields, run: { _id: runId, attemptNumber: 1, status: "pending", logsUrl: ctx.blobStorage.getLogsBlobUrl(`${requestId}/runs/${runId}/run.jsonl`) }, }; @@ -891,6 +896,20 @@ apiRoute(ctx.app, ctx.registry, { } await ctx.requestCollection.insertMany(newDocs); + await ensureNativeSubmission({ + collections: { submissions: ctx.submissionCollection }, + submissionId, + projectId, + requests: newDocs.map((doc) => ({ + requestId: doc._id, + runId: doc.run!._id, + })), + createdAt: newDocs[0]?.createdAt, + }); + await ctx.requestCollection.updateMany( + { _id: { $in: allNewIds }, submissionId }, + { $set: { submissionFinalizedAt: new Date() } }, + ); res.status(201).json({ ids: allNewIds, @@ -1274,7 +1293,7 @@ apiRoute(ctx.app, ctx.registry, { : undefined; // Persisted observation-criteria selection (issue #1156); deduped, evaluated - // by the pp-taxonomy post-processor. Absent/empty = no observations evaluated. + // by the pp-observations post-processor. Absent/empty = no observations evaluated. const persistedObservations: string[] | undefined = observationsProvided ? [...new Set(resolvedObservations)] : undefined; @@ -1316,6 +1335,9 @@ apiRoute(ctx.app, ctx.registry, { ...(persistedGates ? { gates: persistedGates } : {}), ...(persistedObservations ? { observations: persistedObservations } : {}), submissionId, + submissionExpectedRequestCount: count, + submissionRequestIndex: i, + submissionInitialRunId: runId, ...agentsMdFields, // Mint a distinct run id for the first attempt. Blob artifacts // are scoped under `{requestId}/runs/{runId}/...` so retries @@ -1327,6 +1349,20 @@ apiRoute(ctx.app, ctx.registry, { // Bulk insert all documents — scheduler will dispatch to queues await ctx.requestCollection.insertMany(newDocs); + await ensureNativeSubmission({ + collections: { submissions: ctx.submissionCollection }, + submissionId, + projectId, + requests: newDocs.map((doc) => ({ + requestId: doc._id, + runId: doc.run!._id, + })), + createdAt: newDocs[0]?.createdAt, + }); + await ctx.requestCollection.updateMany( + { _id: { $in: newIds }, submissionId }, + { $set: { submissionFinalizedAt: new Date() } }, + ); console.log(`Created ${count} ${mode} requests for ${workerType} (priority: ${requestedPriority ?? 0})`); @@ -1379,6 +1415,9 @@ apiRoute(ctx.app, ctx.registry, { ...(persistedGates ? { gates: persistedGates } : {}), ...(persistedObservations ? { observations: persistedObservations } : {}), submissionId, + submissionExpectedRequestCount: 1, + submissionRequestIndex: 0, + submissionInitialRunId: runId, ...agentsMdFields, // Mint a distinct run id for the first attempt. Blob artifacts // are scoped under `{requestId}/runs/{runId}/...` so retries @@ -1388,6 +1427,17 @@ apiRoute(ctx.app, ctx.registry, { // Store in MongoDB — scheduler will dispatch to queue await ctx.requestCollection.insertOne(requestDoc); + await ensureNativeSubmission({ + collections: { submissions: ctx.submissionCollection }, + submissionId, + projectId, + requests: [{ requestId, runId }], + createdAt: requestDoc.createdAt, + }); + await ctx.requestCollection.updateOne( + { _id: requestId, submissionId }, + { $set: { submissionFinalizedAt: new Date() } }, + ); console.log(`Created ${mode} request ${requestId} for ${workerType} (priority: ${requestedPriority ?? 0})`); @@ -2206,6 +2256,9 @@ apiRoute(ctx.app, ctx.registry, { ...(original.agentsMdPromptId ? { agentsMdPromptId: original.agentsMdPromptId } : {}), ...(original.agentsMdParentIds && original.agentsMdParentIds.length > 0 ? { agentsMdParentIds: original.agentsMdParentIds } : {}), submissionId, + submissionExpectedRequestCount: originalRuns.length * count, + submissionRequestIndex: newDocs.length, + submissionInitialRunId: runId, // Bulk re-submit creates a brand-new request — mint a distinct // run id for the first attempt so blob artifacts live under // `{requestId}/runs/{runId}/...` (independent of the original run). @@ -2219,6 +2272,20 @@ apiRoute(ctx.app, ctx.registry, { // Insert all new documents — scheduler will dispatch to queues if (newDocs.length > 0) { await ctx.requestCollection.insertMany(newDocs); + await ensureNativeSubmission({ + collections: { submissions: ctx.submissionCollection }, + submissionId, + projectId: newDocs[0].projectId, + requests: newDocs.map((doc) => ({ + requestId: doc._id, + runId: doc.run!._id, + })), + createdAt: newDocs[0].createdAt, + }); + await ctx.requestCollection.updateMany( + { _id: { $in: newIds }, submissionId }, + { $set: { submissionFinalizedAt: new Date() } }, + ); } console.log(`Bulk re-submitted ${newIds.length} runs from ${originalRuns.length} originals (count=${count})`); @@ -3129,6 +3196,24 @@ apiRoute(ctx.app, ctx.registry, { { _id: { $in: ids }, deletedAt: { $exists: false } }, ).toArray(); const requestMap = new Map(requests.map((r) => [r._id, r])); + const affectedSubmissionIds = [ + ...new Set( + requests.flatMap((request) => + request.submissionId ? [request.submissionId] : [], + ), + ), + ]; + if (affectedSubmissionIds.length > 0) { + await ctx.submissionCollection.updateMany( + { _id: { $in: affectedSubmissionIds } }, + { + $set: { + "run.reconcileAfter": new Date(Date.now() + 60_000), + updatedAt: new Date(), + }, + }, + ); + } const results: Array<{ requestId: string; runId?: string; attemptNumber?: number; error?: string }> = []; let retried = 0; @@ -3210,6 +3295,16 @@ apiRoute(ctx.app, ctx.registry, { retried++; } + if (affectedSubmissionIds.length > 0) { + await ctx.submissionCollection.updateMany( + { _id: { $in: affectedSubmissionIds } }, + { + $unset: { "run.reconcileAfter": "" }, + $set: { updatedAt: new Date() }, + }, + ); + } + res.status(201).json({ retried, skipped, results }); }, }); diff --git a/apps/api/src/routes/submissions.test.ts b/apps/api/src/routes/submissions.test.ts new file mode 100644 index 000000000..984bdd358 --- /dev/null +++ b/apps/api/src/routes/submissions.test.ts @@ -0,0 +1,253 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { OpenAPIRegistry } from "@asteasolutions/zod-to-openapi"; +import express from "express"; +import request from "supertest"; +import { describe, expect, it, vi } from "vitest"; +import type { Collection, Db } from "mongodb"; +import type { + RequestDocument, + ServiceHandlerDocument, + SubmissionDocument, + SubmissionRunHistoryDocument, +} from "shared"; +import { computeSubmissionVectorFingerprint } from "shared"; +import type { RouteContext } from "../route-context.js"; +import { registerSubmissionsRoutes } from "./submissions.js"; + +function queryResult(items: T[]) { + return { + sort: () => queryResult(items), + limit: () => queryResult(items), + toArray: async () => items, + }; +} + +function buildApp(input: { + requests: RequestDocument[]; + submission: SubmissionDocument; + history?: SubmissionRunHistoryDocument[]; +}) { + let submission = structuredClone(input.submission); + const services: ServiceHandlerDocument[] = [ + { + _id: "pp-atif", + type: "post-process-handler", + version: 1, + queue: "post-processor", + selector: "atif", + autoBackfill: true, + dependsOn: [], + }, + { + _id: "pp-observations", + type: "post-process-handler", + version: 1, + queue: "post-processor", + selector: "observations", + autoBackfill: true, + dependsOn: ["pp-atif"], + }, + ]; + const submissionCollection = { + findOne: vi.fn(async () => structuredClone(submission)), + find: vi.fn(() => queryResult([structuredClone(submission)])), + findOneAndUpdate: vi.fn(async ( + filter: Record, + update: { $set: Record }, + ) => { + if (filter["run._id"] !== submission.run._id) return null; + submission = { + ...submission, + updatedAt: update.$set.updatedAt as Date, + run: { + ...submission.run, + dependencyProjection: update.$set[ + "run.dependencyProjection" + ] as SubmissionDocument["run"]["dependencyProjection"], + blocking: update.$set[ + "run.blocking" + ] as SubmissionDocument["run"]["blocking"], + updatedAt: update.$set["run.updatedAt"] as Date, + }, + }; + return structuredClone(submission); + }), + } as unknown as Collection; + const db = { + collection: vi.fn(() => ({ + find: vi.fn(() => + queryResult(services.filter((service) => service.type === "post-process-handler")), + ), + findOne: vi.fn(async () => null), + })), + } as unknown as Db; + const ctx = { + app: express(), + registry: new OpenAPIRegistry(), + db, + requestCollection: { + find: vi.fn(() => queryResult(input.requests)), + } as unknown as Collection, + submissionCollection, + submissionRunsCollection: { + find: vi.fn(() => queryResult(input.history ?? [])), + findOne: vi.fn(async (filter: { _id: string }) => + (input.history ?? []).find((run) => run._id === filter._id) ?? null, + ), + } as unknown as Collection, + } as unknown as RouteContext; + ctx.app.use(express.json()); + registerSubmissionsRoutes(ctx); + ctx.app.use( + ( + error: Error, + _req: express.Request, + res: express.Response, + _next: express.NextFunction, + ) => res.status(500).json({ error: error.message }), + ); + return ctx.app; +} + +describe("submission routes", () => { + const requestDocument: RequestDocument = { + _id: "request-1", + projectId: "project-1", + scenario: { task: "Implement feature", criteria: ["criterion"] }, + workerType: "worker", + createdAt: new Date(), + priority: 0, + run: { + _id: "run-1", + attemptNumber: 1, + status: "done", + outcome: "failed", + handlerStatus: { + "pp-observations": { status: "done", version: 1 }, + }, + }, + }; + const submissionDocument: SubmissionDocument = { + _id: "submission-1", + submissionId: "submission-1", + projectId: "project-1", + requestIds: ["request-1"], + createdAt: new Date(), + run: { + _id: "submission-run-1", + attemptNumber: 1, + vectorFingerprint: computeSubmissionVectorFingerprint([ + { requestId: "request-1", runId: "run-1" }, + ]), + requests: [{ requestId: "request-1", runId: "run-1" }], + createdAt: new Date(), + dependencyProjection: [], + blocking: [], + }, + }; + + it("returns readiness and the exact request/run vector", async () => { + const response = await request( + buildApp({ + requests: [requestDocument], + submission: submissionDocument, + }), + ).get("/api/v1/submissions/submission-1"); + + expect(response.status, JSON.stringify(response.body)).toBe(200); + expect(response.body).toMatchObject({ + submissionId: "submission-1", + submissionRunId: "submission-run-1", + readiness: "ready", + requests: [{ requestId: "request-1", runId: "run-1", outcome: "failed" }], + dependencyProjection: [{ + requestId: "request-1", + runId: "run-1", + handlerId: "pp-observations", + state: "ready", + }], + }); + }); + + it("lists current and immutable archived attempts", async () => { + const historical: SubmissionRunHistoryDocument = { + ...submissionDocument.run, + _id: "submission-run-0", + attemptNumber: 1, + reconcileAfter: new Date(), + rollover: { + nextSubmissionRunId: "internal-next", + vectorFingerprint: "internal-fingerprint", + requests: [{ requestId: "request-1", runId: "run-1" }], + reason: "request-vector-changed", + claimedAt: new Date(), + }, + submissionId: "submission-1", + projectId: "project-1", + }; + const response = await request( + buildApp({ + requests: [requestDocument], + submission: submissionDocument, + history: [historical], + }), + ).get("/api/v1/submissions/submission-1/runs"); + + expect(response.status).toBe(200); + expect(response.body.runs.map((run: { _id: string }) => run._id)).toEqual([ + "submission-run-1", + "submission-run-0", + ]); + expect(response.body.runs[1]).not.toHaveProperty("reconcileAfter"); + expect(response.body.runs[1]).not.toHaveProperty("rollover"); + }); + + it("rejects a manual retry targeting a stale submission run", async () => { + const response = await request( + buildApp({ + requests: [requestDocument], + submission: submissionDocument, + }), + ) + .post("/api/v1/submissions/submission-1/retry") + .send({ submissionRunId: "stale-submission-run" }); + + expect(response.status).toBe(409); + expect(response.body).toMatchObject({ + error: "Submission attempt is stale", + submissionRunId: "submission-run-1", + }); + }); + + it("returns exact waiting request/run pairs when retry dependencies are not ready", async () => { + const waitingRequest: RequestDocument = { + ...requestDocument, + run: { + _id: "run-1", + attemptNumber: 1, + status: "done", + handlerStatus: {}, + }, + }; + const response = await request( + buildApp({ + requests: [waitingRequest], + submission: submissionDocument, + }), + ) + .post("/api/v1/submissions/submission-1/retry") + .send({ submissionRunId: "submission-run-1" }); + + expect(response.status).toBe(409); + expect(response.body.blocking).toEqual([ + { + requestId: "request-1", + runId: "run-1", + handlerId: "pp-observations", + reason: "dependency-not-ready", + }, + ]); + }); +}); diff --git a/apps/api/src/routes/submissions.ts b/apps/api/src/routes/submissions.ts new file mode 100644 index 000000000..201aae5bd --- /dev/null +++ b/apps/api/src/routes/submissions.ts @@ -0,0 +1,245 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { z } from "zod"; +import { + SubmissionCoordinator, + SubmissionListResponseSchema, + SubmissionResponseSchema, + SubmissionRetryResponseSchema, + SubmissionRunResponseSchema, + type ServiceHandlerDocument, + deriveSubmissionReadiness, +} from "shared"; +import type { SubmissionDocument } from "../route-context.js"; +import type { RouteContext } from "../route-context.js"; +import { apiRoute } from "../openapi/api-route.js"; +import { ProjectIdQuerySchema, getQueryProjectId } from "../utils/project-scope.js"; + +function coordinator(ctx: RouteContext): SubmissionCoordinator { + return new SubmissionCoordinator({ + requests: ctx.requestCollection, + submissions: ctx.submissionCollection, + submissionRuns: ctx.submissionRunsCollection, + services: ctx.db.collection("services"), + }); +} + +function toRunResponse( + run: T, +): Omit { + const { + reconcileAfter: _reconcileAfter, + rollover: _rollover, + ...response + } = run; + return response; +} + +function retryBlocking(submission: SubmissionDocument) { + if (submission.run.blocking.length > 0) return submission.run.blocking; + return submission.run.dependencyProjection + .filter((dependency) => dependency.state !== "ready") + .map((dependency) => ({ + requestId: dependency.requestId, + runId: dependency.runId, + handlerId: dependency.handlerId, + reason: "dependency-not-ready" as const, + ...(dependency.error ? { error: dependency.error } : {}), + })); +} + +async function toResponse(ctx: RouteContext, submission: SubmissionDocument) { + const requestDocs = await ctx.requestCollection + .find({ + _id: { $in: submission.requestIds }, + projectId: submission.projectId, + deletedAt: { $exists: false }, + }) + .toArray(); + const byId = new Map(requestDocs.map((request) => [request._id, request])); + const requests = submission.run.requests.flatMap((ref) => { + const request = byId.get(ref.requestId); + if (!request) return []; + return [{ + requestId: request._id, + runId: ref.runId, + task: request.scenario.task, + status: request.run?.status ?? "unknown", + ...(request.run?.outcome ? { outcome: request.run.outcome } : {}), + workerType: request.workerType, + ...(request.model ? { model: request.model } : {}), + ...(request.profileId ? { profileId: request.profileId } : {}), + }]; + }); + return { + submissionId: submission._id, + projectId: submission.projectId, + requestIds: submission.requestIds, + createdAt: submission.createdAt, + ...(submission.updatedAt ? { updatedAt: submission.updatedAt } : {}), + submissionRunId: submission.run._id, + attemptNumber: submission.run.attemptNumber, + readiness: deriveSubmissionReadiness(submission.run), + requests, + dependencyProjection: submission.run.dependencyProjection, + blocking: submission.run.blocking, + ...(submission.run.handlerStatus + ? { handlerProgress: submission.run.handlerStatus } + : {}), + ...(submission.run.report ? { report: submission.run.report } : {}), + ...(submission.run.supersededAt + ? { supersededAt: submission.run.supersededAt } + : {}), + ...(submission.run.supersededBySubmissionRunId + ? { supersededBySubmissionRunId: submission.run.supersededBySubmissionRunId } + : {}), + ...(submission.run.supersededReason + ? { supersededReason: submission.run.supersededReason } + : {}), + }; +} + +export function registerSubmissionsRoutes(ctx: RouteContext): void { + apiRoute(ctx.app, ctx.registry, { + method: "get", + path: "/api/v1/submissions", + tags: ["Submissions"], + summary: "List submissions", + query: ProjectIdQuerySchema.extend({ + limit: z.coerce.number().int().min(1).max(100).default(50), + }), + response: SubmissionListResponseSchema, + handler: async (req, res) => { + const projectId = getQueryProjectId(req); + const docs = await ctx.submissionCollection + .find({ projectId }) + .sort({ createdAt: -1, _id: -1 }) + .limit(req.query.limit) + .toArray(); + res.json({ + submissions: await Promise.all(docs.map((doc) => toResponse(ctx, doc))), + }); + }, + }); + + apiRoute(ctx.app, ctx.registry, { + method: "get", + path: "/api/v1/submissions/:id", + tags: ["Submissions"], + summary: "Get a submission", + params: z.object({ id: z.string() }), + response: SubmissionResponseSchema, + errorResponses: { 404: { description: "Submission not found" } }, + handler: async (req, res) => { + const reconciled = await coordinator(ctx).reconcile(req.params.id); + if (!reconciled) { + res.status(404).json({ error: "Submission not found" }); + return; + } + res.json(await toResponse(ctx, reconciled.submission)); + }, + }); + + apiRoute(ctx.app, ctx.registry, { + method: "get", + path: "/api/v1/submissions/:id/runs", + tags: ["Submissions"], + summary: "List current and historical submission attempts", + params: z.object({ id: z.string() }), + response: z.object({ runs: z.array(SubmissionRunResponseSchema) }), + errorResponses: { 404: { description: "Submission not found" } }, + handler: async (req, res) => { + const submission = await ctx.submissionCollection.findOne({ _id: req.params.id }); + if (!submission) { + res.status(404).json({ error: "Submission not found" }); + return; + } + const historical = await ctx.submissionRunsCollection + .find({ submissionId: req.params.id }) + .sort({ attemptNumber: -1 }) + .toArray(); + res.json({ + runs: [toRunResponse(submission.run), ...historical.map(toRunResponse)], + }); + }, + }); + + apiRoute(ctx.app, ctx.registry, { + method: "get", + path: "/api/v1/submissions/:id/runs/:submissionRunId", + tags: ["Submissions"], + summary: "Get one submission attempt", + params: z.object({ id: z.string(), submissionRunId: z.string() }), + response: SubmissionRunResponseSchema, + errorResponses: { 404: { description: "Submission attempt not found" } }, + handler: async (req, res) => { + const submission = await ctx.submissionCollection.findOne({ _id: req.params.id }); + if (submission?.run._id === req.params.submissionRunId) { + res.json(toRunResponse(submission.run)); + return; + } + const historical = await ctx.submissionRunsCollection.findOne({ + _id: req.params.submissionRunId, + submissionId: req.params.id, + }); + if (!historical) { + res.status(404).json({ error: "Submission attempt not found" }); + return; + } + res.json(toRunResponse(historical)); + }, + }); + + apiRoute(ctx.app, ctx.registry, { + method: "post", + path: "/api/v1/submissions/:id/retry", + tags: ["Submissions"], + summary: "Retry current submission processing", + params: z.object({ id: z.string() }), + body: z.object({ submissionRunId: z.string() }), + response: SubmissionRetryResponseSchema, + errorResponses: { + 404: { description: "Submission not found" }, + 409: { description: "Submission attempt is stale or dependencies are blocked" }, + }, + handler: async (req, res) => { + const current = await ctx.submissionCollection.findOne({ _id: req.params.id }); + if (!current) { + res.status(404).json({ error: "Submission not found" }); + return; + } + if (current.run._id !== req.body.submissionRunId) { + res.status(409).json({ + error: "Submission attempt is stale", + submissionRunId: current.run._id, + blocking: retryBlocking(current), + }); + return; + } + const result = await coordinator(ctx).retryCurrent( + req.params.id, + req.body.submissionRunId, + ); + if (!result) { + res.status(404).json({ error: "Submission not found" }); + return; + } + if (result.readiness === "blocked" || result.readiness === "waiting") { + res.status(409).json({ + error: "Submission dependencies are not ready", + submissionRunId: result.submission.run._id, + blocking: retryBlocking(result.submission), + }); + return; + } + res.status(201).json({ + submissionId: result.submission._id, + submissionRunId: result.submission.run._id, + attemptNumber: result.submission.run.attemptNumber, + readiness: result.readiness, + blocking: result.submission.run.blocking, + }); + }, + }); +} diff --git a/apps/api/src/test-helpers.ts b/apps/api/src/test-helpers.ts index 023c46b73..74447d6e7 100644 --- a/apps/api/src/test-helpers.ts +++ b/apps/api/src/test-helpers.ts @@ -49,11 +49,29 @@ export function createMockCollection(docs: T[] = insertedCount: 1, acknowledged: true, }), - updateOne: vi.fn().mockResolvedValue({ - matchedCount: 1, - modifiedCount: 1, - acknowledged: true, - }), + updateOne: vi.fn().mockImplementation( + async ( + filter: Record, + update: { $setOnInsert?: T }, + options?: { upsert?: boolean }, + ) => { + const existing = data.find((doc) => doc._id === filter._id); + if (!existing && options?.upsert && update.$setOnInsert) { + data.push({ ...update.$setOnInsert }); + return { + matchedCount: 0, + modifiedCount: 0, + upsertedCount: 1, + acknowledged: true, + }; + } + return { + matchedCount: 1, + modifiedCount: 1, + acknowledged: true, + }; + }, + ), updateMany: vi.fn().mockResolvedValue({ matchedCount: 1, modifiedCount: 1, @@ -204,6 +222,8 @@ export function createAllMockDependencies() { const db = createMockDb(); const collection = createMockCollection(); const runsCollection = createMockCollection(); + const submissionCollection = createMockCollection(); + const submissionRunsCollection = createMockCollection(); const criteriaCollection = createMockCollection(); const promptFeatureCollection = createMockCollection(); const reportCollection = createMockCollection(); @@ -232,6 +252,8 @@ export function createAllMockDependencies() { db, collection, runsCollection, + submissionCollection, + submissionRunsCollection, criteriaCollection, promptFeatureCollection, reportCollection, @@ -262,6 +284,8 @@ export function createAllMockDependencies() { db: ReturnType; collection: Collection; runsCollection: Collection; + submissionCollection: Collection; + submissionRunsCollection: Collection; criteriaCollection: Collection; promptFeatureCollection: Collection; reportCollection: Collection; diff --git a/apps/scheduler/src/index.ts b/apps/scheduler/src/index.ts index 101750a30..9fe0fbf79 100644 --- a/apps/scheduler/src/index.ts +++ b/apps/scheduler/src/index.ts @@ -8,10 +8,16 @@ import { DefaultAzureCredential } from "@azure/identity"; import { RequestScheduler } from "./request-scheduler.js"; import { PostProcessorDispatcher } from "./post-processor-dispatcher.js"; import { HandlerDispatcher } from "./handler-dispatcher.js"; +import { SubmissionDispatcher } from "./submission-dispatcher.js"; import { createHttpServer, type NotifyHandler } from "./notify-routes.js"; import { StuckRunReaper } from "./stuck-run-reaper.js"; import { RedisHeartbeatStore, type HeartbeatStore } from "shared"; -import type { CodingAgentDocument, RequestDocument } from "shared"; +import type { + CodingAgentDocument, + RequestDocument, + SubmissionDocument, + SubmissionRunHistoryDocument, +} from "shared"; import { initTelemetry, trackMetric, trackEvent, shutdownTelemetry } from "telemetry"; // ── Configuration ──────────────────────────────────────────────────── @@ -128,6 +134,9 @@ async function main(): Promise { const db = mongoClient.db(MONGO_DATABASE); const collection = db.collection(MONGO_COLLECTION); const agentCollection = db.collection("agents"); + const submissionCollection = db.collection("submissions"); + const submissionRunsCollection = + db.collection("submission-runs"); // Start the scheduler const scheduler = new RequestScheduler( @@ -191,6 +200,17 @@ async function main(): Promise { `[Scheduler] Handler dispatcher (DAG) started (poll=${ppPollIntervalMs}ms, topologyCacheTtl=${handlerCacheTtlMs}ms)`, ); + const submissionDispatcher = new SubmissionDispatcher( + collection, + submissionCollection, + submissionRunsCollection, + db, + createQueueClient, + ppPollIntervalMs, + ); + submissionDispatcher.start(); + console.log(`[Scheduler] Submission dispatcher started (poll=${ppPollIntervalMs}ms)`); + // Start the stuck-run reaper (authoritative backstop). Redis is non-fatal: // on misconfig or connection failure the reaper self-disables (its sweeps // skip when ping() fails) while the dispatch loop above keeps running. @@ -227,8 +247,25 @@ async function main(): Promise { ); } - // Wire notify handler to the HandlerDispatcher - const httpServer = createHttpServer(handlerDispatcher); + // Run notifications update the run DAG and immediately reconcile the parent + // submission. The polling loop remains the durable safety net. + const notifyHandler: NotifyHandler = { + onRunTerminal: async (requestId, runId) => { + await handlerDispatcher.onRunTerminal(requestId, runId); + await submissionDispatcher.onRequestChanged(requestId); + }, + onHandlerComplete: async (requestId, runId, handlerId, status) => { + await handlerDispatcher.onHandlerComplete( + requestId, + runId, + handlerId, + status, + ); + await submissionDispatcher.onRequestChanged(requestId); + }, + registerHandler: (doc) => handlerDispatcher.registerHandler(doc), + }; + const httpServer = createHttpServer(notifyHandler); httpServer.listen(HEALTH_PORT, () => { console.log(`[Scheduler] HTTP server listening on :${HEALTH_PORT}`); }); @@ -239,6 +276,7 @@ async function main(): Promise { await scheduler.stop(); await postProcessorDispatcher.stop(); await handlerDispatcher.stop(); + await submissionDispatcher.stop(); if (stuckRunReaper) await stuckRunReaper.stop(); if (heartbeatStore) await heartbeatStore.close(); httpServer.close(); diff --git a/apps/scheduler/src/notify-routes.ts b/apps/scheduler/src/notify-routes.ts index b63d13dd9..6810a90c0 100644 --- a/apps/scheduler/src/notify-routes.ts +++ b/apps/scheduler/src/notify-routes.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. import http from "node:http"; -import type { HandlerServiceDocument } from "shared"; +import type { ServiceHandlerDocument } from "shared"; /** * Maximum accepted request body size for the scheduler's HTTP endpoints. @@ -28,7 +28,7 @@ export interface NotifyHandler { handlerId: string, status: "done" | "failed", ): Promise; - registerHandler(doc: HandlerServiceDocument): Promise; + registerHandler(doc: ServiceHandlerDocument): Promise; } interface RunTerminalRequest { @@ -98,7 +98,7 @@ function parseHandlerCompleteRequest(body: unknown): HandlerCompleteRequest | nu }; } -function parseHandlerRegisterRequest(body: unknown): HandlerServiceDocument | null { +function parseHandlerRegisterRequest(body: unknown): ServiceHandlerDocument | null { if (!isRecord(body)) { return null; } @@ -115,7 +115,7 @@ function parseHandlerRegisterRequest(body: unknown): HandlerServiceDocument | nu if ( !isNonEmptyString(_id) || - type !== "post-process-handler" || + (type !== "post-process-handler" && type !== "submission-handler") || typeof version !== "number" || !Number.isFinite(version) || !isNonEmptyString(queue) || @@ -127,15 +127,23 @@ function parseHandlerRegisterRequest(body: unknown): HandlerServiceDocument | nu return null; } - return { + const common = { _id, - type, version, queue, selector, autoBackfill, dependsOn: dependsOn as string[], }; + if (type === "submission-handler") { + if (body.dependencyMode !== "all-runs") return null; + return { + ...common, + type, + dependencyMode: "all-runs", + }; + } + return { ...common, type }; } export function readJsonBody( @@ -262,7 +270,7 @@ export function createHttpServer( if (!parsedBody) { sendJson(res, 400, { error: - "Invalid handler registration: _id, type='post-process-handler', version (number), queue, selector, autoBackfill (boolean), and dependsOn (string[]) are required", + "Invalid handler registration: _id, supported type, version, queue, selector, autoBackfill, dependsOn, and submission dependencyMode when applicable are required", }); return; } diff --git a/apps/scheduler/src/submission-dispatcher.ts b/apps/scheduler/src/submission-dispatcher.ts new file mode 100644 index 000000000..cd2914853 --- /dev/null +++ b/apps/scheduler/src/submission-dispatcher.ts @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import type { QueueClient } from "@azure/storage-queue"; +import type { Collection, Db } from "mongodb"; +import { + SubmissionCoordinator, + type RequestDocument, + type SubmissionDocument, + type SubmissionHandlerServiceDocument, + type SubmissionQueueMessagePayload, + type SubmissionRunHistoryDocument, + type ServiceHandlerDocument, +} from "shared"; + +export class SubmissionDispatcher { + private interval: ReturnType | null = null; + private dispatching = false; + private scanAfterSubmissionId: string | null = null; + private readonly queueClients = new Map(); + private readonly coordinator: SubmissionCoordinator; + + constructor( + private readonly requests: Collection, + private readonly submissions: Collection, + submissionRuns: Collection, + db: Db, + private readonly createQueueClient: (queueName: string) => QueueClient, + private readonly pollIntervalMs = 30_000, + private readonly batchSize = 30, + ) { + this.coordinator = new SubmissionCoordinator( + { + requests, + submissions, + submissionRuns, + services: db.collection("services"), + }, + (service, message) => this.enqueue(service, message), + ); + } + + start(): void { + if (this.interval) return; + this.interval = setInterval(() => this.poll(), this.pollIntervalMs); + void this.poll(); + } + + async stop(): Promise { + if (this.interval) { + clearInterval(this.interval); + this.interval = null; + } + const deadline = Date.now() + 5_000; + while (this.dispatching && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 100)); + } + } + + async onRequestChanged(requestId: string): Promise { + const request = await this.requests.findOne( + { _id: requestId }, + { projection: { submissionId: 1 } }, + ); + if (request?.submissionId) { + await this.coordinator.reconcile(request.submissionId); + } + } + + private async poll(): Promise { + if (this.dispatching) return; + this.dispatching = true; + try { + await this.coordinator.recoverMissingNativeSubmissions(this.batchSize); + const candidates = await this.submissions + .find( + this.scanAfterSubmissionId + ? { _id: { $gt: this.scanAfterSubmissionId } } + : {}, + ) + .sort({ _id: 1 }) + .limit(this.batchSize) + .project({ _id: 1 }) + .toArray(); + this.scanAfterSubmissionId = + candidates.length === this.batchSize + ? candidates.at(-1)?._id ?? null + : null; + for (const candidate of candidates) { + await this.coordinator.reconcile(candidate._id); + } + } catch (error) { + console.error("[SubmissionDispatcher] Poll failed:", error); + } finally { + this.dispatching = false; + } + } + + private async enqueue( + service: SubmissionHandlerServiceDocument, + message: SubmissionQueueMessagePayload, + ): Promise { + let client = this.queueClients.get(service.queue); + if (!client) { + client = this.createQueueClient(service.queue); + await client.createIfNotExists(); + this.queueClients.set(service.queue, client); + } + const encoded = Buffer.from(JSON.stringify(message)).toString("base64"); + await client.sendMessage(encoded); + } +} diff --git a/docs/architecture/app-design.md b/docs/architecture/app-design.md index 8f1d67c01..9ff0c010f 100644 --- a/docs/architecture/app-design.md +++ b/docs/architecture/app-design.md @@ -470,6 +470,78 @@ Profile fan-out mode is also supported for comparative runs: 3. Each expanded request resolves configuration from its variation profile; unpinned specs resolve to `latestVersion` 4. Expanded requests persist `profileId` and `profileVersionId` on each `RequestDocument` for indexing and traceability +### Submission identity and processing attempts + +Every native submit creates a stable `SubmissionDocument`, including one-request +submissions. The API generates the submission id, every request id, and every +initial run id before writing anything. It inserts the requests first, then +idempotently finalizes the submission with: + +- immutable `projectId` and ordered `requestIds`; +- one embedded current `SubmissionRunState`; +- an exact immutable vector of `{ requestId, runId }` pairs for that attempt; +- a deterministic vector fingerprint, dependency projection, blocking details, + submission-level handler status, and report pointers. + +Requests carry `submissionExpectedRequestCount`, `submissionRequestIndex`, and +the immutable `submissionInitialRunId`, then receive `submissionFinalizedAt` +only after the parent document exists. The scheduler uses those markers to +recover the exact initial vector after an interrupted final write, even if a +request has since been retried. It never adopts historical/imported requests +that only have `submissionId`; those remain view-only and non-triggering. + +The current attempt lives only at `SubmissionDocument.run`. When any request's +current run id changes, reconciliation archives the previous attempt to the +immutable `submission-runs` collection and compare-and-swaps a fresh embedded +attempt containing every request's latest run id. The next attempt id is +deterministic for `(submissionId, attemptNumber, vectorFingerprint)`, so a +rollover first claims that successor on the exact current attempt. Only the +claim winner writes the immutable archive's supersession metadata, then swaps +the embedded current attempt. A restart between claim, archive, and swap resumes +the same claimed rollover instead of creating a dangling successor or parallel +current attempt. Claimed attempts reject worker claims/completions, and only the +latest embedded vector without a rollover claim is dispatchable. Individual +retries may therefore leave useful intermediate history. +Bulk request retry places a short, expiring reconciliation hold on each affected +submission while all replacement runs are installed, then releases it so the +completed batch produces one rollover. Polling clears expired holds and repairs +vector drift, missing projections, dropped notifications, and interrupted +archive/swap operations. + +`pp-readout` is a registered `submission-handler` with +`dependencyMode: all-runs` and `dependsOn: [pp-observations]`. Reconciliation +projects the authoritative `run.handlerStatus` for every exact request/run pair: + +- `pp-observations: done` is valid evidence even when the coding outcome failed + or an observation result has `passed: false`; +- a failed `pp-observations`, or one blocked by a failed DAG ancestor, blocks + readout; +- unrelated handler failures do not block; +- completed projections are naturally preserved for request/run pairs whose + run id did not change. + +Submission queue messages are attempt-scoped: +`{ type, submissionId, submissionRunId }`. PR B's worker must claim and complete +with filters on both `submissionId` and `run._id`, call +`isCurrentSubmissionRun()` before expensive work and final publication, and +discard a message when `claimSubmissionHandler()` returns `null`. Final writes +use `completeSubmissionHandler()`, whose compare-and-swap rejects stale +publication after supersession. + +The API exposes: + +- `GET /api/v1/submissions?projectId=...` +- `GET /api/v1/submissions/:id` +- `GET /api/v1/submissions/:id/runs` +- `GET /api/v1/submissions/:id/runs/:submissionRunId` +- `POST /api/v1/submissions/:id/retry` + +Responses expose readiness, exact blocking request/run pairs, handler progress, +supersession metadata, resolved request summaries, and the current report +pointer without queue names or scheduler claim fields. Portal submit flows +navigate to Submission Detail, and the CLI mirrors list/get/history/retry +capabilities under `scope submission`. + ## Runs List Query API `GET /api/v1/requests` powers the Portal **Runs** list and `scope run list`. All @@ -693,9 +765,9 @@ Criteria are reusable evaluation rules stored in the database and optionally def - **Criterion kind** — `kind: "gate" | "observation"` distinguishes criteria that gate the agent from record-only observations. Observation criteria can optionally set `taxonomyElementId` to one of the hard-coded observation dimensions and a `subject` (`run`|`iteration`) that selects whole-run vs per-iteration evaluation; run detail derives dimension grouping by joining each `observationResults[].criterionId` (per-turn or run-level) back to the criterion metadata. - **Kind** — `kind: "gate" | "observation"` (default `gate`). **Gate** criteria steer the coding agent through the gate DAG. **Observation** criteria (issue #1156) are record-only: they produce a boolean + evidence, never feed back to the agent, never pass/fail a gate, and never enter the gate DAG. Dependencies may only reference same-kind criteria. - **Taxonomy classification** — observation criteria carry an optional `taxonomyElementId` from a hard-coded enum of the three R&A Readout quality dimensions (`dimension:idiomatic-use`, `dimension:dependency-currency`, `dimension:configuration-correctness`). Classification is static/design-time, not per-run. -- **Evaluation subject** — `subject: "run" | "iteration"` decides the evaluation granularity of an observation. **`run`** (the default for observations) is evaluated **once** against the final snapshot + the merged trajectory across all iterations and stored at run level (`run.observationResults`); **`iteration`** is evaluated per turn and stored on each turn (`turn.observationResults`). Gate criteria are always `iteration` (the API rejects `run` for gates); `subject` is honored only by the `pp-taxonomy` pipeline. The AI authoring assistant auto-detects the subject and the user can override it. +- **Evaluation subject** — `subject: "run" | "iteration"` decides the evaluation granularity of an observation. **`run`** (the default for observations) is evaluated **once** against the final snapshot + the merged trajectory across all iterations and stored at run level (`run.observationResults`); **`iteration`** is evaluated per turn and stored on each turn (`turn.observationResults`). Gate criteria are always `iteration` (the API rejects `run` for gates); `subject` is honored only by the `pp-observations` pipeline. The AI authoring assistant auto-detects the subject and the user can override it. -Observation evaluation happens off the coding-agent critical path in the `pp-taxonomy` post-processor (see [post-processing](post-processing.md)). A run carries the chosen `observations: string[]` (observation-criteria ids); **iteration-subject** results are stored per turn as `turn.observationResults: CriterionResult[]`, while **run-subject** results are stored once at run level as `run.observationResults: CriterionResult[]` (both the same shape as gate `criteriaResults`). Dimension grouping is derived at read time by joining `criterionId` → criterion `taxonomyElementId`. +Observation evaluation happens off the coding-agent critical path in the `pp-observations` post-processor (see [post-processing](post-processing.md)). A run carries the chosen `observations: string[]` (observation-criteria ids); **iteration-subject** results are stored per turn as `turn.observationResults: CriterionResult[]`, while **run-subject** results are stored once at run level as `run.observationResults: CriterionResult[]` (both the same shape as gate `criteriaResults`). Dimension grouping is derived at read time by joining `criterionId` → criterion `taxonomyElementId`. See [`ENV_VARIABLES.md`](../../scope-mt-app/ENV_VARIABLES.md) for related configuration options. diff --git a/docs/architecture/overview.md b/docs/architecture/overview.md index a5c10eaf6..e6b179e56 100644 --- a/docs/architecture/overview.md +++ b/docs/architecture/overview.md @@ -79,7 +79,7 @@ flowchart TB | `workers/coder-acp-claude-code` | Claude Code agent via Agent Client Protocol (ACP) | | `workers/coder-acp-copilot` | GitHub Copilot agent via Agent Client Protocol (ACP) | | `workers/report-generator` | Copilot SDK worker that generates post-run markdown reports | -| `workers/post-processor` | DAG-based post-run handlers: `pp-atif` (trajectory ATIF) and `pp-taxonomy` (boolean observations via the judge, per-iteration or whole-run by criterion `subject`) | +| `workers/post-processor` | DAG-based post-run handlers: `pp-atif` (trajectory ATIF) and `pp-observations` (boolean observations via the judge, per-iteration or whole-run by criterion `subject`) | | `gateway` | AI Gateway — shared Rust TLS-intercepting proxy with plugin architecture (HAR capture, future: token refresh, rate limiting) | | `evaluations/static-prompts` | Developer-run static prompt quality and user-controlled prompt red-team suites | @@ -115,6 +115,14 @@ walkthrough, failures, cache isolation, and implemented/deferred boundary. 4. **Judge** — After the agent completes, the worker invokes the Judge to evaluate output against criteria. Results (pass/fail per criterion, scores) are persisted to CosmosDB. 5. **Snapshot** — Each iteration's workspace is snapshotted to Blob Storage for later inspection. +Every native submit also creates a stable submission that owns the complete +request set. Submission processing follows the requests' exact current run-id +vector: request retries archive and supersede the previous submission attempt, +run-level `pp-observations` completion feeds an all-runs dependency projection, +and only the embedded current submission attempt may dispatch `pp-readout`. +Portal and CLI users can inspect current/history attempts and retry current +submission processing without mutating request execution history. + > A run may execute as a sequence of **gates** (`Select → Build → Test → Run → > Deploy`), each with its own prompt, criteria subset, and iteration budget, > running stop-on-failure against the same workspace. Requests without an explicit diff --git a/website/src/openapi/scope-openapi.json b/website/src/openapi/scope-openapi.json index ca95e2002..eb0e8dfd8 100644 --- a/website/src/openapi/scope-openapi.json +++ b/website/src/openapi/scope-openapi.json @@ -1 +1 @@ -{"openapi":"3.1.0","info":{"title":"Scope API","version":"1.0.0","description":"REST API for the Scope platform — benchmarking AI coding agents"},"servers":[{"url":"/","description":"Current server"}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Use the unchanged IdP access token, without the Bearer prefix."}},"schemas":{"KeyResponse":{"type":"object","properties":{},"additionalProperties":{}},"KeyInput":{"type":"object","properties":{},"additionalProperties":{}},"ValidateKeyInput":{"type":"object","properties":{"token":{"type":"string"}},"required":["token"]},"AccountResponse":{"type":"object","properties":{},"additionalProperties":{}},"AccountInput":{"type":"object","properties":{},"additionalProperties":{}},"UserMeResponse":{"type":"object","properties":{"id":{"type":"string"},"role":{"type":"string"},"email":{"type":"string"},"displayName":{"type":"string"},"idp":{"type":"string"},"idpTenant":{"type":"string"}},"required":["id"]},"ProjectResponse":{"type":"object","properties":{"_id":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"creator":{"type":"string"},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"deletedAt":{"type":["string","null"],"format":"date-time"}},"required":["_id","name","createdAt"]},"CreateProjectInput":{"type":"object","properties":{"name":{"type":"string","minLength":1},"description":{"type":"string"},"creator":{"type":"string"}},"required":["name"]},"UpdateProjectInput":{"type":"object","properties":{"name":{"type":"string","minLength":1},"description":{"type":"string"}}},"RequestResponse":{"type":"object","properties":{"_id":{"type":"string"},"scenario":{"$ref":"#/components/schemas/Scenario"},"workerType":{"type":"string"},"model":{"type":"string"},"reasoningEffort":{"type":"string"},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"maxIterations":{"type":"number"},"personaInstructions":{"type":"string"},"persona":{"$ref":"#/components/schemas/Persona"},"deletedAt":{"type":["string","null"],"format":"date-time"},"taskPromptId":{"type":"string"},"agentsMdPromptId":{"type":"string"},"agentsMdParentIds":{"type":"array","items":{"type":"string"}},"mcpServers":{"type":"array","items":{"type":"string"}},"skillRevisions":{"type":"array","items":{"type":"string"}},"codebaseRevisionId":{"type":"string"},"resources":{"type":"array","items":{"$ref":"#/components/schemas/ResourceBinding"}},"extensions":{"type":"array","items":{"type":"string"}},"agentVersion":{"type":"string"},"profileId":{"type":"string"},"profileVersionId":{"type":"string"},"submissionId":{"type":"string"},"priority":{"type":"integer","default":0},"gates":{"type":"array","items":{"$ref":"#/components/schemas/GateConfig"}},"observations":{"type":"array","items":{"type":"string"}},"gateSummaries":{"type":"array","items":{"$ref":"#/components/schemas/GateRunSummary"}},"run":{"$ref":"#/components/schemas/RunState"},"projectId":{"type":"string"}},"required":["_id","scenario","workerType","createdAt","projectId"]},"Scenario":{"type":"object","properties":{"version":{"type":"string","enum":["v1","v2"]},"task":{"type":"string"},"criteria":{"type":"array","items":{"type":"string"}}},"required":["task","criteria"]},"Persona":{"type":"object","properties":{"personality":{"type":"string","enum":["demanding","friendly"]},"experience":{"type":"string","enum":["junior","senior"]},"verbosity":{"type":"string","enum":["brief","moderate"]},"type":{"type":"string","enum":["traditional","ai_assisted","vibe"]}},"required":["personality","experience","verbosity","type"]},"ResourceBinding":{"type":"object","properties":{"ref":{"type":"string"},"revisionId":{"type":"string"},"params":{"type":"object","additionalProperties":{"type":"string"}}},"required":["ref","revisionId","params"]},"GateConfig":{"type":"object","properties":{"gate":{"type":"string","enum":["select","build","test","run","deploy"]},"promptId":{"type":"string"},"promptText":{"type":"string"},"criteria":{"type":"array","items":{"type":"string"}},"maxIterations":{"type":"integer","minimum":1,"maximum":50}},"required":["gate","criteria"]},"GateRunSummary":{"type":"object","properties":{"gate":{"type":"string","enum":["select","build","test","run","deploy"]},"status":{"type":"string","enum":["passed","failed","skipped"]},"iterations":{"type":"integer","minimum":0}},"required":["gate","status","iterations"]},"RunState":{"type":"object","properties":{"_id":{"type":"string"},"attemptNumber":{"type":"integer","minimum":1},"status":{"type":"string","enum":["pending","queued","processing","paused","done"]},"queuedQueueName":{"type":"string"},"outcome":{"type":"string","enum":["succeeded","failed","finished"]},"result":{"type":"string"},"error":{"type":"string"},"logsUrl":{"type":"string"},"updatedAt":{"type":["string","null"],"format":"date-time"},"startedAt":{"type":["string","null"],"format":"date-time"},"finishedAt":{"type":["string","null"],"format":"date-time"},"durationMs":{"type":"number"},"turns":{"type":"array","items":{"$ref":"#/components/schemas/ConversationTurn"}},"workerVersion":{"type":"string"},"os":{"type":"object","properties":{"platform":{"type":"string"},"release":{"type":"string"},"arch":{"type":"string"}},"required":["platform","release","arch"]},"lastHeartbeatAt":{"type":["string","null"],"format":"date-time"},"worker":{"type":"object","properties":{"instanceId":{"type":"string"},"podName":{"type":"string"}},"required":["instanceId"]},"harUrl":{"type":"string"},"videoUrls":{"type":"array","items":{"type":"string"}},"setupVideoUrls":{"type":"array","items":{"type":"string"}},"tokenUsage":{"$ref":"#/components/schemas/TokenUsage"},"aiCallCount":{"type":"number"},"resources":{"type":"array","items":{"$ref":"#/components/schemas/ResourceRunOutcome"}},"mcpRegistered":{"type":"boolean"},"rawChatUrl":{"type":"string"},"rawChatFormat":{"type":"string"},"pausedAt":{"type":["string","null"],"format":"date-time"},"resumedAt":{"type":["string","null"],"format":"date-time"},"observationResults":{"type":"array","items":{"$ref":"#/components/schemas/CriterionResult"}}},"required":["_id","attemptNumber","status"]},"ConversationTurn":{"type":"object","properties":{"iteration":{"type":"number"},"gate":{"type":"string","enum":["select","build","test","run","deploy"]},"codingAgentResponse":{"type":"string"},"judgeFeedback":{"type":"string"},"snapshotUrl":{"type":"string"},"passed":{"type":"boolean"},"timestamp":{"type":["string","null"],"format":"date-time"},"criteriaResults":{"type":"array","items":{"$ref":"#/components/schemas/CriterionResult"}},"observationResults":{"type":"array","items":{"$ref":"#/components/schemas/CriterionResult"}},"harUrl":{"type":"string"},"videoUrls":{"type":"array","items":{"type":"string"}},"tokenUsage":{"$ref":"#/components/schemas/TokenUsage"},"startedAt":{"type":["string","null"],"format":"date-time"},"durationMs":{"type":"number"},"toolCalls":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"arguments":{"type":"object","additionalProperties":{}},"response":{"type":"string"},"timestamp":{"type":"string"}},"required":["id","name","arguments"]}},"toolCallsUrl":{"type":"string"},"toolCallCount":{"type":"number"},"aiCallCount":{"type":"number"},"rawChatUrl":{"type":"string"},"rawChatFormat":{"type":"string"},"chatResultUrl":{"type":"string"},"chatResultFormat":{"type":"string"}},"required":["iteration","judgeFeedback","snapshotUrl","passed","timestamp"]},"CriterionResult":{"type":"object","properties":{"criterionId":{"type":"string"},"passed":{"type":"boolean"},"feedback":{"type":"string"},"evaluated":{"type":"boolean"}},"required":["criterionId","passed","feedback","evaluated"]},"TokenUsage":{"type":"object","properties":{"promptTokens":{"type":"number"},"completionTokens":{"type":"number"},"totalTokens":{"type":"number"}},"required":["promptTokens","completionTokens","totalTokens"]},"ResourceRunOutcome":{"type":"object","properties":{"ref":{"type":"string"},"slug":{"type":"string"},"revisionId":{"type":"string"},"setupSucceeded":{"type":"boolean"},"published":{"type":"array","items":{"type":"string"}},"params":{"type":"object","additionalProperties":{"type":"string"}},"setupDurationMs":{"type":"number"},"error":{"type":"string"},"teardownRan":{"type":"boolean"}},"required":["ref","slug","revisionId","setupSucceeded","published"]},"ResourceBindingSpec":{"anyOf":[{"type":"string"},{"type":"object","properties":{"ref":{"type":"string"},"params":{"type":"object","additionalProperties":{"type":"string"}}},"required":["ref"]}]},"CreateRequestInput":{"type":"object","properties":{"scenario":{"$ref":"#/components/schemas/Scenario"},"model":{"type":"string"},"reasoningEffort":{"type":"string"},"maxIterations":{"type":"integer","minimum":1,"maximum":50},"personaInstructions":{"type":"string"},"persona":{"$ref":"#/components/schemas/Persona"},"mcpServers":{"type":"array","items":{"type":"string"}},"skillRevisions":{"type":"array","items":{"type":"string"}},"codebaseRevisionId":{"type":"string"},"resources":{"type":"array","items":{"$ref":"#/components/schemas/ResourceBindingSpec"}},"extensions":{"type":"array","items":{"type":"string"}},"profileId":{"type":"string"},"profileVariations":{"type":"array","items":{"type":"string"}},"priority":{"type":"integer"},"agentsMd":{"type":"string"},"agentsMdParentIds":{"type":"array","items":{"type":"string"}},"gates":{"type":"array","items":{"$ref":"#/components/schemas/GateConfig"}},"observations":{"type":"array","items":{"type":"string"}}},"required":["scenario"]},"RunFacetsResponse":{"type":"object","properties":{"total":{"type":"number"},"facets":{"type":"object","properties":{"workerType":{"type":"array","items":{"$ref":"#/components/schemas/RunFacetBucket"}},"status":{"type":"array","items":{"$ref":"#/components/schemas/RunFacetBucket"}},"outcome":{"type":"array","items":{"$ref":"#/components/schemas/RunFacetBucket"}},"model":{"type":"array","items":{"$ref":"#/components/schemas/RunFacetBucket"}},"os":{"type":"array","items":{"$ref":"#/components/schemas/RunFacetBucket"}},"priority":{"type":"array","items":{"$ref":"#/components/schemas/RunFacetBucket"}},"agentVersion":{"type":"array","items":{"$ref":"#/components/schemas/RunFacetBucket"}},"profileId":{"type":"array","items":{"$ref":"#/components/schemas/RunFacetBucket"}}},"required":["workerType","status","outcome","model","os","priority","agentVersion","profileId"]}},"required":["total","facets"]},"RunFacetBucket":{"type":"object","properties":{"value":{"type":"string"},"count":{"type":"number"}},"required":["value","count"]},"PaginatedRunsResponse":{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/RequestResponse"}},"limit":{"type":"number"},"estimatedTotal":{"type":"number"},"cursors":{"$ref":"#/components/schemas/Cursors"}},"required":["data","limit","estimatedTotal","cursors"]},"Cursors":{"type":"object","properties":{"next":{"type":["string","null"]},"prev":{"type":["string","null"]}},"required":["next","prev"]},"PaginatedRunGroupsResponse":{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/RunGroup"}},"limit":{"type":"number"},"estimatedTotal":{"type":"number"},"cursors":{"$ref":"#/components/schemas/Cursors"}},"required":["data","limit","estimatedTotal","cursors"]},"RunGroup":{"type":"object","properties":{"key":{"type":"string"},"label":{"type":"string"},"runIds":{"type":"array","items":{"type":"string"}},"aggregates":{"$ref":"#/components/schemas/GroupAggregates"},"uniform":{"$ref":"#/components/schemas/GroupUniformValues"}},"required":["key","label","runIds","aggregates","uniform"]},"GroupAggregates":{"type":"object","properties":{"count":{"type":"number"},"turns":{"$ref":"#/components/schemas/AggregateStats"},"duration":{"$ref":"#/components/schemas/AggregateStats"},"promptTokens":{"$ref":"#/components/schemas/AggregateStats"},"completionTokens":{"$ref":"#/components/schemas/AggregateStats"},"statusCounts":{"type":"object","additionalProperties":{"type":"number"}},"outcomeCounts":{"type":"object","additionalProperties":{"type":"number"}}},"required":["count","turns","duration","promptTokens","completionTokens","statusCounts","outcomeCounts"]},"AggregateStats":{"type":["object","null"],"properties":{"min":{"type":"number"},"max":{"type":"number"},"mean":{"type":"number"},"stdDev":{"type":"number"}},"required":["min","max","mean","stdDev"]},"GroupUniformValues":{"type":"object","properties":{"workerType":{"type":"string"},"agentVersion":{"type":"string"},"model":{"type":"string"},"platform":{"type":"string"},"mcpServers":{"type":"array","items":{"type":"string"}},"skillRevisions":{"type":"array","items":{"type":"string"}},"codebaseRevisionId":{"type":"string"},"extensions":{"type":"array","items":{"type":"string"}},"status":{"type":"string","enum":["pending","queued","processing","paused","done"]},"submissionId":{"type":"string"},"task":{"type":"string"}}},"BulkResubmitInput":{"type":"object","properties":{"ids":{"type":"array","items":{"type":"string"},"minItems":1},"count":{"type":"integer","minimum":1,"maximum":10,"default":1},"overrides":{"type":"object","properties":{"profileId":{"type":["string","null"]},"workerType":{"type":"string"},"agentVersion":{"type":"string"},"model":{"type":["string","null"]},"reasoningEffort":{"type":["string","null"]},"maxIterations":{"type":["number","null"]},"mcpServers":{"type":["array","null"],"items":{"type":"string"}},"skillRevisions":{"type":["array","null"],"items":{"type":"string"}},"extensions":{"type":["array","null"],"items":{"type":"string"}}}}},"required":["ids"]},"ReportResponse":{"type":"object","properties":{"_id":{"type":"string"},"requestId":{"type":"string"},"templateId":{"type":"string"},"reporter":{"$ref":"#/components/schemas/Reporter"},"content":{"type":"string"},"status":{"type":"string","enum":["pending","generating","completed","failed"]},"error":{"type":"string"},"insightReferences":{"type":"array","items":{"$ref":"#/components/schemas/InsightReference"}},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"projectId":{"type":"string"}},"required":["_id","requestId","status","createdAt","projectId"]},"Reporter":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"gitHash":{"type":"string"},"model":{"type":"string"},"agentId":{"type":"string"},"agentVersion":{"type":"string"}},"required":["id","name","gitHash","model","agentId","agentVersion"]},"InsightReference":{"type":"object","properties":{"insightId":{"type":"string"},"referencedAt":{"type":["string","null"],"format":"date-time"},"isNew":{"type":"boolean"}},"required":["insightId","referencedAt","isNew"]},"CreateCriteriaInput":{"type":"object","properties":{"id":{"type":"string","pattern":"^[a-z][a-z0-9_]*$"},"prompt":{"type":"string"},"dependsOn":{"type":"array","items":{"type":"string"}},"gates":{"type":"array","items":{"type":"string","enum":["select","build","test","run","deploy"]}},"kind":{"type":"string","enum":["gate","observation"],"default":"gate"},"taxonomyElementId":{"type":"string","enum":["dimension:idiomatic-use","dimension:dependency-currency","dimension:configuration-correctness"]},"subject":{"type":"string","enum":["run","iteration"]}},"required":["id","prompt"]},"CriteriaResponse":{"type":"object","properties":{"id":{"type":"string"},"prompt":{"type":"string"},"dependsOn":{"type":"array","items":{"type":"string"}},"gates":{"type":"array","items":{"type":"string","enum":["select","build","test","run","deploy"]}},"kind":{"type":"string","enum":["gate","observation"]},"taxonomyElementId":{"type":"string","enum":["dimension:idiomatic-use","dimension:dependency-currency","dimension:configuration-correctness"]},"subject":{"type":"string","enum":["run","iteration"]},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"deletedAt":{"type":["string","null"],"format":"date-time"},"projectId":{"type":"string"}},"required":["id","prompt","createdAt","projectId"]},"CriteriaGraph":{"type":"object","properties":{"nodes":{"type":"array","items":{"$ref":"#/components/schemas/CriteriaGraphNode"}},"edges":{"type":"array","items":{"$ref":"#/components/schemas/CriteriaGraphEdge"}}},"required":["nodes","edges"]},"CriteriaGraphNode":{"type":"object","properties":{"id":{"type":"string"},"prompt":{"type":"string"},"dependsOn":{"type":"array","items":{"type":"string"}},"gates":{"type":"array","items":{"type":"string","enum":["select","build","test","run","deploy"]}},"kind":{"type":"string","enum":["gate","observation"]},"taxonomyElementId":{"type":"string","enum":["dimension:idiomatic-use","dimension:dependency-currency","dimension:configuration-correctness"]},"subject":{"type":"string","enum":["run","iteration"]}},"required":["id","prompt"]},"CriteriaGraphEdge":{"type":"object","properties":{"from":{"type":"string"},"to":{"type":"string"}},"required":["from","to"]},"UpdateCriteriaInput":{"type":"object","properties":{"prompt":{"type":"string"},"dependsOn":{"type":"array","items":{"type":"string"}},"gates":{"type":"array","items":{"type":"string","enum":["select","build","test","run","deploy"]}},"kind":{"type":"string","enum":["gate","observation"]},"taxonomyElementId":{"type":"string","enum":["dimension:idiomatic-use","dimension:dependency-currency","dimension:configuration-correctness"]},"subject":{"type":"string","enum":["run","iteration"]}}},"CreatePromptFeatureInput":{"type":"object","properties":{"id":{"type":"string","pattern":"^[a-z][a-z0-9_]*$"},"prompt":{"type":"string"},"type":{"$ref":"#/components/schemas/PromptType"}},"required":["id","prompt"]},"PromptType":{"type":"string","enum":["select","build","test","run","deploy","agents.md"]},"PromptFeatureResult":{"type":"object","properties":{"featureId":{"type":"string"},"detected":{"type":"boolean"},"evaluated":{"type":"boolean"}},"required":["featureId","detected","evaluated"]},"SuggestedPromptFeature":{"type":"object","properties":{"suggestedId":{"type":"string"},"behavior":{"type":"string"},"prompt":{"type":"string"}},"required":["suggestedId","behavior","prompt"]},"PromptFeatureResponse":{"type":"object","properties":{"id":{"type":"string"},"prompt":{"type":"string"},"type":{"$ref":"#/components/schemas/PromptType"},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"deletedAt":{"type":["string","null"],"format":"date-time"},"projectId":{"type":"string"}},"required":["id","prompt","createdAt","projectId"]},"UpdatePromptFeatureInput":{"type":"object","properties":{"prompt":{"type":"string"}}},"TaskPromptResponse":{"type":"object","properties":{"_id":{"type":"string"},"keyId":{"type":"string"},"type":{"$ref":"#/components/schemas/PromptType"},"text":{"type":"string"},"contentBlobUrl":{"type":"string"},"features":{"type":"array","items":{"$ref":"#/components/schemas/PromptFeatureResult"}},"featuresExtractedAt":{"type":["string","null"],"format":"date-time"},"createdAt":{"type":["string","null"],"format":"date-time"},"deletedAt":{"type":["string","null"],"format":"date-time"},"projectId":{"type":"string"}},"required":["_id","keyId","createdAt","projectId"]},"CreateTaskPromptInput":{"type":"object","properties":{"text":{"type":"string"},"type":{"$ref":"#/components/schemas/PromptType"}},"required":["text"]},"PatchTaskPromptFeatureInput":{"type":"object","properties":{"detected":{"type":"boolean"}},"required":["detected"]},"CreateReportInput":{"type":"object","properties":{"requestId":{"type":"string"},"templateId":{"type":"string"}},"required":["requestId"]},"BulkCreateReportsInput":{"type":"object","properties":{"requestIds":{"type":"array","items":{"type":"string"}},"templateId":{"type":"string"}},"required":["requestIds"]},"BulkReportStatusInput":{"type":"object","properties":{"reportIds":{"type":"array","items":{"type":"string"}}},"required":["reportIds"]},"BulkReportSummaryResponse":{"type":"object","additionalProperties":{"$ref":"#/components/schemas/ReportSummary"}},"ReportSummary":{"type":"object","properties":{"total":{"type":"number"},"pending":{"type":"number"},"generating":{"type":"number"},"completed":{"type":"number"},"failed":{"type":"number"}},"required":["total","pending","generating","completed","failed"]},"BulkReportSummaryInput":{"type":"object","properties":{"requestIds":{"type":"array","items":{"type":"string"}}},"required":["requestIds"]},"TriggerReportsInput":{"type":"object","properties":{"requestId":{"type":"string"}},"required":["requestId"]},"BulkTriggerReportsInput":{"type":"object","properties":{"requestIds":{"type":"array","items":{"type":"string"}}},"required":["requestIds"]},"InsightResponse":{"type":"object","properties":{"_id":{"type":"string"},"title":{"type":"string"},"description":{"type":"string"},"category":{"type":"string"},"tags":{"type":"array","items":{"type":"string"}},"upvotes":{"type":"number"},"downvotes":{"type":"number"},"blocked":{"type":"boolean"},"referenceCount":{"type":"number"},"createdBy":{"type":"string","enum":["agent","user"]},"sourceReportId":{"type":"string"},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"deletedAt":{"type":["string","null"],"format":"date-time"},"projectId":{"type":"string"}},"required":["_id","title","description","upvotes","downvotes","blocked","referenceCount","createdBy","createdAt","projectId"]},"ProfileWithVersionResponse":{"type":"object","properties":{"_id":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"latestVersion":{"type":"number"},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"deletedAt":{"type":["string","null"],"format":"date-time"},"version":{"$ref":"#/components/schemas/ProfileVersionResponse"},"projectId":{"type":"string"}},"required":["_id","name","latestVersion","createdAt","version","projectId"]},"ProfileVersionResponse":{"type":"object","properties":{"_id":{"type":"string"},"profileId":{"type":"string"},"version":{"type":"number"},"workerType":{"type":"string"},"model":{"type":"string"},"reasoningEffort":{"type":"string"},"agentVersion":{"type":"string"},"mcpServers":{"type":"array","items":{"type":"string"}},"skillRevisions":{"type":"array","items":{"type":"string"}},"resources":{"type":"array","items":{"$ref":"#/components/schemas/ResourceBindingSpec"}},"extensions":{"type":"array","items":{"type":"string"}},"createdAt":{"type":["string","null"],"format":"date-time"},"projectId":{"type":"string"}},"required":["_id","profileId","version","workerType","model","createdAt","projectId"]},"CreateProfileInput":{"type":"object","properties":{"name":{"type":"string","minLength":1,"maxLength":128},"description":{"type":"string","maxLength":512},"workerType":{"type":"string"},"model":{"type":"string"},"reasoningEffort":{"type":"string"},"agentVersion":{"type":"string"},"mcpServers":{"type":"array","items":{"type":"string"}},"skillRevisions":{"type":"array","items":{"type":"string"}},"resources":{"type":"array","items":{"$ref":"#/components/schemas/ResourceBindingSpec"}},"extensions":{"type":"array","items":{"type":"string"}}},"required":["name","workerType","model"]},"ProfileResponse":{"type":"object","properties":{"_id":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"latestVersion":{"type":"number"},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"deletedAt":{"type":["string","null"],"format":"date-time"},"projectId":{"type":"string"}},"required":["_id","name","latestVersion","createdAt","projectId"]},"UpdateProfileIdentity":{"type":"object","properties":{"name":{"type":"string","minLength":1,"maxLength":128},"description":{"type":"string","maxLength":512}}},"ReportTemplateResponse":{"type":"object","properties":{"_id":{"type":"string"},"id":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"userPrompt":{"type":"string"},"systemPrompt":{"$ref":"#/components/schemas/ReportTemplateSystemPrompt"},"trigger":{"$ref":"#/components/schemas/ReportTrigger"},"model":{"type":"string"},"timeoutMs":{"type":"integer","exclusiveMinimum":0},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"deletedAt":{"type":["string","null"],"format":"date-time"},"projectId":{"type":"string"}},"required":["_id","id","name","userPrompt","createdAt","projectId"]},"ReportTemplateSystemPrompt":{"type":"object","properties":{"mode":{"type":"string","enum":["append","override"]},"content":{"type":"string"}},"required":["mode","content"]},"ReportTrigger":{"oneOf":[{"type":"object","properties":{"type":{"type":"string","enum":["always"]}},"required":["type"]},{"type":"object","properties":{"type":{"type":"string","enum":["criteria"]},"criteriaIds":{"type":"array","items":{"type":"string"}},"match":{"type":"string","enum":["any","all"]}},"required":["type","criteriaIds"]},{"type":"object","properties":{"type":{"type":"string","enum":["taskPrompt"]},"taskPromptIds":{"type":"array","items":{"type":"string"}}},"required":["type","taskPromptIds"]},{"type":"object","properties":{"type":{"type":"string","enum":["promptFeature"]},"featureIds":{"type":"array","items":{"type":"string"}},"match":{"type":"string","enum":["any","all"]}},"required":["type","featureIds"]}]},"CreateReportTemplateInput":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"userPrompt":{"type":"string"},"systemPrompt":{"$ref":"#/components/schemas/ReportTemplateSystemPrompt"},"trigger":{"$ref":"#/components/schemas/ReportTrigger"},"model":{"type":"string"},"timeoutMs":{"type":"integer","exclusiveMinimum":0}},"required":["id","name","userPrompt"]},"UpdateReportTemplateInput":{"type":"object","properties":{"name":{"type":"string"},"description":{"type":"string"},"userPrompt":{"type":"string"},"systemPrompt":{"allOf":[{"$ref":"#/components/schemas/ReportTemplateSystemPrompt"},{"type":["object","null"]}]},"trigger":{"$ref":"#/components/schemas/ReportTrigger"},"model":{"type":["string","null"]},"timeoutMs":{"type":["integer","null"],"exclusiveMinimum":0}}},"AgentResponse":{"type":"object","properties":{"_id":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"modelProvider":{"type":"string"},"supportedModels":{"type":"array","items":{"type":"string"}},"defaultModel":{"type":"string"},"available":{"type":"boolean"},"capabilities":{"$ref":"#/components/schemas/AgentCapabilities"},"versions":{"type":"array","items":{"$ref":"#/components/schemas/AgentVersion"}},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"deletedAt":{"type":["string","null"],"format":"date-time"}},"required":["_id","name","supportedModels","createdAt"]},"AgentCapabilities":{"type":"object","properties":{"supportsReasoningEffort":{"type":"boolean"},"supportsMcpServers":{"type":"boolean"},"supportsSkills":{"type":"boolean"},"supportsExtensions":{"type":"boolean"},"supportsResources":{"type":"boolean"}}},"AgentVersion":{"type":"object","properties":{"agentVersion":{"type":"string","minLength":1},"workerVersion":{"type":"string","minLength":1},"components":{"type":"object","additionalProperties":{"type":"string"}},"gitCommit":{"type":"string","minLength":1},"buildTime":{"type":"string","minLength":1},"imageTag":{"type":"string","minLength":1},"queueName":{"type":"string"},"status":{"type":"string","enum":["active","retired"]},"createdAt":{"type":["string","null"],"format":"date-time"}},"required":["agentVersion","workerVersion","components","gitCommit","buildTime","imageTag","status","createdAt"]},"CreateAgentInput":{"type":"object","properties":{"_id":{"type":"string","minLength":1},"name":{"type":"string","minLength":1},"description":{"type":"string"},"modelProvider":{"type":"string"},"supportedModels":{"type":"array","items":{"type":"string"}},"defaultModel":{"type":"string"},"available":{"type":"boolean"},"capabilities":{"$ref":"#/components/schemas/AgentCapabilities"}},"required":["_id","name"]},"UpdateAgentInput":{"type":"object","properties":{"name":{"type":"string"},"description":{"type":"string"},"modelProvider":{"type":"string"},"supportedModels":{"type":"array","items":{"type":"string"}},"defaultModel":{"type":"string"},"available":{"type":"boolean"},"capabilities":{"$ref":"#/components/schemas/AgentCapabilities"}}},"RegisterAgentVersionInput":{"type":"object","properties":{"agentVersion":{"type":"string","minLength":1},"workerVersion":{"type":"string","minLength":1},"components":{"type":"object","additionalProperties":{"type":"string"}},"gitCommit":{"type":"string","minLength":1},"buildTime":{"type":"string","minLength":1},"imageTag":{"type":"string","minLength":1},"queueName":{"type":"string","minLength":1}},"required":["agentVersion","workerVersion","components","gitCommit","buildTime","imageTag","queueName"]},"PatchAgentVersionInput":{"type":"object","properties":{"status":{"type":"string","enum":["active","retired"]}},"required":["status"]},"ModelResponse":{"type":"object","properties":{"_id":{"type":"string"},"modelId":{"type":"string"},"provider":{"type":"string"},"agentId":{"type":"string"},"firstSeenAt":{"type":["string","null"],"format":"date-time"},"lastSeenAt":{"type":["string","null"],"format":"date-time"},"disappearedAt":{"type":["string","null"],"format":"date-time"},"providerAvailableFrom":{"type":["string","null"],"format":"date-time"},"providerEndOfLife":{"type":["string","null"],"format":"date-time"},"metadata":{"type":"object","additionalProperties":{}},"capabilities":{"$ref":"#/components/schemas/ModelCapabilities"}},"required":["_id","modelId","provider","agentId","firstSeenAt","lastSeenAt"]},"ModelCapabilities":{"type":"object","properties":{"reasoningEffort":{"type":"array","items":{"type":"string"}},"toolCalls":{"type":"boolean"},"vision":{"type":"boolean"},"streaming":{"type":"boolean"},"adaptiveThinking":{"type":"boolean"},"maxThinkingBudget":{"type":"number"}}},"McpServerResponse":{"type":"object","properties":{"_id":{"type":"string"},"slug":{"type":"string"},"name":{"type":"string"},"type":{"type":"string","enum":["sse","http","stdio"]},"url":{"type":"string"},"command":{"type":"string"},"args":{"type":"array","items":{"type":"string"}},"env":{"type":"object","additionalProperties":{"type":"string"}},"headers":{"type":"array","items":{"$ref":"#/components/schemas/McpServerHeader"}},"sessionMode":{"type":"string","enum":["stateful","stateless"]},"version":{"type":"string"},"description":{"type":"string"},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"deletedAt":{"type":["string","null"],"format":"date-time"},"projectId":{"type":"string"}},"required":["_id","slug","name","type","createdAt","projectId"]},"McpServerHeader":{"type":"object","properties":{"name":{"type":"string"},"value":{"type":"string"}},"required":["name","value"]},"UpdateMcpServerInput":{"type":"object","properties":{"name":{"type":"string"},"type":{"type":"string","enum":["sse","http","stdio"]},"url":{"type":"string"},"command":{"type":"string"},"args":{"type":"array","items":{"type":"string"}},"env":{"type":"object","additionalProperties":{"type":"string"}},"headers":{"type":"array","items":{"$ref":"#/components/schemas/McpServerHeader"}},"sessionMode":{"type":"string","enum":["stateful","stateless"]},"version":{"type":"string"},"description":{"type":"string"}}},"SkillResponse":{"type":"object","properties":{"_id":{"type":"string"},"slug":{"type":"string"},"source":{"type":"string"},"skillName":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"origin":{"type":"string","enum":["skills-sh","manual"]},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"deletedAt":{"type":["string","null"],"format":"date-time"},"projectId":{"type":"string"}},"required":["_id","slug","source","skillName","name","origin","createdAt","projectId"]},"SkillSearchResult":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"source":{"type":"string"},"description":{"type":"string"},"internal":{"type":"boolean"},"installs":{"type":"number"}},"required":["id","name","source","internal"]},"SkillDiscoveryResult":{"type":"object","properties":{"skillName":{"type":"string"},"skillPath":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"existsInLibrary":{"type":"boolean"},"currentRevisionCommitSha":{"type":"string"},"latestUpstreamCommitSha":{"type":"string"},"updateAvailable":{"type":"boolean"},"lastImportedAt":{"type":"string"}},"required":["skillName","skillPath"]},"SkillRevisionResponse":{"type":"object","properties":{"_id":{"type":"string"},"ref":{"type":"string"},"source":{"type":"string"},"skillName":{"type":"string"},"skillPath":{"type":"string"},"commitHash":{"type":"string"},"commitTimestamp":{"type":["string","null"],"format":"date-time"},"name":{"type":"string"},"description":{"type":"string"},"license":{"type":"string"},"compatibility":{"type":"string"},"allowedTools":{"type":"string"},"metadata":{"type":"object","additionalProperties":{"type":"string"}},"content":{"type":"string"},"archiveUrl":{"type":"string"},"validationWarnings":{"type":"array","items":{"type":"string"}},"resolvedAt":{"type":["string","null"],"format":"date-time"},"createdAt":{"type":["string","null"],"format":"date-time"},"projectId":{"type":"string"}},"required":["_id","ref","source","skillName","skillPath","commitHash","commitTimestamp","name","description","content","archiveUrl","resolvedAt","createdAt","projectId"]},"CreateSkillInput":{"type":"object","properties":{"source":{"type":"string"},"skillName":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"origin":{"type":"string","enum":["skills-sh","manual"]}},"required":["source","skillName","name","origin"]},"CodebaseResponse":{"type":"object","properties":{"_id":{"type":"string"},"slug":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"sourceType":{"type":"string","enum":["git","archive"]},"source":{"type":"string"},"defaultBranch":{"type":"string"},"revisionCounter":{"type":"number"},"latestRevisionId":{"type":"string"},"creator":{"type":"string"},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"deletedAt":{"type":["string","null"],"format":"date-time"},"projectId":{"type":"string"}},"required":["_id","slug","name","sourceType","revisionCounter","createdAt","projectId"]},"UpdateCodebaseInput":{"type":"object","properties":{"name":{"type":"string","minLength":1},"description":{"type":"string"},"defaultBranch":{"type":"string"}}},"CodebaseRevisionResponse":{"type":"object","properties":{"_id":{"type":"string"},"codebaseId":{"type":"string"},"slug":{"type":"string"},"revisionNumber":{"type":"number"},"ref":{"type":"string"},"sourceType":{"type":"string","enum":["git","archive"]},"source":{"type":"string"},"requestedRef":{"type":"string"},"resolvedCommitSha":{"type":"string"},"commitTimestamp":{"type":["string","null"],"format":"date-time"},"originalFilename":{"type":"string"},"contentSha256":{"type":"string"},"archiveUrl":{"type":"string"},"sizeBytes":{"type":"number"},"fileCount":{"type":"number"},"creator":{"type":"string"},"resolvedAt":{"type":["string","null"],"format":"date-time"},"createdAt":{"type":["string","null"],"format":"date-time"},"deduplicated":{"type":"boolean"},"projectId":{"type":"string"}},"required":["_id","codebaseId","slug","revisionNumber","ref","sourceType","archiveUrl","resolvedAt","createdAt","projectId"]},"ResolveCodebaseRevisionInput":{"type":"object","properties":{"requestedRef":{"type":"string"},"creator":{"type":"string"}}},"ResourceResponse":{"type":"object","properties":{"_id":{"type":"string"},"slug":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"revisionCounter":{"type":"number"},"latestRevisionId":{"type":"string"},"latestRevisionNumber":{"type":"number"},"creator":{"type":"string"},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"deletedAt":{"type":["string","null"],"format":"date-time"},"projectId":{"type":"string"}},"required":["_id","slug","name","revisionCounter","createdAt","projectId"]},"CreateResourceInput":{"type":"object","properties":{"name":{"type":"string","minLength":1},"slug":{"type":"string","minLength":1},"description":{"type":"string"},"setup":{"$ref":"#/components/schemas/ResourceScript"},"teardown":{"$ref":"#/components/schemas/ResourceScript"},"exports":{"type":"array","items":{"type":"string","pattern":"^[A-Za-z_][A-Za-z0-9_]*$"}},"parameters":{"type":"array","items":{"$ref":"#/components/schemas/ResourceParameter"}},"creator":{"type":"string"}},"required":["name","setup"]},"ResourceScript":{"type":"object","properties":{"sh":{"type":"string","minLength":1}}},"ResourceParameter":{"type":"object","properties":{"name":{"type":"string","pattern":"^[A-Za-z_][A-Za-z0-9_]*$"},"description":{"type":"string"},"required":{"type":"boolean","default":false},"default":{"type":"string"},"example":{"type":"string"}},"required":["name"]},"UpdateResourceInput":{"type":"object","properties":{"name":{"type":"string","minLength":1},"description":{"type":"string"}}},"ResourceRevisionResponse":{"type":"object","properties":{"_id":{"type":"string"},"resourceId":{"type":"string"},"slug":{"type":"string"},"revisionNumber":{"type":"number"},"ref":{"type":"string"},"setup":{"$ref":"#/components/schemas/ResourceScript"},"teardown":{"$ref":"#/components/schemas/ResourceScript"},"exports":{"type":"array","items":{"type":"string"}},"parameters":{"type":"array","items":{"$ref":"#/components/schemas/ResourceParameter"}},"contentSha256":{"type":"string"},"creator":{"type":"string"},"createdAt":{"type":["string","null"],"format":"date-time"},"deduplicated":{"type":"boolean"},"projectId":{"type":"string"}},"required":["_id","resourceId","slug","revisionNumber","ref","setup","exports","contentSha256","createdAt","projectId"]},"CreateResourceRevisionInput":{"type":"object","properties":{"setup":{"$ref":"#/components/schemas/ResourceScript"},"teardown":{"$ref":"#/components/schemas/ResourceScript"},"exports":{"type":"array","items":{"type":"string","pattern":"^[A-Za-z_][A-Za-z0-9_]*$"}},"parameters":{"type":"array","items":{"$ref":"#/components/schemas/ResourceParameter"}},"creator":{"type":"string"}},"required":["setup"]},"ExtensionResponse":{"type":"object","properties":{"_id":{"type":"string"},"slug":{"type":"string"},"publisher":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"origin":{"type":"string","enum":["marketplace","manual"]},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"deletedAt":{"type":["string","null"],"format":"date-time"},"projectId":{"type":"string"}},"required":["_id","slug","publisher","name","origin","createdAt","projectId"]},"ExtensionSearchResult":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"publisher":{"type":"string"},"description":{"type":"string"},"internal":{"type":"boolean"},"version":{"type":"string"}},"required":["id","name","publisher","internal"]},"CreateExtensionInput":{"type":"object","properties":{"_id":{"type":"string","pattern":"^[a-zA-Z0-9-]+\\.[a-zA-Z0-9-]+$"},"publisher":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"origin":{"type":"string","enum":["marketplace","manual"]}},"required":["_id","publisher","name","origin"]},"UpdateExtensionInput":{"type":"object","properties":{"name":{"type":"string"},"description":{"type":"string"}}},"ExtensionVersionInfo":{"type":"object","properties":{"version":{"type":"string"},"preRelease":{"type":"boolean"},"lastUpdated":{"type":"string"}},"required":["version","preRelease","lastUpdated"]},"CreateInsightInput":{"type":"object","properties":{"title":{"type":"string"},"description":{"type":"string"},"category":{"type":"string"},"tags":{"type":"array","items":{"type":"string"}},"createdBy":{"type":"string","enum":["agent","user"]},"sourceReportId":{"type":"string"}},"required":["title","description"]},"UpdateInsightInput":{"type":"object","properties":{"title":{"type":"string"},"description":{"type":"string"},"category":{"type":"string"},"tags":{"type":"array","items":{"type":"string"}}}},"FeatureFlagResponse":{"type":"object","properties":{"key":{"type":"string"},"label":{"type":"string"},"enabled":{"type":"boolean"},"updatedAt":{"type":["string","null"],"format":"date-time"}},"required":["key","label","enabled","updatedAt"]},"UpdateFeatureFlagInput":{"type":"object","properties":{"enabled":{"type":"boolean"}},"required":["enabled"]}},"parameters":{}},"paths":{"/api/v1/keys/preview":{"post":{"tags":["Keys"],"summary":"Preview key","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/KeyInput"}}}},"responses":{"200":{"description":"Key preview","content":{"application/json":{"schema":{"$ref":"#/components/schemas/KeyResponse"}}}}}}},"/api/v1/keys":{"post":{"tags":["Keys"],"summary":"Create key","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/KeyInput"}}}},"responses":{"201":{"description":"Key created","content":{"application/json":{"schema":{"$ref":"#/components/schemas/KeyResponse"}}}}}},"get":{"tags":["Keys"],"summary":"List keys","responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/KeyResponse"}}}}}}}},"/api/v1/keys/{id}":{"get":{"tags":["Keys"],"summary":"Get key","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/KeyResponse"}}}}}},"put":{"tags":["Keys"],"summary":"Update key","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/KeyInput"}}}},"responses":{"200":{"description":"Key updated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/KeyResponse"}}}}}},"delete":{"tags":["Keys"],"summary":"Delete key","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Key deleted","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"}},"required":["success"]}}}}}}},"/api/v1/keys/{id}/validate":{"post":{"tags":["Keys"],"summary":"Validate key","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidateKeyInput"}}}},"responses":{"200":{"description":"Validation result","content":{"application/json":{"schema":{"type":"object","properties":{},"additionalProperties":{},"description":"Key validation result"}}}}}}},"/api/v1/accounts":{"post":{"tags":["Accounts"],"summary":"Create account","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AccountInput"}}}},"responses":{"201":{"description":"Account created","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AccountResponse"}}}}}},"get":{"tags":["Accounts"],"summary":"List accounts","responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/AccountResponse"}}}}}}}},"/api/v1/accounts/{id}":{"get":{"tags":["Accounts"],"summary":"Get account","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AccountResponse"}}}}}},"put":{"tags":["Accounts"],"summary":"Update account","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AccountInput"}}}},"responses":{"200":{"description":"Account updated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AccountResponse"}}}}}},"delete":{"tags":["Accounts"],"summary":"Delete account","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Account deleted","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"}},"required":["success"]}}}}}}},"/api/v1/users/me":{"get":{"tags":["Users"],"summary":"Get the authenticated user's identity","description":"Read the existing authenticated Scope identity without enrollment or profile writes. Responses must not be HTTP-cached.","security":[{"bearerAuth":[]}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserMeResponse"}}}},"401":{"description":"Not authenticated"},"403":{"description":"User is not enrolled or is disabled"},"503":{"description":"Authentication service unavailable"}}},"post":{"tags":["Users"],"summary":"Enroll the authenticated user","description":"JIT-enroll the authenticated user, refresh their profile and lastLoginAt, apply bootstrap-admin rules, and warm the access cache. Use this only after an explicit IdP login; do not prefetch, poll, or automatically retry transient failures.","security":[{"bearerAuth":[]}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserMeResponse"}}}},"401":{"description":"Not authenticated"},"403":{"description":"User is disabled"},"503":{"description":"Authentication service unavailable"}}}},"/health":{"get":{"tags":["Health"],"summary":"Liveness probe","responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"status":{"type":"string"},"version":{"type":"string"}},"required":["status","version"]}}}}}}},"/ready":{"get":{"tags":["Health"],"summary":"Readiness probe","responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"status":{"type":"string"},"migrations":{}},"required":["status"]}}}},"503":{"description":"Service is not ready"}}}},"/about":{"get":{"tags":["System"],"summary":"API metadata","responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string"},"version":{"type":"string"},"buildTime":{"type":"string"},"environment":{"type":"string"},"description":{"type":"string"},"workers":{"type":"array","items":{"type":"string"}}},"required":["name","version","buildTime","environment","description","workers"]}}}}}}},"/api/v1/version":{"get":{"tags":["System"],"summary":"Version info","responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"commit":{"type":"string"},"buildTime":{"type":"string"},"environment":{"type":"string"},"strictAgentCapabilities":{"type":"boolean"}},"required":["commit","buildTime","environment","strictAgentCapabilities"]}}}}}}},"/api/v1/projects":{"get":{"tags":["Projects"],"summary":"List all projects","parameters":[{"schema":{"type":"string","enum":["true","false"],"description":"When true, include soft-deleted projects in the result"},"required":false,"description":"When true, include soft-deleted projects in the result","name":"includeDeleted","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ProjectResponse"}}}}}}},"post":{"tags":["Projects"],"summary":"Create a project","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateProjectInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProjectResponse"}}}},"400":{"description":"Invalid input"}}}},"/api/v1/projects/{id}":{"get":{"tags":["Projects"],"summary":"Get a project","responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProjectResponse"}}}},"404":{"description":"Project not found"}}},"patch":{"tags":["Projects"],"summary":"Update a project","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateProjectInput"}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProjectResponse"}}}},"404":{"description":"Project not found"}}},"delete":{"tags":["Projects"],"summary":"Soft-delete a project","responses":{"204":{"description":"Success"},"404":{"description":"Project not found"}}}},"/api/v1/projects/{id}/restore":{"post":{"tags":["Projects"],"summary":"Restore a soft-deleted project","responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProjectResponse"}}}},"404":{"description":"Project not found"}}}},"/api/v1/requests":{"post":{"tags":["Requests"],"summary":"Submit request(s)","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/CreateRequestInput"},{"type":"object","properties":{"count":{"type":"number","minimum":1,"maximum":10,"default":1},"skills":{"type":"array","items":{"type":"string"}},"agentVersion":{"type":"string"},"codebase":{"type":"string"}}}]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"anyOf":[{"$ref":"#/components/schemas/RequestResponse"},{"type":"array","items":{"$ref":"#/components/schemas/RequestResponse"}}]}}}}}},"get":{"tags":["Requests"],"summary":"List requests","parameters":[{"schema":{"anyOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]},"required":false,"name":"worker","in":"query"},{"schema":{"type":"string"},"required":false,"name":"taskPromptId","in":"query"},{"schema":{"type":"string"},"required":false,"name":"criteria","in":"query"},{"schema":{"type":"string"},"required":false,"name":"submissionId","in":"query"},{"schema":{"anyOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]},"required":false,"name":"profileId","in":"query"},{"schema":{"anyOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]},"required":false,"name":"status","in":"query"},{"schema":{"anyOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]},"required":false,"name":"outcome","in":"query"},{"schema":{"anyOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]},"required":false,"name":"model","in":"query"},{"schema":{"anyOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]},"required":false,"name":"os","in":"query"},{"schema":{"anyOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]},"required":false,"name":"priority","in":"query"},{"schema":{"anyOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]},"required":false,"name":"agentVersion","in":"query"},{"schema":{"type":"string"},"required":false,"name":"search","in":"query"},{"schema":{"type":"string","enum":["task","submissionId","profile"]},"required":false,"name":"groupBy","in":"query"},{"schema":{"type":"integer","minimum":1,"maximum":100},"required":false,"name":"limit","in":"query"},{"schema":{"type":"string"},"required":false,"name":"after","in":"query"},{"schema":{"type":"string"},"required":false,"name":"before","in":"query"},{"schema":{"type":"string","enum":["true","false"]},"required":false,"name":"last","in":"query"},{"schema":{"type":"string","enum":["created","updated","priority","worker","status","id","duration","createdAt"]},"required":false,"name":"sortBy","in":"query"},{"schema":{"type":"string","enum":["asc","desc"]},"required":false,"name":"sortDir","in":"query"},{"schema":{"type":["string","null"],"format":"date-time"},"required":false,"name":"createdAfter","in":"query"},{"schema":{"type":["string","null"],"format":"date-time"},"required":false,"name":"createdBefore","in":"query"},{"schema":{"type":["integer","null"],"minimum":0},"required":false,"name":"turns","in":"query"},{"schema":{"type":"string","enum":["eq","gte","lte"]},"required":false,"name":"turnsOp","in":"query"},{"schema":{"type":["integer","null"],"minimum":0},"required":false,"name":"maxIterations","in":"query"},{"schema":{"type":"string","enum":["eq","gte","lte"]},"required":false,"name":"maxIterationsOp","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"anyOf":[{"$ref":"#/components/schemas/PaginatedRunsResponse"},{"$ref":"#/components/schemas/PaginatedRunGroupsResponse"}]}}}}}}},"/api/v1/requests/facets":{"get":{"tags":["Requests"],"summary":"List run filter facets","description":"Returns every distinct value and its full-dataset count per categorical filter dimension for the Runs list rail. Counts are absolute over all non-deleted runs **in the given project**: they intentionally ignore the active search, date range, iteration, and categorical selections so every selectable value stays visible with a stable count. Requires ?projectId=. Computed with parallel $group aggregations (Cosmos has no $facet) and cached per-project for a short TTL.","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RunFacetsResponse"}}}}}}},"/api/v1/requests/{id}":{"get":{"tags":["Requests"],"summary":"Get request","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestResponse"}}}},"404":{"description":"Not found"}}},"delete":{"tags":["Requests"],"summary":"Soft-delete request","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string"}},"required":["message"]}}}},"404":{"description":"Not found"}}}},"/api/v1/analysis":{"get":{"tags":["Requests"],"summary":"Compute pass@k / success@T metrics","description":"Aggregates pass@k / success@T metrics over a single project's done runs. Requires ?projectId=.","parameters":[{"schema":{"type":"string"},"required":false,"name":"worker","in":"query"},{"schema":{"type":"string"},"required":false,"name":"taskPromptId","in":"query"},{"schema":{"type":"string"},"required":false,"name":"criteria","in":"query"},{"schema":{"type":"string"},"required":false,"name":"features","in":"query"},{"schema":{"type":"string"},"required":false,"name":"submissionId","in":"query"},{"schema":{"type":"string"},"required":false,"name":"k","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{},"additionalProperties":{},"description":"Analysis metrics"}}}}}}},"/api/v1/requests/bulk-resubmit":{"post":{"tags":["Requests"],"summary":"Bulk resubmit requests","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BulkResubmitInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/RequestResponse"}}}}}}}},"/api/v1/requests/bulk":{"delete":{"tags":["Requests"],"summary":"Bulk soft-delete requests","requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"ids":{"type":"array","items":{"type":"string"}}},"required":["ids"]}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"deleted":{"type":"number"}},"required":["deleted"]}}}}}}},"/api/v1/requests/archive":{"post":{"tags":["Requests"],"summary":"Download batch archive of multiple runs","requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"ids":{"type":"array","items":{"type":"string"},"minItems":1,"maxItems":100}},"required":["ids"]}}}},"responses":{"201":{"description":"Gzipped batch archive containing individual run archives"},"400":{"description":"Invalid input"},"404":{"description":"One or more runs not found"}}}},"/api/v1/runs/upload":{"post":{"tags":["Requests"],"summary":"Import run archive","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"201":{"description":"Success"}}}},"/api/v1/runs/upload-batch":{"post":{"tags":["Requests"],"summary":"Import batch run archive","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"207":{"description":"Multi-status: 201 if all runs imported, 400 if none imported, 207 if partial"},"400":{"description":"No archive uploaded, empty archive, or all runs failed"}}}},"/api/v1/requests/{id}/reports":{"get":{"tags":["Reports"],"summary":"Get reports for request","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ReportResponse"}}}}},"404":{"description":"Run not found"}}}},"/api/v1/requests/{id}/runs":{"get":{"tags":["Requests"],"summary":"List attempts for a request","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/RunState"}}}}},"404":{"description":"Request not found"}}}},"/api/v1/requests/{id}/runs/{runId}":{"get":{"tags":["Requests"],"summary":"Get a single attempt","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":true,"name":"runId","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RunState"}}}},"404":{"description":"Request or run not found"}}}},"/api/v1/requests/bulk-retry":{"post":{"tags":["Requests"],"summary":"Bulk retry requests (start new attempts)","requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"ids":{"type":"array","items":{"type":"string"},"minItems":1},"force":{"type":"boolean"}},"required":["ids"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"retried":{"type":"integer"},"skipped":{"type":"integer"},"results":{"type":"array","items":{"type":"object","properties":{"requestId":{"type":"string"},"runId":{"type":"string"},"attemptNumber":{"type":"integer"},"error":{"type":"string"}},"required":["requestId"]}}},"required":["retried","skipped","results"]}}}}}}},"/api/v1/requests/{id}/retry":{"post":{"tags":["Requests"],"summary":"Retry a request (start a new attempt)","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"force":{"type":"boolean"}}}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"requestId":{"type":"string"},"runId":{"type":"string"},"attemptNumber":{"type":"integer"}},"required":["requestId","runId","attemptNumber"]}}}},"404":{"description":"Request not found"},"409":{"description":"Conflict — request is not in a retryable state, or a concurrent retry won the race"},"422":{"description":"Cannot retry — current run not yet terminal"}}}},"/api/v1/requests/{id}/priority":{"post":{"tags":["Requests"],"summary":"Set priority on a single request","requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"priority":{"type":"integer"}},"required":["priority"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"priority":{"type":"number"}},"required":["id","priority"]}}}}}}},"/api/v1/requests/bulk-priority":{"post":{"tags":["Requests"],"summary":"Set priority on multiple requests","requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"ids":{"type":"array","items":{"type":"string"},"minItems":1,"maxItems":100},"priority":{"type":"integer"}},"required":["ids","priority"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"updated":{"type":"number"},"skipped":{"type":"number"}},"required":["updated","skipped"]}}}}}}},"/api/v1/requests/{id}/pause":{"post":{"tags":["Requests"],"summary":"Pause a single request","responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"status":{"type":"string"}},"required":["id","status"]}}}}}}},"/api/v1/requests/{id}/resume":{"post":{"tags":["Requests"],"summary":"Resume a paused request","responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"status":{"type":"string"}},"required":["id","status"]}}}}}}},"/api/v1/requests/bulk-pause":{"post":{"tags":["Requests"],"summary":"Pause multiple requests","requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"ids":{"type":"array","items":{"type":"string"},"minItems":1,"maxItems":100}},"required":["ids"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"updated":{"type":"number"},"skipped":{"type":"number"}},"required":["updated","skipped"]}}}}}}},"/api/v1/requests/bulk-resume":{"post":{"tags":["Requests"],"summary":"Resume multiple paused requests","requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"ids":{"type":"array","items":{"type":"string"},"minItems":1,"maxItems":100}},"required":["ids"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"updated":{"type":"number"},"skipped":{"type":"number"}},"required":["updated","skipped"]}}}}}}},"/api/v1/requests/{id}/cancel":{"post":{"tags":["Requests"],"summary":"Cancel a request (marks as done/failed and signals worker to exit)","responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"previousStatus":{"type":"string"},"status":{"type":"string"},"outcome":{"type":"string"}},"required":["id","previousStatus","status","outcome"]}}}}}}},"/api/v1/requests/bulk-cancel":{"post":{"tags":["Requests"],"summary":"Cancel multiple requests","requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"ids":{"type":"array","items":{"type":"string"},"minItems":1,"maxItems":100}},"required":["ids"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"cancelled":{"type":"number"},"skipped":{"type":"number"},"results":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"cancelled":{"type":"boolean"},"previousStatus":{"type":"string"},"error":{"type":"string"}},"required":["id","cancelled"]}}},"required":["cancelled","skipped","results"]}}}}}}},"/api/v1/requests/{id}/logs":{"get":{"tags":["Requests"],"summary":"Stream request logs (SSE)","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Server-sent event stream of log entries"},"404":{"description":"Not found"}}}},"/api/v1/requests/{id}/runs/{runId}/logs":{"get":{"tags":["Requests"],"summary":"Stream logs for a specific attempt (SSE)","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":true,"name":"runId","in":"path"}],"responses":{"200":{"description":"Server-sent event stream of log entries"},"404":{"description":"Not found"}}}},"/api/v1/requests/{id}/har":{"get":{"tags":["Requests"],"summary":"Download HAR file","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"HAR-format JSON file"},"404":{"description":"Not found"}}}},"/api/v1/requests/{id}/runs/{runId}/har":{"get":{"tags":["Requests"],"summary":"Download HAR file for a specific attempt","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":true,"name":"runId","in":"path"}],"responses":{"200":{"description":"HAR-format JSON file"},"404":{"description":"Not found"}}}},"/api/v1/requests/{id}/atif":{"get":{"tags":["Requests"],"summary":"Download ATIF trajectory file for a specific iteration","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","description":"The iteration number (1-based)"},"required":true,"description":"The iteration number (1-based)","name":"iteration","in":"query"}],"responses":{"200":{"description":"ATIF v1.7 trajectory JSON file"},"400":{"description":"Missing or invalid iteration"},"404":{"description":"Not found"}}}},"/api/v1/requests/{id}/runs/{runId}/atif":{"get":{"tags":["Requests"],"summary":"Download ATIF trajectory file for a specific attempt and iteration","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":true,"name":"runId","in":"path"},{"schema":{"type":"string","description":"The iteration number (1-based)"},"required":true,"description":"The iteration number (1-based)","name":"iteration","in":"query"}],"responses":{"200":{"description":"ATIF v1.7 trajectory JSON file"},"400":{"description":"Missing or invalid iteration"},"404":{"description":"Not found"}}}},"/api/v1/requests/{id}/video":{"get":{"tags":["Requests"],"summary":"Download session recording","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"WebM video recording (supports Range requests)"},"404":{"description":"Not found"}}}},"/api/v1/requests/{id}/runs/{runId}/video":{"get":{"tags":["Requests"],"summary":"Download session recording for a specific attempt","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":true,"name":"runId","in":"path"}],"responses":{"200":{"description":"WebM video recording (supports Range requests)"},"404":{"description":"Not found"}}}},"/api/v1/requests/{id}/tool-calls":{"get":{"tags":["Requests"],"summary":"Download per-iteration tool-calls JSONL","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"JSONL stream — one ToolCall per line"},"404":{"description":"Not found"}}}},"/api/v1/requests/{id}/runs/{runId}/tool-calls":{"get":{"tags":["Requests"],"summary":"Download per-iteration tool-calls JSONL for a specific attempt","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":true,"name":"runId","in":"path"}],"responses":{"200":{"description":"JSONL stream — one ToolCall per line"},"404":{"description":"Not found"}}}},"/api/v1/requests/{id}/snapshots/{iteration}":{"get":{"tags":["Requests"],"summary":"Download iteration snapshot","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":true,"name":"iteration","in":"path"}],"responses":{"200":{"description":"Gzipped snapshot archive"},"404":{"description":"Not found"}}}},"/api/v1/requests/{id}/runs/{runId}/snapshots/{iteration}":{"get":{"tags":["Requests"],"summary":"Download iteration snapshot for a specific attempt","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":true,"name":"runId","in":"path"},{"schema":{"type":"string"},"required":true,"name":"iteration","in":"path"}],"responses":{"200":{"description":"Gzipped snapshot archive"},"404":{"description":"Not found"}}}},"/api/v1/requests/{id}/archive":{"get":{"tags":["Requests"],"summary":"Download full run archive","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Gzipped run archive"},"404":{"description":"Not found"}}}},"/api/v1/requests/{id}/runs/{runId}/archive":{"get":{"tags":["Requests"],"summary":"Download full run archive for a specific attempt","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":true,"name":"runId","in":"path"}],"responses":{"200":{"description":"Gzipped run archive"},"404":{"description":"Not found"}}}},"/api/v1/criteria/generate-prompt":{"post":{"tags":["Criteria"],"summary":"Generate criterion prompt from behavior","parameters":[{"schema":{"type":"string","minLength":1,"description":"Optional project scope. When provided, a slug/id is resolved within that project (slugs may repeat across projects); when omitted, resolution falls back to a legacy global lookup for backward compatibility.","example":"00000000-0000-0000-0000-000000000000"},"required":false,"description":"Optional project scope. When provided, a slug/id is resolved within that project (slugs may repeat across projects); when omitted, resolution falls back to a legacy global lookup for backward compatibility.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"behavior":{"type":"string"},"currentId":{"type":"string"},"gates":{"type":"array","items":{"type":"string"}}},"required":["behavior"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"prompt":{"type":"string"},"suggestedId":{"type":"string"},"suggestedParents":{"type":"array","items":{"type":"string"}},"suggestedChildren":{"type":"array","items":{"type":"string"}}},"required":["prompt","suggestedId","suggestedParents","suggestedChildren"]}}}},"400":{"description":"Empty behavior string"},"503":{"description":"LLM not configured"}}}},"/api/v1/criteria/seed":{"post":{"tags":["Criteria"],"summary":"Seed criteria in bulk","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"criteria":{"type":"array","items":{"$ref":"#/components/schemas/CreateCriteriaInput"}}},"required":["criteria"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"seeded":{"type":"number"},"errors":{"type":"array","items":{"type":"string"}}},"required":["seeded","errors"]}}}},"400":{"description":"Seed batch would introduce a dependency cycle"}}}},"/api/v1/criteria":{"get":{"tags":["Criteria"],"summary":"List criteria","parameters":[{"schema":{"type":"string"},"required":false,"name":"q","in":"query"},{"schema":{"type":"string","description":"Comma-separated criterion IDs to include"},"required":false,"description":"Comma-separated criterion IDs to include","name":"ids","in":"query"},{"schema":{"type":"string","enum":["true","false"],"description":"When true and ids is set, also include dependency ancestors"},"required":false,"description":"When true and ids is set, also include dependency ancestors","name":"ancestors","in":"query"},{"schema":{"type":"string","enum":["gate","observation"],"description":"Filter by criterion kind"},"required":false,"description":"Filter by criterion kind","name":"kind","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/CriteriaResponse"}}}}}}},"post":{"tags":["Criteria"],"summary":"Create criterion","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateCriteriaInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CriteriaResponse"}}}},"409":{"description":"Criterion already exists"}}}},"/api/v1/criteria/mdp":{"get":{"tags":["Criteria"],"summary":"Compute MDP transitions","parameters":[{"schema":{"type":"string"},"required":false,"name":"criteria","in":"query"},{"schema":{"type":"string"},"required":false,"name":"features","in":"query"},{"schema":{"type":"string"},"required":false,"name":"since","in":"query"},{"schema":{"type":"string"},"required":false,"name":"worker","in":"query"},{"schema":{"type":"string"},"required":false,"name":"taskPromptId","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{},"additionalProperties":{}}}}}}}},"/api/v1/criteria/graph":{"get":{"tags":["Criteria"],"summary":"Get criteria DAG","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CriteriaGraph"}}}}}}},"/api/v1/criteria/{id}":{"get":{"tags":["Criteria"],"summary":"Get criterion","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CriteriaResponse"}}}},"404":{"description":"Criterion not found"}}},"put":{"tags":["Criteria"],"summary":"Update criterion","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateCriteriaInput"}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CriteriaResponse"}}}},"400":{"description":"Invalid dependency reference or self-reference"},"404":{"description":"Criterion not found"}}},"delete":{"tags":["Criteria"],"summary":"Soft-delete criterion","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"deleted":{"type":"boolean"}},"required":["id","deleted"]}}}},"404":{"description":"Criterion not found"},"409":{"description":"Criterion has dependents"}}}},"/api/v1/prompt-features/generate-prompt":{"post":{"tags":["Prompt Features"],"summary":"Generate prompt feature from behavior","parameters":[{"schema":{"type":"string","minLength":1,"description":"Optional project scope. When provided, a slug/id is resolved within that project (slugs may repeat across projects); when omitted, resolution falls back to a legacy global lookup for backward compatibility.","example":"00000000-0000-0000-0000-000000000000"},"required":false,"description":"Optional project scope. When provided, a slug/id is resolved within that project (slugs may repeat across projects); when omitted, resolution falls back to a legacy global lookup for backward compatibility.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"behavior":{"type":"string"},"currentId":{"type":"string"}},"required":["behavior"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"prompt":{"type":"string"}},"required":["prompt"]}}}},"400":{"description":"Empty behavior string"},"503":{"description":"LLM not configured"}}}},"/api/v1/prompt-features/seed":{"post":{"tags":["Prompt Features"],"summary":"Seed prompt features in bulk","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"features":{"type":"array","items":{"$ref":"#/components/schemas/CreatePromptFeatureInput"}}},"required":["features"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"seeded":{"type":"number"},"errors":{"type":"array","items":{"type":"string"}}},"required":["seeded","errors"]}}}}}}},"/api/v1/prompt-features/extract-from-text":{"post":{"tags":["Prompt Features"],"summary":"Extract features from text","parameters":[{"schema":{"type":"string","minLength":1,"description":"Optional project scope. When provided, a slug/id is resolved within that project (slugs may repeat across projects); when omitted, resolution falls back to a legacy global lookup for backward compatibility.","example":"00000000-0000-0000-0000-000000000000"},"required":false,"description":"Optional project scope. When provided, a slug/id is resolved within that project (slugs may repeat across projects); when omitted, resolution falls back to a legacy global lookup for backward compatibility.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"text":{"type":"string"},"model":{"type":"string"},"type":{"type":"string","enum":["select","agents.md"]}},"required":["text"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"features":{"type":"array","items":{"$ref":"#/components/schemas/PromptFeatureResult"}},"suggestedFeatures":{"type":"array","items":{"$ref":"#/components/schemas/SuggestedPromptFeature"}},"cached":{"type":"boolean"}},"required":["features","cached"]}}}},"400":{"description":"Empty text string"},"503":{"description":"LLM not configured"}}}},"/api/v1/prompt-features":{"get":{"tags":["Prompt Features"],"summary":"List features","parameters":[{"schema":{"type":"string"},"required":false,"name":"q","in":"query"},{"schema":{"type":"string","enum":["select","agents.md"]},"required":false,"name":"type","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/PromptFeatureResponse"}}}}}}},"post":{"tags":["Prompt Features"],"summary":"Create feature","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreatePromptFeatureInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PromptFeatureResponse"}}}},"400":{"description":"Invalid input"},"409":{"description":"Feature already exists"}}}},"/api/v1/prompt-features/{id}":{"get":{"tags":["Prompt Features"],"summary":"Get feature","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PromptFeatureResponse"}}}},"404":{"description":"Feature not found"}}},"put":{"tags":["Prompt Features"],"summary":"Update feature","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdatePromptFeatureInput"}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PromptFeatureResponse"}}}},"400":{"description":"Invalid input"},"404":{"description":"Feature not found"}}},"delete":{"tags":["Prompt Features"],"summary":"Soft-delete feature","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"deleted":{"type":"boolean"}},"required":["id","deleted"]}}}},"404":{"description":"Feature not found"}}}},"/api/v1/task-prompts/generate":{"post":{"tags":["Task Prompts"],"summary":"Generate task prompts","requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"description":{"type":"string"},"existingPrompt":{"type":"string"}}}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"tasks":{"type":"array","items":{"type":"string"}}},"required":["tasks"]}}}},"503":{"description":"LLM not configured"}}}},"/api/v1/task-prompts":{"get":{"tags":["Task Prompts"],"summary":"List task prompts","parameters":[{"schema":{"type":["number","null"]},"required":false,"name":"limit","in":"query"},{"schema":{"type":["number","null"]},"required":false,"name":"offset","in":"query"},{"schema":{"type":"string"},"required":false,"name":"search","in":"query"},{"schema":{"$ref":"#/components/schemas/PromptType"},"required":false,"name":"type","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"items":{"type":"array","items":{"$ref":"#/components/schemas/TaskPromptResponse"}},"total":{"type":"number"},"limit":{"type":"number"},"offset":{"type":"number"}},"required":["items","total","limit","offset"]}}}}}},"post":{"tags":["Task Prompts"],"summary":"Create or find task prompt","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateTaskPromptInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/TaskPromptResponse"}}}},"400":{"description":"Empty text string"}}}},"/api/v1/task-prompts/{id}":{"get":{"tags":["Task Prompts"],"summary":"Get task prompt","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/TaskPromptResponse"}}}},"404":{"description":"Task prompt not found"}}},"delete":{"tags":["Task Prompts"],"summary":"Soft-delete task prompt","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"deleted":{"type":"boolean"}},"required":["deleted"]}}}},"404":{"description":"Task prompt not found"}}}},"/api/v1/task-prompts/{id}/content":{"get":{"tags":["Task Prompts"],"summary":"Get resolved task prompt content","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"text":{"type":"string"}},"required":["id","text"]}}}},"404":{"description":"Task prompt not found"}}}},"/api/v1/task-prompts/{id}/extract-features":{"post":{"tags":["Task Prompts"],"summary":"Extract features from task prompt","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":false,"name":"force","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"model":{"type":"string"}}}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"taskPromptId":{"type":"string"},"features":{"type":"array","items":{"$ref":"#/components/schemas/PromptFeatureResult"}},"featuresExtractedAt":{"type":["string","null"],"format":"date-time"},"suggestedFeatures":{"type":"array","items":{"$ref":"#/components/schemas/SuggestedPromptFeature"}},"cached":{"type":"boolean"}},"required":["taskPromptId","features","cached"]}}}},"404":{"description":"Task prompt not found"},"503":{"description":"LLM not configured"}}}},"/api/v1/task-prompts/{id}/features/{featureId}":{"patch":{"tags":["Task Prompts"],"summary":"Toggle feature flag on task prompt","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":true,"name":"featureId","in":"path"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PatchTaskPromptFeatureInput"}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/TaskPromptResponse"}}}},"400":{"description":"Invalid detected value"},"404":{"description":"Task prompt or feature not found"}}}},"/api/v1/reports":{"post":{"tags":["Reports"],"summary":"Create report","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateReportInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportResponse"}}}},"400":{"description":"Invalid input"},"404":{"description":"Run or template not found"}}},"get":{"tags":["Reports"],"summary":"List reports","parameters":[{"schema":{"type":"string"},"required":false,"name":"requestId","in":"query"},{"schema":{"type":"string"},"required":false,"name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ReportResponse"}}}}}}}},"/api/v1/reports/bulk-create":{"post":{"tags":["Reports"],"summary":"Bulk create reports","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BulkCreateReportsInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ReportResponse"}}}}},"400":{"description":"Invalid input"}}}},"/api/v1/reports/bulk-status":{"post":{"tags":["Reports"],"summary":"Bulk get report statuses","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BulkReportStatusInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ReportResponse"}}}}},"400":{"description":"Invalid input"}}}},"/api/v1/reports/bulk-summary":{"post":{"tags":["Reports"],"summary":"Bulk get report summary per run","description":"Returns aggregated report status counts per run. Only the latest report per template is counted (re-triggers are deduplicated).","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BulkReportSummaryInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/BulkReportSummaryResponse"}}}},"400":{"description":"Invalid input"}}}},"/api/v1/reports/{id}":{"get":{"tags":["Reports"],"summary":"Get report","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportResponse"}}}},"404":{"description":"Report not found"}}}},"/api/v1/reports/{id}/logs":{"get":{"tags":["Reports"],"summary":"Stream report logs (SSE)","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Server-sent event stream of log entries"},"404":{"description":"Report not found"}}}},"/api/v1/reports/trigger":{"post":{"tags":["Reports"],"summary":"Trigger reports","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TriggerReportsInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"triggered":{"type":"number"},"reports":{"type":"array","items":{"$ref":"#/components/schemas/ReportResponse"}}},"required":["triggered","reports"]}}}},"400":{"description":"Invalid input"},"404":{"description":"Run not found"}}}},"/api/v1/reports/bulk-trigger":{"post":{"tags":["Reports"],"summary":"Bulk trigger reports","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BulkTriggerReportsInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"type":"object","properties":{},"additionalProperties":{}}}}}},"400":{"description":"Invalid input"}}}},"/api/v1/reports/{id}/insights":{"get":{"tags":["Reports"],"summary":"Get insights for report","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"allOf":[{"$ref":"#/components/schemas/InsightResponse"},{"type":"object","properties":{"referencedAt":{"type":["string","null"],"format":"date-time"},"isNew":{"type":"boolean"}}}]}}}}},"404":{"description":"Report not found"}}},"post":{"tags":["Reports"],"summary":"Link insight to report","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"insightId":{"type":"string"},"isNew":{"type":"boolean"}},"required":["insightId"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"insightId":{"type":"string"},"referencedAt":{"type":["string","null"],"format":"date-time"},"isNew":{"type":"boolean"}},"required":["insightId","referencedAt","isNew"]}}}},"404":{"description":"Report or insight not found"},"409":{"description":"Insight already referenced by this report"}}}},"/api/v1/profiles":{"post":{"tags":["Profiles"],"summary":"Create a new profile","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateProfileInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProfileWithVersionResponse"}}}}}},"get":{"tags":["Profiles"],"summary":"List profiles","parameters":[{"schema":{"type":"string"},"required":false,"name":"workerType","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ProfileWithVersionResponse"}}}}}}}},"/api/v1/profiles/{profileId}":{"get":{"tags":["Profiles"],"summary":"Get profile with latest version","parameters":[{"schema":{"type":"string"},"required":true,"name":"profileId","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProfileWithVersionResponse"}}}}}},"post":{"tags":["Profiles"],"summary":"Create new profile version","parameters":[{"schema":{"type":"string"},"required":true,"name":"profileId","in":"path"}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"workerType":{"type":"string"},"model":{"type":"string"},"reasoningEffort":{"type":"string"},"agentVersion":{"type":"string"},"mcpServers":{"type":"array","items":{"type":"string"}},"skillRevisions":{"type":"array","items":{"type":"string"}},"resources":{"type":"array","items":{"$ref":"#/components/schemas/ResourceBindingSpec"}},"extensions":{"type":"array","items":{"type":"string"}}},"required":["workerType","model"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProfileVersionResponse"}}}}}},"put":{"tags":["Profiles"],"summary":"Update profile identity","parameters":[{"schema":{"type":"string"},"required":true,"name":"profileId","in":"path"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateProfileIdentity"}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProfileResponse"}}}}}},"delete":{"tags":["Profiles"],"summary":"Delete profile","parameters":[{"schema":{"type":"string"},"required":true,"name":"profileId","in":"path"}],"responses":{"204":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string"}},"required":["message"]}}}}}}},"/api/v1/profiles/{profileId}/versions":{"get":{"tags":["Profiles"],"summary":"List profile versions","parameters":[{"schema":{"type":"string"},"required":true,"name":"profileId","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ProfileVersionResponse"}}}}}}}},"/api/v1/profiles/{profileId}/versions/{version}":{"get":{"tags":["Profiles"],"summary":"Get profile version","parameters":[{"schema":{"type":"string"},"required":true,"name":"profileId","in":"path"},{"schema":{"type":["number","null"]},"required":false,"name":"version","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProfileVersionResponse"}}}}}}},"/api/v1/report-templates/default-system-prompt":{"get":{"tags":["Report Templates"],"summary":"Get default system prompt","responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"content":{"type":"string"}},"required":["content"]}}}}}}},"/api/v1/report-templates/available-models":{"get":{"tags":["Report Templates"],"summary":"List models available for report generation","responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"type":"object","properties":{"modelId":{"type":"string"}},"required":["modelId"]}}}}}}}},"/api/v1/report-templates":{"get":{"tags":["Report Templates"],"summary":"List report templates","parameters":[{"schema":{"type":"string"},"required":false,"name":"q","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ReportTemplateResponse"}}}}}}},"post":{"tags":["Report Templates"],"summary":"Create report template","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateReportTemplateInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportTemplateResponse"}}}},"409":{"description":"Report template already exists"}}}},"/api/v1/report-templates/{id}":{"get":{"tags":["Report Templates"],"summary":"Get report template","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportTemplateResponse"}}}},"404":{"description":"Report template not found"}}},"put":{"tags":["Report Templates"],"summary":"Update report template","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateReportTemplateInput"}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportTemplateResponse"}}}},"404":{"description":"Report template not found"}}},"delete":{"tags":["Report Templates"],"summary":"Delete report template","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"204":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string"}},"required":["message"]}}}},"404":{"description":"Report template not found"}}}},"/api/v1/agents":{"get":{"tags":["Agents"],"summary":"List agents","parameters":[{"schema":{"type":"string"},"required":false,"name":"modelProvider","in":"query"},{"schema":{"type":"string","enum":["true","false"]},"required":false,"name":"includeDeleted","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/AgentResponse"}}}}}}},"post":{"tags":["Agents"],"summary":"Create or update agent (upsert)","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateAgentInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentResponse"}}}},"400":{"description":"Validation error"},"409":{"description":"Restored agent versions conflict with an active queue owner"}}}},"/api/v1/agents/{id}":{"get":{"tags":["Agents"],"summary":"Get agent","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","enum":["true","false"]},"required":false,"name":"includeDeleted","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentResponse"}}}},"404":{"description":"Agent not found"}}},"put":{"tags":["Agents"],"summary":"Update agent","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateAgentInput"}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentResponse"}}}},"400":{"description":"Validation error"},"404":{"description":"Agent not found"}}},"delete":{"tags":["Agents"],"summary":"Delete agent","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"204":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string"}},"required":["message"]}}}},"404":{"description":"Agent not found"}}}},"/api/v1/agents/{id}/versions":{"get":{"tags":["Agents"],"summary":"List agent versions","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":false,"name":"status","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/AgentVersion"}}}}},"404":{"description":"Agent not found"}}},"post":{"tags":["Agents"],"summary":"Register agent version (upsert)","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RegisterAgentVersionInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentVersion"}}}},"400":{"description":"Validation error"},"404":{"description":"Agent not found"},"409":{"description":"Queue is assigned to another agent"},"503":{"description":"Concurrent registration did not stabilize"}}}},"/api/v1/agents/{id}/versions/{agentVersion}":{"patch":{"tags":["Agents"],"summary":"Patch agent version","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":true,"name":"agentVersion","in":"path"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PatchAgentVersionInput"}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentVersion"}}}},"400":{"description":"Invalid status value"},"404":{"description":"Agent or version not found"},"409":{"description":"Queue is assigned to another agent"},"503":{"description":"Concurrent activation did not stabilize"}}}},"/api/v1/models":{"get":{"tags":["Models"],"summary":"List models","parameters":[{"schema":{"type":"string"},"required":false,"name":"agentId","in":"query"},{"schema":{"type":"string"},"required":false,"name":"provider","in":"query"},{"schema":{"type":"string","enum":["active","disappeared"]},"required":false,"name":"status","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ModelResponse"}}}}}}}},"/api/v1/models/{id}":{"get":{"tags":["Models"],"summary":"Get model","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ModelResponse"}}}}}}},"/api/v1/models/sync":{"post":{"tags":["Models"],"summary":"Sync models from provider","requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"agentId":{"type":"string"},"provider":{"type":"string"},"models":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"providerAvailableFrom":{"type":"string"},"providerEndOfLife":{"type":"string"},"metadata":{"type":"object","additionalProperties":{}},"capabilities":{"type":"object","properties":{"reasoningEffort":{"type":"array","items":{"type":"string"}},"toolCalls":{"type":"boolean"},"vision":{"type":"boolean"},"streaming":{"type":"boolean"},"adaptiveThinking":{"type":"boolean"},"maxThinkingBudget":{"type":"number"}}}},"required":["id"]}},"scannedAt":{"type":"string"}},"required":["agentId","provider","models","scannedAt"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"added":{"type":"array","items":{"type":"string"}},"removed":{"type":"array","items":{"type":"string"}},"unchanged":{"type":"array","items":{"type":"string"}}},"required":["added","removed","unchanged"]}}}}}}},"/api/v1/mcp/servers":{"get":{"tags":["MCP Servers"],"summary":"List MCP servers","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/McpServerResponse"}}}}}}},"post":{"tags":["MCP Servers"],"summary":"Create MCP server","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"_id":{"type":"string","pattern":"^[a-z0-9]([a-z0-9-]*[a-z0-9])?$"},"name":{"type":"string"},"type":{"type":"string","enum":["sse","http","stdio"]},"url":{"type":"string"},"command":{"type":"string"},"args":{"type":"array","items":{"type":"string"}},"env":{"type":"object","additionalProperties":{"type":"string"}},"headers":{"type":"array","items":{"$ref":"#/components/schemas/McpServerHeader"}},"sessionMode":{"type":"string","enum":["stateful","stateless"]},"version":{"type":"string"},"description":{"type":"string"}},"required":["_id","name","type"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/McpServerResponse"}}}}}}},"/api/v1/mcp/servers/{id}":{"get":{"tags":["MCP Servers"],"summary":"Get MCP server","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/McpServerResponse"}}}}}},"put":{"tags":["MCP Servers"],"summary":"Update MCP server","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateMcpServerInput"}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/McpServerResponse"}}}}}},"delete":{"tags":["MCP Servers"],"summary":"Delete MCP server","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"204":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string"}},"required":["message"]}}}}}}},"/api/v1/skills":{"get":{"tags":["Skills"],"summary":"List all skills","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/SkillResponse"}}}}}}},"post":{"tags":["Skills"],"summary":"Create or import a skill","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateSkillInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SkillResponse"}}}}}}},"/api/v1/skills/search":{"get":{"tags":["Skills"],"summary":"Search skills (internal + external)","parameters":[{"schema":{"type":"string"},"required":true,"name":"q","in":"query"},{"schema":{"type":"string"},"required":false,"name":"limit","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/SkillSearchResult"}}}}},"400":{"description":"Missing query parameter"}}}},"/api/v1/skills/search/external":{"get":{"tags":["Skills"],"summary":"Search external skills registry","parameters":[{"schema":{"type":"string"},"required":true,"name":"q","in":"query"},{"schema":{"type":"string"},"required":false,"name":"limit","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Optional project scope. When provided, external results are de-duplicated only against skills already installed in that project."},"required":false,"description":"Optional project scope. When provided, external results are de-duplicated only against skills already installed in that project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/SkillSearchResult"}}}}},"400":{"description":"Missing query parameter"}}}},"/api/v1/skills/discover":{"get":{"tags":["Skills"],"summary":"Discover skills in a GitHub repository","parameters":[{"schema":{"type":"string"},"required":true,"name":"source","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/SkillDiscoveryResult"}}}}},"400":{"description":"Missing or malformed source parameter"},"404":{"description":"Repository not found"},"502":{"description":"GitHub API error"}}}},"/api/v1/skills/{id}(*)/revisions":{"get":{"tags":["Skills"],"summary":"List skill revisions","parameters":[{"schema":{"type":"string"},"required":false,"name":"limit","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/SkillRevisionResponse"}}}}},"404":{"description":"Skill not found"}}}},"/api/v1/skills/{id}(*)":{"get":{"tags":["Skills"],"summary":"Get skill by slug","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SkillResponse"}}}},"404":{"description":"Skill not found"}}},"delete":{"tags":["Skills"],"summary":"Soft-delete a skill","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"204":{"description":"Success"},"404":{"description":"Skill not found"}}}},"/api/v1/skill-revisions/by-ref/{ref}(*)/archive":{"get":{"tags":["Skill Revisions"],"summary":"Download skill revision archive","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Binary tar.gz archive"},"404":{"description":"Skill revision or archive not found"},"500":{"description":"Blob storage error"}}}},"/api/v1/skill-revisions/by-ref/{ref}(*)":{"get":{"tags":["Skill Revisions"],"summary":"Get skill revision by ref","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SkillRevisionResponse"}}}},"404":{"description":"Skill revision not found"}}}},"/api/v1/skill-revisions/{id}":{"get":{"tags":["Skill Revisions"],"summary":"Get skill revision by ID","responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SkillRevisionResponse"}}}},"404":{"description":"Skill revision not found"}}}},"/api/v1/skills/{id}(*)/resolve":{"post":{"tags":["Skills"],"summary":"Trigger skill resolution","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SkillRevisionResponse"}}}},"404":{"description":"Skill not found"},"500":{"description":"Blob storage error"}}}},"/api/v1/codebases":{"get":{"tags":["Codebases"],"summary":"List all codebases","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/CodebaseResponse"}}}}}}},"post":{"tags":["Codebases"],"summary":"Create a codebase (archive codebases require the archive file)","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"201":{"description":"Success"},"400":{"description":"Invalid input or missing archive"}}}},"/api/v1/codebases/{id}":{"get":{"tags":["Codebases"],"summary":"Get a codebase","responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CodebaseResponse"}}}},"404":{"description":"Codebase not found"}}},"patch":{"tags":["Codebases"],"summary":"Update a codebase","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateCodebaseInput"}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CodebaseResponse"}}}},"404":{"description":"Codebase not found"}}},"delete":{"tags":["Codebases"],"summary":"Delete a codebase","responses":{"204":{"description":"Success"},"404":{"description":"Codebase not found"}}}},"/api/v1/codebases/{id}/revisions":{"get":{"tags":["Codebases"],"summary":"List codebase revisions","parameters":[{"schema":{"type":"string"},"required":false,"name":"limit","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/CodebaseRevisionResponse"}}}}},"404":{"description":"Codebase not found"}}},"post":{"tags":["Codebases"],"summary":"Resolve a new git codebase revision","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ResolveCodebaseRevisionInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CodebaseRevisionResponse"}}}},"400":{"description":"Not a git codebase"},"404":{"description":"Codebase not found"},"502":{"description":"GitHub resolution failed"}}}},"/api/v1/codebases/{id}/upload":{"post":{"tags":["Codebases"],"summary":"Upload a codebase archive as a new revision","responses":{"201":{"description":"Success"},"400":{"description":"Missing archive or not an archive codebase"},"404":{"description":"Codebase not found"}}}},"/api/v1/codebase-revisions/{id}/archive":{"get":{"tags":["Codebase Revisions"],"summary":"Download codebase revision archive","responses":{"200":{"description":"Binary tar.gz archive"},"404":{"description":"Revision or archive not found"},"500":{"description":"Blob storage error"}}}},"/api/v1/codebase-revisions/{id}":{"get":{"tags":["Codebase Revisions"],"summary":"Get codebase revision by id","responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CodebaseRevisionResponse"}}}},"404":{"description":"Revision not found"}}}},"/api/v1/resources":{"get":{"tags":["Resources"],"summary":"List all resources","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ResourceResponse"}}}}}}},"post":{"tags":["Resources"],"summary":"Create a resource and its first revision","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateResourceInput"}}}},"responses":{"201":{"description":"Success"},"400":{"description":"Invalid input"},"409":{"description":"Resource slug or revision ref already exists in this project"}}}},"/api/v1/resources/{id}":{"get":{"tags":["Resources"],"summary":"Get a resource","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ResourceResponse"}}}},"404":{"description":"Resource not found"}}},"patch":{"tags":["Resources"],"summary":"Update a resource","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateResourceInput"}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ResourceResponse"}}}},"404":{"description":"Resource not found"}}},"delete":{"tags":["Resources"],"summary":"Delete a resource","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"204":{"description":"Success"},"404":{"description":"Resource not found"}}}},"/api/v1/resources/{id}/revisions":{"get":{"tags":["Resource Revisions"],"summary":"List resource revisions","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"},{"schema":{"type":"string"},"required":false,"name":"limit","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ResourceRevisionResponse"}}}}},"404":{"description":"Resource not found"}}},"post":{"tags":["Resource Revisions"],"summary":"Create a resource revision","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateResourceRevisionInput"}}}},"responses":{"201":{"description":"Success"},"404":{"description":"Resource not found"},"409":{"description":"Resource revision ref already exists in this project"}}}},"/api/v1/resources/{id}/revisions/latest":{"get":{"tags":["Resource Revisions"],"summary":"Get the latest resource revision","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ResourceRevisionResponse"}}}},"404":{"description":"Revision not found"}}}},"/api/v1/resources/{id}/revisions/{revisionNumber}":{"get":{"tags":["Resource Revisions"],"summary":"Get a resource revision by resource and revision number","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":true,"name":"revisionNumber","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ResourceRevisionResponse"}}}},"404":{"description":"Revision not found"}}}},"/api/v1/resources/revisions/{id}":{"get":{"tags":["Resource Revisions"],"summary":"Get resource revision by id","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ResourceRevisionResponse"}}}},"404":{"description":"Revision not found"}}}},"/api/v1/extensions":{"get":{"tags":["Extensions"],"summary":"List all extensions","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ExtensionResponse"}}}}}}},"post":{"tags":["Extensions"],"summary":"Create or import an extension","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateExtensionInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExtensionResponse"}}}}}}},"/api/v1/extensions/search":{"get":{"tags":["Extensions"],"summary":"Search extensions (internal + marketplace)","parameters":[{"schema":{"type":"string"},"required":true,"name":"q","in":"query"},{"schema":{"type":"string"},"required":false,"name":"limit","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ExtensionSearchResult"}}}}},"400":{"description":"Missing query parameter"}}}},"/api/v1/extensions/{id}":{"get":{"tags":["Extensions"],"summary":"Get extension by ID","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExtensionResponse"}}}}}},"put":{"tags":["Extensions"],"summary":"Update extension","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateExtensionInput"}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExtensionResponse"}}}}}},"delete":{"tags":["Extensions"],"summary":"Delete extension","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"204":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string"}},"required":["message"]}}}}}}},"/api/v1/extensions/{id}/versions":{"get":{"tags":["Extensions"],"summary":"List available versions for an extension","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":false,"name":"preRelease","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ExtensionVersionInfo"}}}}}}}},"/api/v1/insights":{"get":{"tags":["Insights"],"summary":"List insights","parameters":[{"schema":{"type":"string"},"required":false,"name":"q","in":"query"},{"schema":{"type":"string"},"required":false,"name":"blocked","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/InsightResponse"}}}}}}},"post":{"tags":["Insights"],"summary":"Create insight","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateInsightInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InsightResponse"}}}}}}},"/api/v1/insights/search":{"get":{"tags":["Insights"],"summary":"Search insights","parameters":[{"schema":{"type":"string"},"required":true,"name":"q","in":"query"},{"schema":{"type":"string"},"required":false,"name":"blocked","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/InsightResponse"}}}}}}}},"/api/v1/insights/{id}":{"get":{"tags":["Insights"],"summary":"Get insight","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InsightResponse"}}}},"404":{"description":"Insight not found"}}},"put":{"tags":["Insights"],"summary":"Update insight","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateInsightInput"}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InsightResponse"}}}},"404":{"description":"Insight not found"}}},"delete":{"tags":["Insights"],"summary":"Delete insight","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"204":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string"}},"required":["message"]}}}},"404":{"description":"Insight not found"}}}},"/api/v1/insights/{id}/upvote":{"post":{"tags":["Insights"],"summary":"Upvote insight","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InsightResponse"}}}},"404":{"description":"Insight not found"}}}},"/api/v1/insights/{id}/downvote":{"post":{"tags":["Insights"],"summary":"Downvote insight","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InsightResponse"}}}},"404":{"description":"Insight not found"}}}},"/api/v1/insights/{id}/block":{"post":{"tags":["Insights"],"summary":"Block insight","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InsightResponse"}}}},"404":{"description":"Insight not found"}}}},"/api/v1/insights/{id}/unblock":{"post":{"tags":["Insights"],"summary":"Unblock insight","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InsightResponse"}}}},"404":{"description":"Insight not found"}}}},"/api/v1/insights/{id}/reports":{"get":{"tags":["Insights"],"summary":"Get reports referencing insight","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ReportResponse"}}}}},"404":{"description":"Insight not found"}}}},"/api/v1/feature-flags":{"get":{"tags":["Feature Flags"],"summary":"List feature flags","responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/FeatureFlagResponse"}}}}}}}},"/api/v1/feature-flags/{key}":{"put":{"tags":["Feature Flags"],"summary":"Update feature flag","parameters":[{"schema":{"type":"string"},"required":true,"name":"key","in":"path"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateFeatureFlagInput"}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FeatureFlagResponse"}}}}}}}},"webhooks":{}} \ No newline at end of file +{"openapi":"3.1.0","info":{"title":"Scope API","version":"1.0.0","description":"REST API for the Scope platform — benchmarking AI coding agents"},"servers":[{"url":"/","description":"Current server"}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Use the unchanged IdP access token, without the Bearer prefix."}},"schemas":{"KeyResponse":{"type":"object","properties":{},"additionalProperties":{}},"KeyInput":{"type":"object","properties":{},"additionalProperties":{}},"ValidateKeyInput":{"type":"object","properties":{"token":{"type":"string"}},"required":["token"]},"AccountResponse":{"type":"object","properties":{},"additionalProperties":{}},"AccountInput":{"type":"object","properties":{},"additionalProperties":{}},"UserMeResponse":{"type":"object","properties":{"id":{"type":"string"},"role":{"type":"string"},"email":{"type":"string"},"displayName":{"type":"string"},"idp":{"type":"string"},"idpTenant":{"type":"string"}},"required":["id"]},"ProjectResponse":{"type":"object","properties":{"_id":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"creator":{"type":"string"},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"deletedAt":{"type":["string","null"],"format":"date-time"}},"required":["_id","name","createdAt"]},"CreateProjectInput":{"type":"object","properties":{"name":{"type":"string","minLength":1},"description":{"type":"string"},"creator":{"type":"string"}},"required":["name"]},"UpdateProjectInput":{"type":"object","properties":{"name":{"type":"string","minLength":1},"description":{"type":"string"}}},"SubmissionListResponse":{"type":"object","properties":{"submissions":{"type":"array","items":{"$ref":"#/components/schemas/SubmissionResponse"}}},"required":["submissions"]},"SubmissionResponse":{"type":"object","properties":{"submissionId":{"type":"string"},"projectId":{"type":"string"},"requestIds":{"type":"array","items":{"type":"string"}},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"submissionRunId":{"type":"string"},"attemptNumber":{"type":"integer"},"readiness":{"type":"string","enum":["waiting","ready","blocked","processing","done","failed"]},"requests":{"type":"array","items":{"$ref":"#/components/schemas/SubmissionRequestSummary"}},"dependencyProjection":{"type":"array","items":{"$ref":"#/components/schemas/SubmissionDependencyProjection"}},"blocking":{"type":"array","items":{"$ref":"#/components/schemas/SubmissionBlockingDetail"}},"handlerProgress":{"type":"object","additionalProperties":{"$ref":"#/components/schemas/SubmissionHandlerStatus"}},"report":{"$ref":"#/components/schemas/SubmissionReportPointer"},"supersededAt":{"type":["string","null"],"format":"date-time"},"supersededBySubmissionRunId":{"type":"string"},"supersededReason":{"type":"string","enum":["request-vector-changed","manual-retry"]}},"required":["submissionId","projectId","requestIds","createdAt","submissionRunId","attemptNumber","readiness","requests","dependencyProjection","blocking"]},"SubmissionRequestSummary":{"type":"object","properties":{"requestId":{"type":"string"},"runId":{"type":"string"},"task":{"type":"string"},"status":{"type":"string"},"outcome":{"type":"string"},"workerType":{"type":"string"},"model":{"type":"string"},"profileId":{"type":"string"}},"required":["requestId","runId","task","status","workerType"]},"SubmissionDependencyProjection":{"type":"object","properties":{"requestId":{"type":"string"},"runId":{"type":"string"},"handlerId":{"type":"string"},"state":{"type":"string","enum":["waiting","ready","failed","blocked"]},"version":{"type":"number"},"updatedAt":{"type":["string","null"],"format":"date-time"},"error":{"type":"string"}},"required":["requestId","runId","handlerId","state"]},"SubmissionBlockingDetail":{"type":"object","properties":{"requestId":{"type":"string"},"runId":{"type":"string"},"handlerId":{"type":"string"},"reason":{"type":"string","enum":["request-missing","run-changed","dependency-not-ready","dependency-failed","dependency-blocked"]},"error":{"type":"string"}},"required":["requestId","runId","handlerId","reason"]},"SubmissionHandlerStatus":{"type":"object","properties":{"status":{"type":"string","enum":["queued","processing","done","failed"]},"version":{"type":"number"},"updatedAt":{"type":["string","null"],"format":"date-time"},"error":{"type":"string"}},"required":["status"]},"SubmissionReportPointer":{"type":"object","properties":{"reportId":{"type":"string"},"url":{"type":"string"},"updatedAt":{"type":["string","null"],"format":"date-time"}}},"SubmissionRunResponse":{"type":"object","properties":{"_id":{"type":"string"},"attemptNumber":{"type":"integer","minimum":1},"vectorFingerprint":{"type":"string"},"requests":{"type":"array","items":{"$ref":"#/components/schemas/SubmissionRequestRef"}},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"startedAt":{"type":["string","null"],"format":"date-time"},"finishedAt":{"type":["string","null"],"format":"date-time"},"dependencyProjection":{"type":"array","items":{"$ref":"#/components/schemas/SubmissionDependencyProjection"},"default":[]},"handlerStatus":{"type":"object","additionalProperties":{"$ref":"#/components/schemas/SubmissionHandlerStatus"}},"blocking":{"type":"array","items":{"$ref":"#/components/schemas/SubmissionBlockingDetail"},"default":[]},"report":{"$ref":"#/components/schemas/SubmissionReportPointer"},"supersededAt":{"type":["string","null"],"format":"date-time"},"supersededBySubmissionRunId":{"type":"string"},"supersededReason":{"type":"string","enum":["request-vector-changed","manual-retry"]},"submissionId":{"type":"string"},"projectId":{"type":"string"}},"required":["_id","attemptNumber","vectorFingerprint","requests","createdAt"]},"SubmissionRequestRef":{"type":"object","properties":{"requestId":{"type":"string"},"runId":{"type":"string"}},"required":["requestId","runId"]},"SubmissionRetryResponse":{"type":"object","properties":{"submissionId":{"type":"string"},"submissionRunId":{"type":"string"},"attemptNumber":{"type":"integer"},"readiness":{"type":"string","enum":["waiting","ready","blocked","processing","done","failed"]},"blocking":{"type":"array","items":{"$ref":"#/components/schemas/SubmissionBlockingDetail"}}},"required":["submissionId","submissionRunId","attemptNumber","readiness","blocking"]},"RequestResponse":{"type":"object","properties":{"_id":{"type":"string"},"scenario":{"$ref":"#/components/schemas/Scenario"},"workerType":{"type":"string"},"model":{"type":"string"},"reasoningEffort":{"type":"string"},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"maxIterations":{"type":"number"},"personaInstructions":{"type":"string"},"persona":{"$ref":"#/components/schemas/Persona"},"deletedAt":{"type":["string","null"],"format":"date-time"},"taskPromptId":{"type":"string"},"agentsMdPromptId":{"type":"string"},"agentsMdParentIds":{"type":"array","items":{"type":"string"}},"mcpServers":{"type":"array","items":{"type":"string"}},"skillRevisions":{"type":"array","items":{"type":"string"}},"codebaseRevisionId":{"type":"string"},"resources":{"type":"array","items":{"$ref":"#/components/schemas/ResourceBinding"}},"extensions":{"type":"array","items":{"type":"string"}},"agentVersion":{"type":"string"},"profileId":{"type":"string"},"profileVersionId":{"type":"string"},"submissionId":{"type":"string"},"submissionExpectedRequestCount":{"type":"integer","minimum":1},"submissionRequestIndex":{"type":"integer","minimum":0},"submissionInitialRunId":{"type":"string"},"submissionFinalizedAt":{"type":["string","null"],"format":"date-time"},"priority":{"type":"integer","default":0},"gates":{"type":"array","items":{"$ref":"#/components/schemas/GateConfig"}},"observations":{"type":"array","items":{"type":"string"}},"gateSummaries":{"type":"array","items":{"$ref":"#/components/schemas/GateRunSummary"}},"run":{"$ref":"#/components/schemas/RunState"},"projectId":{"type":"string"}},"required":["_id","scenario","workerType","createdAt","projectId"]},"Scenario":{"type":"object","properties":{"version":{"type":"string","enum":["v1","v2"]},"task":{"type":"string"},"criteria":{"type":"array","items":{"type":"string"}}},"required":["task","criteria"]},"Persona":{"type":"object","properties":{"personality":{"type":"string","enum":["demanding","friendly"]},"experience":{"type":"string","enum":["junior","senior"]},"verbosity":{"type":"string","enum":["brief","moderate"]},"type":{"type":"string","enum":["traditional","ai_assisted","vibe"]}},"required":["personality","experience","verbosity","type"]},"ResourceBinding":{"type":"object","properties":{"ref":{"type":"string"},"revisionId":{"type":"string"},"params":{"type":"object","additionalProperties":{"type":"string"}}},"required":["ref","revisionId","params"]},"GateConfig":{"type":"object","properties":{"gate":{"type":"string","enum":["select","build","test","run","deploy"]},"promptId":{"type":"string"},"promptText":{"type":"string"},"criteria":{"type":"array","items":{"type":"string"}},"maxIterations":{"type":"integer","minimum":1,"maximum":50}},"required":["gate","criteria"]},"GateRunSummary":{"type":"object","properties":{"gate":{"type":"string","enum":["select","build","test","run","deploy"]},"status":{"type":"string","enum":["passed","failed","skipped"]},"iterations":{"type":"integer","minimum":0}},"required":["gate","status","iterations"]},"RunState":{"type":"object","properties":{"_id":{"type":"string"},"attemptNumber":{"type":"integer","minimum":1},"status":{"type":"string","enum":["pending","queued","processing","paused","done"]},"queuedQueueName":{"type":"string"},"outcome":{"type":"string","enum":["succeeded","failed","finished"]},"result":{"type":"string"},"error":{"type":"string"},"logsUrl":{"type":"string"},"updatedAt":{"type":["string","null"],"format":"date-time"},"startedAt":{"type":["string","null"],"format":"date-time"},"finishedAt":{"type":["string","null"],"format":"date-time"},"durationMs":{"type":"number"},"turns":{"type":"array","items":{"$ref":"#/components/schemas/ConversationTurn"}},"workerVersion":{"type":"string"},"os":{"type":"object","properties":{"platform":{"type":"string"},"release":{"type":"string"},"arch":{"type":"string"}},"required":["platform","release","arch"]},"lastHeartbeatAt":{"type":["string","null"],"format":"date-time"},"worker":{"type":"object","properties":{"instanceId":{"type":"string"},"podName":{"type":"string"}},"required":["instanceId"]},"harUrl":{"type":"string"},"videoUrls":{"type":"array","items":{"type":"string"}},"setupVideoUrls":{"type":"array","items":{"type":"string"}},"tokenUsage":{"$ref":"#/components/schemas/TokenUsage"},"aiCallCount":{"type":"number"},"resources":{"type":"array","items":{"$ref":"#/components/schemas/ResourceRunOutcome"}},"mcpRegistered":{"type":"boolean"},"rawChatUrl":{"type":"string"},"rawChatFormat":{"type":"string"},"pausedAt":{"type":["string","null"],"format":"date-time"},"resumedAt":{"type":["string","null"],"format":"date-time"},"observationResults":{"type":"array","items":{"$ref":"#/components/schemas/CriterionResult"}}},"required":["_id","attemptNumber","status"]},"ConversationTurn":{"type":"object","properties":{"iteration":{"type":"number"},"gate":{"type":"string","enum":["select","build","test","run","deploy"]},"codingAgentResponse":{"type":"string"},"judgeFeedback":{"type":"string"},"snapshotUrl":{"type":"string"},"passed":{"type":"boolean"},"timestamp":{"type":["string","null"],"format":"date-time"},"criteriaResults":{"type":"array","items":{"$ref":"#/components/schemas/CriterionResult"}},"observationResults":{"type":"array","items":{"$ref":"#/components/schemas/CriterionResult"}},"harUrl":{"type":"string"},"videoUrls":{"type":"array","items":{"type":"string"}},"tokenUsage":{"$ref":"#/components/schemas/TokenUsage"},"startedAt":{"type":["string","null"],"format":"date-time"},"durationMs":{"type":"number"},"toolCalls":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"arguments":{"type":"object","additionalProperties":{}},"response":{"type":"string"},"timestamp":{"type":"string"}},"required":["id","name","arguments"]}},"toolCallsUrl":{"type":"string"},"toolCallCount":{"type":"number"},"aiCallCount":{"type":"number"},"rawChatUrl":{"type":"string"},"rawChatFormat":{"type":"string"},"chatResultUrl":{"type":"string"},"chatResultFormat":{"type":"string"}},"required":["iteration","judgeFeedback","snapshotUrl","passed","timestamp"]},"CriterionResult":{"type":"object","properties":{"criterionId":{"type":"string"},"passed":{"type":"boolean"},"feedback":{"type":"string"},"evaluated":{"type":"boolean"}},"required":["criterionId","passed","feedback","evaluated"]},"TokenUsage":{"type":"object","properties":{"promptTokens":{"type":"number"},"completionTokens":{"type":"number"},"totalTokens":{"type":"number"}},"required":["promptTokens","completionTokens","totalTokens"]},"ResourceRunOutcome":{"type":"object","properties":{"ref":{"type":"string"},"slug":{"type":"string"},"revisionId":{"type":"string"},"setupSucceeded":{"type":"boolean"},"published":{"type":"array","items":{"type":"string"}},"params":{"type":"object","additionalProperties":{"type":"string"}},"setupDurationMs":{"type":"number"},"error":{"type":"string"},"teardownRan":{"type":"boolean"}},"required":["ref","slug","revisionId","setupSucceeded","published"]},"ResourceBindingSpec":{"anyOf":[{"type":"string"},{"type":"object","properties":{"ref":{"type":"string"},"params":{"type":"object","additionalProperties":{"type":"string"}}},"required":["ref"]}]},"CreateRequestInput":{"type":"object","properties":{"scenario":{"$ref":"#/components/schemas/Scenario"},"model":{"type":"string"},"reasoningEffort":{"type":"string"},"maxIterations":{"type":"integer","minimum":1,"maximum":50},"personaInstructions":{"type":"string"},"persona":{"$ref":"#/components/schemas/Persona"},"mcpServers":{"type":"array","items":{"type":"string"}},"skillRevisions":{"type":"array","items":{"type":"string"}},"codebaseRevisionId":{"type":"string"},"resources":{"type":"array","items":{"$ref":"#/components/schemas/ResourceBindingSpec"}},"extensions":{"type":"array","items":{"type":"string"}},"profileId":{"type":"string"},"profileVariations":{"type":"array","items":{"type":"string"}},"priority":{"type":"integer"},"agentsMd":{"type":"string"},"agentsMdParentIds":{"type":"array","items":{"type":"string"}},"gates":{"type":"array","items":{"$ref":"#/components/schemas/GateConfig"}},"observations":{"type":"array","items":{"type":"string"}}},"required":["scenario"]},"RunFacetsResponse":{"type":"object","properties":{"total":{"type":"number"},"facets":{"type":"object","properties":{"workerType":{"type":"array","items":{"$ref":"#/components/schemas/RunFacetBucket"}},"status":{"type":"array","items":{"$ref":"#/components/schemas/RunFacetBucket"}},"outcome":{"type":"array","items":{"$ref":"#/components/schemas/RunFacetBucket"}},"model":{"type":"array","items":{"$ref":"#/components/schemas/RunFacetBucket"}},"os":{"type":"array","items":{"$ref":"#/components/schemas/RunFacetBucket"}},"priority":{"type":"array","items":{"$ref":"#/components/schemas/RunFacetBucket"}},"agentVersion":{"type":"array","items":{"$ref":"#/components/schemas/RunFacetBucket"}},"profileId":{"type":"array","items":{"$ref":"#/components/schemas/RunFacetBucket"}}},"required":["workerType","status","outcome","model","os","priority","agentVersion","profileId"]}},"required":["total","facets"]},"RunFacetBucket":{"type":"object","properties":{"value":{"type":"string"},"count":{"type":"number"}},"required":["value","count"]},"PaginatedRunsResponse":{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/RequestResponse"}},"limit":{"type":"number"},"estimatedTotal":{"type":"number"},"cursors":{"$ref":"#/components/schemas/Cursors"}},"required":["data","limit","estimatedTotal","cursors"]},"Cursors":{"type":"object","properties":{"next":{"type":["string","null"]},"prev":{"type":["string","null"]}},"required":["next","prev"]},"PaginatedRunGroupsResponse":{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/RunGroup"}},"limit":{"type":"number"},"estimatedTotal":{"type":"number"},"cursors":{"$ref":"#/components/schemas/Cursors"}},"required":["data","limit","estimatedTotal","cursors"]},"RunGroup":{"type":"object","properties":{"key":{"type":"string"},"label":{"type":"string"},"runIds":{"type":"array","items":{"type":"string"}},"aggregates":{"$ref":"#/components/schemas/GroupAggregates"},"uniform":{"$ref":"#/components/schemas/GroupUniformValues"}},"required":["key","label","runIds","aggregates","uniform"]},"GroupAggregates":{"type":"object","properties":{"count":{"type":"number"},"turns":{"$ref":"#/components/schemas/AggregateStats"},"duration":{"$ref":"#/components/schemas/AggregateStats"},"promptTokens":{"$ref":"#/components/schemas/AggregateStats"},"completionTokens":{"$ref":"#/components/schemas/AggregateStats"},"statusCounts":{"type":"object","additionalProperties":{"type":"number"}},"outcomeCounts":{"type":"object","additionalProperties":{"type":"number"}}},"required":["count","turns","duration","promptTokens","completionTokens","statusCounts","outcomeCounts"]},"AggregateStats":{"type":["object","null"],"properties":{"min":{"type":"number"},"max":{"type":"number"},"mean":{"type":"number"},"stdDev":{"type":"number"}},"required":["min","max","mean","stdDev"]},"GroupUniformValues":{"type":"object","properties":{"workerType":{"type":"string"},"agentVersion":{"type":"string"},"model":{"type":"string"},"platform":{"type":"string"},"mcpServers":{"type":"array","items":{"type":"string"}},"skillRevisions":{"type":"array","items":{"type":"string"}},"codebaseRevisionId":{"type":"string"},"extensions":{"type":"array","items":{"type":"string"}},"status":{"type":"string","enum":["pending","queued","processing","paused","done"]},"submissionId":{"type":"string"},"task":{"type":"string"}}},"BulkResubmitInput":{"type":"object","properties":{"ids":{"type":"array","items":{"type":"string"},"minItems":1},"count":{"type":"integer","minimum":1,"maximum":10,"default":1},"overrides":{"type":"object","properties":{"profileId":{"type":["string","null"]},"workerType":{"type":"string"},"agentVersion":{"type":"string"},"model":{"type":["string","null"]},"reasoningEffort":{"type":["string","null"]},"maxIterations":{"type":["number","null"]},"mcpServers":{"type":["array","null"],"items":{"type":"string"}},"skillRevisions":{"type":["array","null"],"items":{"type":"string"}},"extensions":{"type":["array","null"],"items":{"type":"string"}}}}},"required":["ids"]},"ReportResponse":{"type":"object","properties":{"_id":{"type":"string"},"requestId":{"type":"string"},"templateId":{"type":"string"},"reporter":{"$ref":"#/components/schemas/Reporter"},"content":{"type":"string"},"status":{"type":"string","enum":["pending","generating","completed","failed"]},"error":{"type":"string"},"insightReferences":{"type":"array","items":{"$ref":"#/components/schemas/InsightReference"}},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"projectId":{"type":"string"}},"required":["_id","requestId","status","createdAt","projectId"]},"Reporter":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"gitHash":{"type":"string"},"model":{"type":"string"},"agentId":{"type":"string"},"agentVersion":{"type":"string"}},"required":["id","name","gitHash","model","agentId","agentVersion"]},"InsightReference":{"type":"object","properties":{"insightId":{"type":"string"},"referencedAt":{"type":["string","null"],"format":"date-time"},"isNew":{"type":"boolean"}},"required":["insightId","referencedAt","isNew"]},"CreateCriteriaInput":{"type":"object","properties":{"id":{"type":"string","pattern":"^[a-z][a-z0-9_]*$"},"prompt":{"type":"string"},"dependsOn":{"type":"array","items":{"type":"string"}},"gates":{"type":"array","items":{"type":"string","enum":["select","build","test","run","deploy"]}},"kind":{"type":"string","enum":["gate","observation"],"default":"gate"},"taxonomyElementId":{"type":"string","enum":["dimension:idiomatic-use","dimension:dependency-currency","dimension:configuration-correctness"]},"subject":{"type":"string","enum":["run","iteration"]}},"required":["id","prompt"]},"CriteriaResponse":{"type":"object","properties":{"id":{"type":"string"},"prompt":{"type":"string"},"dependsOn":{"type":"array","items":{"type":"string"}},"gates":{"type":"array","items":{"type":"string","enum":["select","build","test","run","deploy"]}},"kind":{"type":"string","enum":["gate","observation"]},"taxonomyElementId":{"type":"string","enum":["dimension:idiomatic-use","dimension:dependency-currency","dimension:configuration-correctness"]},"subject":{"type":"string","enum":["run","iteration"]},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"deletedAt":{"type":["string","null"],"format":"date-time"},"projectId":{"type":"string"}},"required":["id","prompt","createdAt","projectId"]},"CriteriaGraph":{"type":"object","properties":{"nodes":{"type":"array","items":{"$ref":"#/components/schemas/CriteriaGraphNode"}},"edges":{"type":"array","items":{"$ref":"#/components/schemas/CriteriaGraphEdge"}}},"required":["nodes","edges"]},"CriteriaGraphNode":{"type":"object","properties":{"id":{"type":"string"},"prompt":{"type":"string"},"dependsOn":{"type":"array","items":{"type":"string"}},"gates":{"type":"array","items":{"type":"string","enum":["select","build","test","run","deploy"]}},"kind":{"type":"string","enum":["gate","observation"]},"taxonomyElementId":{"type":"string","enum":["dimension:idiomatic-use","dimension:dependency-currency","dimension:configuration-correctness"]},"subject":{"type":"string","enum":["run","iteration"]}},"required":["id","prompt"]},"CriteriaGraphEdge":{"type":"object","properties":{"from":{"type":"string"},"to":{"type":"string"}},"required":["from","to"]},"UpdateCriteriaInput":{"type":"object","properties":{"prompt":{"type":"string"},"dependsOn":{"type":"array","items":{"type":"string"}},"gates":{"type":"array","items":{"type":"string","enum":["select","build","test","run","deploy"]}},"kind":{"type":"string","enum":["gate","observation"]},"taxonomyElementId":{"type":"string","enum":["dimension:idiomatic-use","dimension:dependency-currency","dimension:configuration-correctness"]},"subject":{"type":"string","enum":["run","iteration"]}}},"CreatePromptFeatureInput":{"type":"object","properties":{"id":{"type":"string","pattern":"^[a-z][a-z0-9_]*$"},"prompt":{"type":"string"},"type":{"$ref":"#/components/schemas/PromptType"}},"required":["id","prompt"]},"PromptType":{"type":"string","enum":["select","build","test","run","deploy","agents.md"]},"PromptFeatureResult":{"type":"object","properties":{"featureId":{"type":"string"},"detected":{"type":"boolean"},"evaluated":{"type":"boolean"}},"required":["featureId","detected","evaluated"]},"SuggestedPromptFeature":{"type":"object","properties":{"suggestedId":{"type":"string"},"behavior":{"type":"string"},"prompt":{"type":"string"}},"required":["suggestedId","behavior","prompt"]},"PromptFeatureResponse":{"type":"object","properties":{"id":{"type":"string"},"prompt":{"type":"string"},"type":{"$ref":"#/components/schemas/PromptType"},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"deletedAt":{"type":["string","null"],"format":"date-time"},"projectId":{"type":"string"}},"required":["id","prompt","createdAt","projectId"]},"UpdatePromptFeatureInput":{"type":"object","properties":{"prompt":{"type":"string"}}},"TaskPromptResponse":{"type":"object","properties":{"_id":{"type":"string"},"keyId":{"type":"string"},"type":{"$ref":"#/components/schemas/PromptType"},"text":{"type":"string"},"contentBlobUrl":{"type":"string"},"features":{"type":"array","items":{"$ref":"#/components/schemas/PromptFeatureResult"}},"featuresExtractedAt":{"type":["string","null"],"format":"date-time"},"createdAt":{"type":["string","null"],"format":"date-time"},"deletedAt":{"type":["string","null"],"format":"date-time"},"projectId":{"type":"string"}},"required":["_id","keyId","createdAt","projectId"]},"CreateTaskPromptInput":{"type":"object","properties":{"text":{"type":"string"},"type":{"$ref":"#/components/schemas/PromptType"}},"required":["text"]},"PatchTaskPromptFeatureInput":{"type":"object","properties":{"detected":{"type":"boolean"}},"required":["detected"]},"CreateReportInput":{"type":"object","properties":{"requestId":{"type":"string"},"templateId":{"type":"string"}},"required":["requestId"]},"BulkCreateReportsInput":{"type":"object","properties":{"requestIds":{"type":"array","items":{"type":"string"}},"templateId":{"type":"string"}},"required":["requestIds"]},"BulkReportStatusInput":{"type":"object","properties":{"reportIds":{"type":"array","items":{"type":"string"}}},"required":["reportIds"]},"BulkReportSummaryResponse":{"type":"object","additionalProperties":{"$ref":"#/components/schemas/ReportSummary"}},"ReportSummary":{"type":"object","properties":{"total":{"type":"number"},"pending":{"type":"number"},"generating":{"type":"number"},"completed":{"type":"number"},"failed":{"type":"number"}},"required":["total","pending","generating","completed","failed"]},"BulkReportSummaryInput":{"type":"object","properties":{"requestIds":{"type":"array","items":{"type":"string"}}},"required":["requestIds"]},"TriggerReportsInput":{"type":"object","properties":{"requestId":{"type":"string"}},"required":["requestId"]},"BulkTriggerReportsInput":{"type":"object","properties":{"requestIds":{"type":"array","items":{"type":"string"}}},"required":["requestIds"]},"InsightResponse":{"type":"object","properties":{"_id":{"type":"string"},"title":{"type":"string"},"description":{"type":"string"},"category":{"type":"string"},"tags":{"type":"array","items":{"type":"string"}},"upvotes":{"type":"number"},"downvotes":{"type":"number"},"blocked":{"type":"boolean"},"referenceCount":{"type":"number"},"createdBy":{"type":"string","enum":["agent","user"]},"sourceReportId":{"type":"string"},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"deletedAt":{"type":["string","null"],"format":"date-time"},"projectId":{"type":"string"}},"required":["_id","title","description","upvotes","downvotes","blocked","referenceCount","createdBy","createdAt","projectId"]},"ProfileWithVersionResponse":{"type":"object","properties":{"_id":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"latestVersion":{"type":"number"},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"deletedAt":{"type":["string","null"],"format":"date-time"},"version":{"$ref":"#/components/schemas/ProfileVersionResponse"},"projectId":{"type":"string"}},"required":["_id","name","latestVersion","createdAt","version","projectId"]},"ProfileVersionResponse":{"type":"object","properties":{"_id":{"type":"string"},"profileId":{"type":"string"},"version":{"type":"number"},"workerType":{"type":"string"},"model":{"type":"string"},"reasoningEffort":{"type":"string"},"agentVersion":{"type":"string"},"mcpServers":{"type":"array","items":{"type":"string"}},"skillRevisions":{"type":"array","items":{"type":"string"}},"resources":{"type":"array","items":{"$ref":"#/components/schemas/ResourceBindingSpec"}},"extensions":{"type":"array","items":{"type":"string"}},"createdAt":{"type":["string","null"],"format":"date-time"},"projectId":{"type":"string"}},"required":["_id","profileId","version","workerType","model","createdAt","projectId"]},"CreateProfileInput":{"type":"object","properties":{"name":{"type":"string","minLength":1,"maxLength":128},"description":{"type":"string","maxLength":512},"workerType":{"type":"string"},"model":{"type":"string"},"reasoningEffort":{"type":"string"},"agentVersion":{"type":"string"},"mcpServers":{"type":"array","items":{"type":"string"}},"skillRevisions":{"type":"array","items":{"type":"string"}},"resources":{"type":"array","items":{"$ref":"#/components/schemas/ResourceBindingSpec"}},"extensions":{"type":"array","items":{"type":"string"}}},"required":["name","workerType","model"]},"ProfileResponse":{"type":"object","properties":{"_id":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"latestVersion":{"type":"number"},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"deletedAt":{"type":["string","null"],"format":"date-time"},"projectId":{"type":"string"}},"required":["_id","name","latestVersion","createdAt","projectId"]},"UpdateProfileIdentity":{"type":"object","properties":{"name":{"type":"string","minLength":1,"maxLength":128},"description":{"type":"string","maxLength":512}}},"ReportTemplateResponse":{"type":"object","properties":{"_id":{"type":"string"},"id":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"userPrompt":{"type":"string"},"systemPrompt":{"$ref":"#/components/schemas/ReportTemplateSystemPrompt"},"trigger":{"$ref":"#/components/schemas/ReportTrigger"},"model":{"type":"string"},"timeoutMs":{"type":"integer","exclusiveMinimum":0},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"deletedAt":{"type":["string","null"],"format":"date-time"},"projectId":{"type":"string"}},"required":["_id","id","name","userPrompt","createdAt","projectId"]},"ReportTemplateSystemPrompt":{"type":"object","properties":{"mode":{"type":"string","enum":["append","override"]},"content":{"type":"string"}},"required":["mode","content"]},"ReportTrigger":{"oneOf":[{"type":"object","properties":{"type":{"type":"string","enum":["always"]}},"required":["type"]},{"type":"object","properties":{"type":{"type":"string","enum":["criteria"]},"criteriaIds":{"type":"array","items":{"type":"string"}},"match":{"type":"string","enum":["any","all"]}},"required":["type","criteriaIds"]},{"type":"object","properties":{"type":{"type":"string","enum":["taskPrompt"]},"taskPromptIds":{"type":"array","items":{"type":"string"}}},"required":["type","taskPromptIds"]},{"type":"object","properties":{"type":{"type":"string","enum":["promptFeature"]},"featureIds":{"type":"array","items":{"type":"string"}},"match":{"type":"string","enum":["any","all"]}},"required":["type","featureIds"]}]},"CreateReportTemplateInput":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"userPrompt":{"type":"string"},"systemPrompt":{"$ref":"#/components/schemas/ReportTemplateSystemPrompt"},"trigger":{"$ref":"#/components/schemas/ReportTrigger"},"model":{"type":"string"},"timeoutMs":{"type":"integer","exclusiveMinimum":0}},"required":["id","name","userPrompt"]},"UpdateReportTemplateInput":{"type":"object","properties":{"name":{"type":"string"},"description":{"type":"string"},"userPrompt":{"type":"string"},"systemPrompt":{"allOf":[{"$ref":"#/components/schemas/ReportTemplateSystemPrompt"},{"type":["object","null"]}]},"trigger":{"$ref":"#/components/schemas/ReportTrigger"},"model":{"type":["string","null"]},"timeoutMs":{"type":["integer","null"],"exclusiveMinimum":0}}},"AgentResponse":{"type":"object","properties":{"_id":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"modelProvider":{"type":"string"},"supportedModels":{"type":"array","items":{"type":"string"}},"defaultModel":{"type":"string"},"available":{"type":"boolean"},"capabilities":{"$ref":"#/components/schemas/AgentCapabilities"},"versions":{"type":"array","items":{"$ref":"#/components/schemas/AgentVersion"}},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"deletedAt":{"type":["string","null"],"format":"date-time"}},"required":["_id","name","supportedModels","createdAt"]},"AgentCapabilities":{"type":"object","properties":{"supportsReasoningEffort":{"type":"boolean"},"supportsMcpServers":{"type":"boolean"},"supportsSkills":{"type":"boolean"},"supportsExtensions":{"type":"boolean"},"supportsResources":{"type":"boolean"}}},"AgentVersion":{"type":"object","properties":{"agentVersion":{"type":"string","minLength":1},"workerVersion":{"type":"string","minLength":1},"components":{"type":"object","additionalProperties":{"type":"string"}},"gitCommit":{"type":"string","minLength":1},"buildTime":{"type":"string","minLength":1},"imageTag":{"type":"string","minLength":1},"queueName":{"type":"string"},"status":{"type":"string","enum":["active","retired"]},"createdAt":{"type":["string","null"],"format":"date-time"}},"required":["agentVersion","workerVersion","components","gitCommit","buildTime","imageTag","status","createdAt"]},"CreateAgentInput":{"type":"object","properties":{"_id":{"type":"string","minLength":1},"name":{"type":"string","minLength":1},"description":{"type":"string"},"modelProvider":{"type":"string"},"supportedModels":{"type":"array","items":{"type":"string"}},"defaultModel":{"type":"string"},"available":{"type":"boolean"},"capabilities":{"$ref":"#/components/schemas/AgentCapabilities"}},"required":["_id","name"]},"UpdateAgentInput":{"type":"object","properties":{"name":{"type":"string"},"description":{"type":"string"},"modelProvider":{"type":"string"},"supportedModels":{"type":"array","items":{"type":"string"}},"defaultModel":{"type":"string"},"available":{"type":"boolean"},"capabilities":{"$ref":"#/components/schemas/AgentCapabilities"}}},"RegisterAgentVersionInput":{"type":"object","properties":{"agentVersion":{"type":"string","minLength":1},"workerVersion":{"type":"string","minLength":1},"components":{"type":"object","additionalProperties":{"type":"string"}},"gitCommit":{"type":"string","minLength":1},"buildTime":{"type":"string","minLength":1},"imageTag":{"type":"string","minLength":1},"queueName":{"type":"string","minLength":1}},"required":["agentVersion","workerVersion","components","gitCommit","buildTime","imageTag","queueName"]},"PatchAgentVersionInput":{"type":"object","properties":{"status":{"type":"string","enum":["active","retired"]}},"required":["status"]},"ModelResponse":{"type":"object","properties":{"_id":{"type":"string"},"modelId":{"type":"string"},"provider":{"type":"string"},"agentId":{"type":"string"},"firstSeenAt":{"type":["string","null"],"format":"date-time"},"lastSeenAt":{"type":["string","null"],"format":"date-time"},"disappearedAt":{"type":["string","null"],"format":"date-time"},"providerAvailableFrom":{"type":["string","null"],"format":"date-time"},"providerEndOfLife":{"type":["string","null"],"format":"date-time"},"metadata":{"type":"object","additionalProperties":{}},"capabilities":{"$ref":"#/components/schemas/ModelCapabilities"}},"required":["_id","modelId","provider","agentId","firstSeenAt","lastSeenAt"]},"ModelCapabilities":{"type":"object","properties":{"reasoningEffort":{"type":"array","items":{"type":"string"}},"toolCalls":{"type":"boolean"},"vision":{"type":"boolean"},"streaming":{"type":"boolean"},"adaptiveThinking":{"type":"boolean"},"maxThinkingBudget":{"type":"number"}}},"McpServerResponse":{"type":"object","properties":{"_id":{"type":"string"},"slug":{"type":"string"},"name":{"type":"string"},"type":{"type":"string","enum":["sse","http","stdio"]},"url":{"type":"string"},"command":{"type":"string"},"args":{"type":"array","items":{"type":"string"}},"env":{"type":"object","additionalProperties":{"type":"string"}},"headers":{"type":"array","items":{"$ref":"#/components/schemas/McpServerHeader"}},"sessionMode":{"type":"string","enum":["stateful","stateless"]},"version":{"type":"string"},"description":{"type":"string"},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"deletedAt":{"type":["string","null"],"format":"date-time"},"projectId":{"type":"string"}},"required":["_id","slug","name","type","createdAt","projectId"]},"McpServerHeader":{"type":"object","properties":{"name":{"type":"string"},"value":{"type":"string"}},"required":["name","value"]},"UpdateMcpServerInput":{"type":"object","properties":{"name":{"type":"string"},"type":{"type":"string","enum":["sse","http","stdio"]},"url":{"type":"string"},"command":{"type":"string"},"args":{"type":"array","items":{"type":"string"}},"env":{"type":"object","additionalProperties":{"type":"string"}},"headers":{"type":"array","items":{"$ref":"#/components/schemas/McpServerHeader"}},"sessionMode":{"type":"string","enum":["stateful","stateless"]},"version":{"type":"string"},"description":{"type":"string"}}},"SkillResponse":{"type":"object","properties":{"_id":{"type":"string"},"slug":{"type":"string"},"source":{"type":"string"},"skillName":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"origin":{"type":"string","enum":["skills-sh","manual"]},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"deletedAt":{"type":["string","null"],"format":"date-time"},"projectId":{"type":"string"}},"required":["_id","slug","source","skillName","name","origin","createdAt","projectId"]},"SkillSearchResult":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"source":{"type":"string"},"description":{"type":"string"},"internal":{"type":"boolean"},"installs":{"type":"number"}},"required":["id","name","source","internal"]},"SkillDiscoveryResult":{"type":"object","properties":{"skillName":{"type":"string"},"skillPath":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"existsInLibrary":{"type":"boolean"},"currentRevisionCommitSha":{"type":"string"},"latestUpstreamCommitSha":{"type":"string"},"updateAvailable":{"type":"boolean"},"lastImportedAt":{"type":"string"}},"required":["skillName","skillPath"]},"SkillRevisionResponse":{"type":"object","properties":{"_id":{"type":"string"},"ref":{"type":"string"},"source":{"type":"string"},"skillName":{"type":"string"},"skillPath":{"type":"string"},"commitHash":{"type":"string"},"commitTimestamp":{"type":["string","null"],"format":"date-time"},"name":{"type":"string"},"description":{"type":"string"},"license":{"type":"string"},"compatibility":{"type":"string"},"allowedTools":{"type":"string"},"metadata":{"type":"object","additionalProperties":{"type":"string"}},"content":{"type":"string"},"archiveUrl":{"type":"string"},"validationWarnings":{"type":"array","items":{"type":"string"}},"resolvedAt":{"type":["string","null"],"format":"date-time"},"createdAt":{"type":["string","null"],"format":"date-time"},"projectId":{"type":"string"}},"required":["_id","ref","source","skillName","skillPath","commitHash","commitTimestamp","name","description","content","archiveUrl","resolvedAt","createdAt","projectId"]},"CreateSkillInput":{"type":"object","properties":{"source":{"type":"string"},"skillName":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"origin":{"type":"string","enum":["skills-sh","manual"]}},"required":["source","skillName","name","origin"]},"CodebaseResponse":{"type":"object","properties":{"_id":{"type":"string"},"slug":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"sourceType":{"type":"string","enum":["git","archive"]},"source":{"type":"string"},"defaultBranch":{"type":"string"},"revisionCounter":{"type":"number"},"latestRevisionId":{"type":"string"},"creator":{"type":"string"},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"deletedAt":{"type":["string","null"],"format":"date-time"},"projectId":{"type":"string"}},"required":["_id","slug","name","sourceType","revisionCounter","createdAt","projectId"]},"UpdateCodebaseInput":{"type":"object","properties":{"name":{"type":"string","minLength":1},"description":{"type":"string"},"defaultBranch":{"type":"string"}}},"CodebaseRevisionResponse":{"type":"object","properties":{"_id":{"type":"string"},"codebaseId":{"type":"string"},"slug":{"type":"string"},"revisionNumber":{"type":"number"},"ref":{"type":"string"},"sourceType":{"type":"string","enum":["git","archive"]},"source":{"type":"string"},"requestedRef":{"type":"string"},"resolvedCommitSha":{"type":"string"},"commitTimestamp":{"type":["string","null"],"format":"date-time"},"originalFilename":{"type":"string"},"contentSha256":{"type":"string"},"archiveUrl":{"type":"string"},"sizeBytes":{"type":"number"},"fileCount":{"type":"number"},"creator":{"type":"string"},"resolvedAt":{"type":["string","null"],"format":"date-time"},"createdAt":{"type":["string","null"],"format":"date-time"},"deduplicated":{"type":"boolean"},"projectId":{"type":"string"}},"required":["_id","codebaseId","slug","revisionNumber","ref","sourceType","archiveUrl","resolvedAt","createdAt","projectId"]},"ResolveCodebaseRevisionInput":{"type":"object","properties":{"requestedRef":{"type":"string"},"creator":{"type":"string"}}},"ResourceResponse":{"type":"object","properties":{"_id":{"type":"string"},"slug":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"revisionCounter":{"type":"number"},"latestRevisionId":{"type":"string"},"latestRevisionNumber":{"type":"number"},"creator":{"type":"string"},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"deletedAt":{"type":["string","null"],"format":"date-time"},"projectId":{"type":"string"}},"required":["_id","slug","name","revisionCounter","createdAt","projectId"]},"CreateResourceInput":{"type":"object","properties":{"name":{"type":"string","minLength":1},"slug":{"type":"string","minLength":1},"description":{"type":"string"},"setup":{"$ref":"#/components/schemas/ResourceScript"},"teardown":{"$ref":"#/components/schemas/ResourceScript"},"exports":{"type":"array","items":{"type":"string","pattern":"^[A-Za-z_][A-Za-z0-9_]*$"}},"parameters":{"type":"array","items":{"$ref":"#/components/schemas/ResourceParameter"}},"creator":{"type":"string"}},"required":["name","setup"]},"ResourceScript":{"type":"object","properties":{"sh":{"type":"string","minLength":1}}},"ResourceParameter":{"type":"object","properties":{"name":{"type":"string","pattern":"^[A-Za-z_][A-Za-z0-9_]*$"},"description":{"type":"string"},"required":{"type":"boolean","default":false},"default":{"type":"string"},"example":{"type":"string"}},"required":["name"]},"UpdateResourceInput":{"type":"object","properties":{"name":{"type":"string","minLength":1},"description":{"type":"string"}}},"ResourceRevisionResponse":{"type":"object","properties":{"_id":{"type":"string"},"resourceId":{"type":"string"},"slug":{"type":"string"},"revisionNumber":{"type":"number"},"ref":{"type":"string"},"setup":{"$ref":"#/components/schemas/ResourceScript"},"teardown":{"$ref":"#/components/schemas/ResourceScript"},"exports":{"type":"array","items":{"type":"string"}},"parameters":{"type":"array","items":{"$ref":"#/components/schemas/ResourceParameter"}},"contentSha256":{"type":"string"},"creator":{"type":"string"},"createdAt":{"type":["string","null"],"format":"date-time"},"deduplicated":{"type":"boolean"},"projectId":{"type":"string"}},"required":["_id","resourceId","slug","revisionNumber","ref","setup","exports","contentSha256","createdAt","projectId"]},"CreateResourceRevisionInput":{"type":"object","properties":{"setup":{"$ref":"#/components/schemas/ResourceScript"},"teardown":{"$ref":"#/components/schemas/ResourceScript"},"exports":{"type":"array","items":{"type":"string","pattern":"^[A-Za-z_][A-Za-z0-9_]*$"}},"parameters":{"type":"array","items":{"$ref":"#/components/schemas/ResourceParameter"}},"creator":{"type":"string"}},"required":["setup"]},"ExtensionResponse":{"type":"object","properties":{"_id":{"type":"string"},"slug":{"type":"string"},"publisher":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"origin":{"type":"string","enum":["marketplace","manual"]},"createdAt":{"type":["string","null"],"format":"date-time"},"updatedAt":{"type":["string","null"],"format":"date-time"},"deletedAt":{"type":["string","null"],"format":"date-time"},"projectId":{"type":"string"}},"required":["_id","slug","publisher","name","origin","createdAt","projectId"]},"ExtensionSearchResult":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"publisher":{"type":"string"},"description":{"type":"string"},"internal":{"type":"boolean"},"version":{"type":"string"}},"required":["id","name","publisher","internal"]},"CreateExtensionInput":{"type":"object","properties":{"_id":{"type":"string","pattern":"^[a-zA-Z0-9-]+\\.[a-zA-Z0-9-]+$"},"publisher":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"origin":{"type":"string","enum":["marketplace","manual"]}},"required":["_id","publisher","name","origin"]},"UpdateExtensionInput":{"type":"object","properties":{"name":{"type":"string"},"description":{"type":"string"}}},"ExtensionVersionInfo":{"type":"object","properties":{"version":{"type":"string"},"preRelease":{"type":"boolean"},"lastUpdated":{"type":"string"}},"required":["version","preRelease","lastUpdated"]},"CreateInsightInput":{"type":"object","properties":{"title":{"type":"string"},"description":{"type":"string"},"category":{"type":"string"},"tags":{"type":"array","items":{"type":"string"}},"createdBy":{"type":"string","enum":["agent","user"]},"sourceReportId":{"type":"string"}},"required":["title","description"]},"UpdateInsightInput":{"type":"object","properties":{"title":{"type":"string"},"description":{"type":"string"},"category":{"type":"string"},"tags":{"type":"array","items":{"type":"string"}}}},"FeatureFlagResponse":{"type":"object","properties":{"key":{"type":"string"},"label":{"type":"string"},"enabled":{"type":"boolean"},"updatedAt":{"type":["string","null"],"format":"date-time"}},"required":["key","label","enabled","updatedAt"]},"UpdateFeatureFlagInput":{"type":"object","properties":{"enabled":{"type":"boolean"}},"required":["enabled"]}},"parameters":{}},"paths":{"/api/v1/keys/preview":{"post":{"tags":["Keys"],"summary":"Preview key","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/KeyInput"}}}},"responses":{"200":{"description":"Key preview","content":{"application/json":{"schema":{"$ref":"#/components/schemas/KeyResponse"}}}}}}},"/api/v1/keys":{"post":{"tags":["Keys"],"summary":"Create key","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/KeyInput"}}}},"responses":{"201":{"description":"Key created","content":{"application/json":{"schema":{"$ref":"#/components/schemas/KeyResponse"}}}}}},"get":{"tags":["Keys"],"summary":"List keys","responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/KeyResponse"}}}}}}}},"/api/v1/keys/{id}":{"get":{"tags":["Keys"],"summary":"Get key","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/KeyResponse"}}}}}},"put":{"tags":["Keys"],"summary":"Update key","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/KeyInput"}}}},"responses":{"200":{"description":"Key updated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/KeyResponse"}}}}}},"delete":{"tags":["Keys"],"summary":"Delete key","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Key deleted","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"}},"required":["success"]}}}}}}},"/api/v1/keys/{id}/validate":{"post":{"tags":["Keys"],"summary":"Validate key","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidateKeyInput"}}}},"responses":{"200":{"description":"Validation result","content":{"application/json":{"schema":{"type":"object","properties":{},"additionalProperties":{},"description":"Key validation result"}}}}}}},"/api/v1/accounts":{"post":{"tags":["Accounts"],"summary":"Create account","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AccountInput"}}}},"responses":{"201":{"description":"Account created","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AccountResponse"}}}}}},"get":{"tags":["Accounts"],"summary":"List accounts","responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/AccountResponse"}}}}}}}},"/api/v1/accounts/{id}":{"get":{"tags":["Accounts"],"summary":"Get account","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AccountResponse"}}}}}},"put":{"tags":["Accounts"],"summary":"Update account","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AccountInput"}}}},"responses":{"200":{"description":"Account updated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AccountResponse"}}}}}},"delete":{"tags":["Accounts"],"summary":"Delete account","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Account deleted","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"}},"required":["success"]}}}}}}},"/api/v1/users/me":{"get":{"tags":["Users"],"summary":"Get the authenticated user's identity","description":"Read the existing authenticated Scope identity without enrollment or profile writes. Responses must not be HTTP-cached.","security":[{"bearerAuth":[]}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserMeResponse"}}}},"401":{"description":"Not authenticated"},"403":{"description":"User is not enrolled or is disabled"},"503":{"description":"Authentication service unavailable"}}},"post":{"tags":["Users"],"summary":"Enroll the authenticated user","description":"JIT-enroll the authenticated user, refresh their profile and lastLoginAt, apply bootstrap-admin rules, and warm the access cache. Use this only after an explicit IdP login; do not prefetch, poll, or automatically retry transient failures.","security":[{"bearerAuth":[]}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserMeResponse"}}}},"401":{"description":"Not authenticated"},"403":{"description":"User is disabled"},"503":{"description":"Authentication service unavailable"}}}},"/health":{"get":{"tags":["Health"],"summary":"Liveness probe","responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"status":{"type":"string"},"version":{"type":"string"}},"required":["status","version"]}}}}}}},"/ready":{"get":{"tags":["Health"],"summary":"Readiness probe","responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"status":{"type":"string"},"migrations":{}},"required":["status"]}}}},"503":{"description":"Service is not ready"}}}},"/about":{"get":{"tags":["System"],"summary":"API metadata","responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string"},"version":{"type":"string"},"buildTime":{"type":"string"},"environment":{"type":"string"},"description":{"type":"string"},"workers":{"type":"array","items":{"type":"string"}}},"required":["name","version","buildTime","environment","description","workers"]}}}}}}},"/api/v1/version":{"get":{"tags":["System"],"summary":"Version info","responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"commit":{"type":"string"},"buildTime":{"type":"string"},"environment":{"type":"string"},"strictAgentCapabilities":{"type":"boolean"}},"required":["commit","buildTime","environment","strictAgentCapabilities"]}}}}}}},"/api/v1/projects":{"get":{"tags":["Projects"],"summary":"List all projects","parameters":[{"schema":{"type":"string","enum":["true","false"],"description":"When true, include soft-deleted projects in the result"},"required":false,"description":"When true, include soft-deleted projects in the result","name":"includeDeleted","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ProjectResponse"}}}}}}},"post":{"tags":["Projects"],"summary":"Create a project","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateProjectInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProjectResponse"}}}},"400":{"description":"Invalid input"}}}},"/api/v1/projects/{id}":{"get":{"tags":["Projects"],"summary":"Get a project","responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProjectResponse"}}}},"404":{"description":"Project not found"}}},"patch":{"tags":["Projects"],"summary":"Update a project","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateProjectInput"}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProjectResponse"}}}},"404":{"description":"Project not found"}}},"delete":{"tags":["Projects"],"summary":"Soft-delete a project","responses":{"204":{"description":"Success"},"404":{"description":"Project not found"}}}},"/api/v1/projects/{id}/restore":{"post":{"tags":["Projects"],"summary":"Restore a soft-deleted project","responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProjectResponse"}}}},"404":{"description":"Project not found"}}}},"/api/v1/submissions":{"get":{"tags":["Submissions"],"summary":"List submissions","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"},{"schema":{"type":"integer","minimum":1,"maximum":100,"default":50},"required":false,"name":"limit","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SubmissionListResponse"}}}}}}},"/api/v1/submissions/{id}":{"get":{"tags":["Submissions"],"summary":"Get a submission","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SubmissionResponse"}}}},"404":{"description":"Submission not found"}}}},"/api/v1/submissions/{id}/runs":{"get":{"tags":["Submissions"],"summary":"List current and historical submission attempts","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"runs":{"type":"array","items":{"$ref":"#/components/schemas/SubmissionRunResponse"}}},"required":["runs"]}}}},"404":{"description":"Submission not found"}}}},"/api/v1/submissions/{id}/runs/{submissionRunId}":{"get":{"tags":["Submissions"],"summary":"Get one submission attempt","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":true,"name":"submissionRunId","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SubmissionRunResponse"}}}},"404":{"description":"Submission attempt not found"}}}},"/api/v1/submissions/{id}/retry":{"post":{"tags":["Submissions"],"summary":"Retry current submission processing","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"submissionRunId":{"type":"string"}},"required":["submissionRunId"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SubmissionRetryResponse"}}}},"404":{"description":"Submission not found"},"409":{"description":"Submission attempt is stale or dependencies are blocked"}}}},"/api/v1/requests":{"post":{"tags":["Requests"],"summary":"Submit request(s)","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/CreateRequestInput"},{"type":"object","properties":{"count":{"type":"number","minimum":1,"maximum":10,"default":1},"skills":{"type":"array","items":{"type":"string"}},"agentVersion":{"type":"string"},"codebase":{"type":"string"}}}]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"anyOf":[{"$ref":"#/components/schemas/RequestResponse"},{"type":"array","items":{"$ref":"#/components/schemas/RequestResponse"}}]}}}}}},"get":{"tags":["Requests"],"summary":"List requests","parameters":[{"schema":{"anyOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]},"required":false,"name":"worker","in":"query"},{"schema":{"type":"string"},"required":false,"name":"taskPromptId","in":"query"},{"schema":{"type":"string"},"required":false,"name":"criteria","in":"query"},{"schema":{"type":"string"},"required":false,"name":"submissionId","in":"query"},{"schema":{"anyOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]},"required":false,"name":"profileId","in":"query"},{"schema":{"anyOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]},"required":false,"name":"status","in":"query"},{"schema":{"anyOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]},"required":false,"name":"outcome","in":"query"},{"schema":{"anyOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]},"required":false,"name":"model","in":"query"},{"schema":{"anyOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]},"required":false,"name":"os","in":"query"},{"schema":{"anyOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]},"required":false,"name":"priority","in":"query"},{"schema":{"anyOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]},"required":false,"name":"agentVersion","in":"query"},{"schema":{"type":"string"},"required":false,"name":"search","in":"query"},{"schema":{"type":"string","enum":["task","submissionId","profile"]},"required":false,"name":"groupBy","in":"query"},{"schema":{"type":"integer","minimum":1,"maximum":100},"required":false,"name":"limit","in":"query"},{"schema":{"type":"string"},"required":false,"name":"after","in":"query"},{"schema":{"type":"string"},"required":false,"name":"before","in":"query"},{"schema":{"type":"string","enum":["true","false"]},"required":false,"name":"last","in":"query"},{"schema":{"type":"string","enum":["created","updated","priority","worker","status","id","duration","createdAt"]},"required":false,"name":"sortBy","in":"query"},{"schema":{"type":"string","enum":["asc","desc"]},"required":false,"name":"sortDir","in":"query"},{"schema":{"type":["string","null"],"format":"date-time"},"required":false,"name":"createdAfter","in":"query"},{"schema":{"type":["string","null"],"format":"date-time"},"required":false,"name":"createdBefore","in":"query"},{"schema":{"type":["integer","null"],"minimum":0},"required":false,"name":"turns","in":"query"},{"schema":{"type":"string","enum":["eq","gte","lte"]},"required":false,"name":"turnsOp","in":"query"},{"schema":{"type":["integer","null"],"minimum":0},"required":false,"name":"maxIterations","in":"query"},{"schema":{"type":"string","enum":["eq","gte","lte"]},"required":false,"name":"maxIterationsOp","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"anyOf":[{"$ref":"#/components/schemas/PaginatedRunsResponse"},{"$ref":"#/components/schemas/PaginatedRunGroupsResponse"}]}}}}}}},"/api/v1/requests/facets":{"get":{"tags":["Requests"],"summary":"List run filter facets","description":"Returns every distinct value and its full-dataset count per categorical filter dimension for the Runs list rail. Counts are absolute over all non-deleted runs **in the given project**: they intentionally ignore the active search, date range, iteration, and categorical selections so every selectable value stays visible with a stable count. Requires ?projectId=. Computed with parallel $group aggregations (Cosmos has no $facet) and cached per-project for a short TTL.","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RunFacetsResponse"}}}}}}},"/api/v1/requests/{id}":{"get":{"tags":["Requests"],"summary":"Get request","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RequestResponse"}}}},"404":{"description":"Not found"}}},"delete":{"tags":["Requests"],"summary":"Soft-delete request","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string"}},"required":["message"]}}}},"404":{"description":"Not found"}}}},"/api/v1/analysis":{"get":{"tags":["Requests"],"summary":"Compute pass@k / success@T metrics","description":"Aggregates pass@k / success@T metrics over a single project's done runs. Requires ?projectId=.","parameters":[{"schema":{"type":"string"},"required":false,"name":"worker","in":"query"},{"schema":{"type":"string"},"required":false,"name":"taskPromptId","in":"query"},{"schema":{"type":"string"},"required":false,"name":"criteria","in":"query"},{"schema":{"type":"string"},"required":false,"name":"features","in":"query"},{"schema":{"type":"string"},"required":false,"name":"submissionId","in":"query"},{"schema":{"type":"string"},"required":false,"name":"k","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{},"additionalProperties":{},"description":"Analysis metrics"}}}}}}},"/api/v1/requests/bulk-resubmit":{"post":{"tags":["Requests"],"summary":"Bulk resubmit requests","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BulkResubmitInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/RequestResponse"}}}}}}}},"/api/v1/requests/bulk":{"delete":{"tags":["Requests"],"summary":"Bulk soft-delete requests","requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"ids":{"type":"array","items":{"type":"string"}}},"required":["ids"]}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"deleted":{"type":"number"}},"required":["deleted"]}}}}}}},"/api/v1/requests/archive":{"post":{"tags":["Requests"],"summary":"Download batch archive of multiple runs","requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"ids":{"type":"array","items":{"type":"string"},"minItems":1,"maxItems":100}},"required":["ids"]}}}},"responses":{"201":{"description":"Gzipped batch archive containing individual run archives"},"400":{"description":"Invalid input"},"404":{"description":"One or more runs not found"}}}},"/api/v1/runs/upload":{"post":{"tags":["Requests"],"summary":"Import run archive","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"201":{"description":"Success"}}}},"/api/v1/runs/upload-batch":{"post":{"tags":["Requests"],"summary":"Import batch run archive","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"207":{"description":"Multi-status: 201 if all runs imported, 400 if none imported, 207 if partial"},"400":{"description":"No archive uploaded, empty archive, or all runs failed"}}}},"/api/v1/requests/{id}/reports":{"get":{"tags":["Reports"],"summary":"Get reports for request","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ReportResponse"}}}}},"404":{"description":"Run not found"}}}},"/api/v1/requests/{id}/runs":{"get":{"tags":["Requests"],"summary":"List attempts for a request","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/RunState"}}}}},"404":{"description":"Request not found"}}}},"/api/v1/requests/{id}/runs/{runId}":{"get":{"tags":["Requests"],"summary":"Get a single attempt","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":true,"name":"runId","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RunState"}}}},"404":{"description":"Request or run not found"}}}},"/api/v1/requests/bulk-retry":{"post":{"tags":["Requests"],"summary":"Bulk retry requests (start new attempts)","requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"ids":{"type":"array","items":{"type":"string"},"minItems":1},"force":{"type":"boolean"}},"required":["ids"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"retried":{"type":"integer"},"skipped":{"type":"integer"},"results":{"type":"array","items":{"type":"object","properties":{"requestId":{"type":"string"},"runId":{"type":"string"},"attemptNumber":{"type":"integer"},"error":{"type":"string"}},"required":["requestId"]}}},"required":["retried","skipped","results"]}}}}}}},"/api/v1/requests/{id}/retry":{"post":{"tags":["Requests"],"summary":"Retry a request (start a new attempt)","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"force":{"type":"boolean"}}}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"requestId":{"type":"string"},"runId":{"type":"string"},"attemptNumber":{"type":"integer"}},"required":["requestId","runId","attemptNumber"]}}}},"404":{"description":"Request not found"},"409":{"description":"Conflict — request is not in a retryable state, or a concurrent retry won the race"},"422":{"description":"Cannot retry — current run not yet terminal"}}}},"/api/v1/requests/{id}/priority":{"post":{"tags":["Requests"],"summary":"Set priority on a single request","requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"priority":{"type":"integer"}},"required":["priority"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"priority":{"type":"number"}},"required":["id","priority"]}}}}}}},"/api/v1/requests/bulk-priority":{"post":{"tags":["Requests"],"summary":"Set priority on multiple requests","requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"ids":{"type":"array","items":{"type":"string"},"minItems":1,"maxItems":100},"priority":{"type":"integer"}},"required":["ids","priority"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"updated":{"type":"number"},"skipped":{"type":"number"}},"required":["updated","skipped"]}}}}}}},"/api/v1/requests/{id}/pause":{"post":{"tags":["Requests"],"summary":"Pause a single request","responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"status":{"type":"string"}},"required":["id","status"]}}}}}}},"/api/v1/requests/{id}/resume":{"post":{"tags":["Requests"],"summary":"Resume a paused request","responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"status":{"type":"string"}},"required":["id","status"]}}}}}}},"/api/v1/requests/bulk-pause":{"post":{"tags":["Requests"],"summary":"Pause multiple requests","requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"ids":{"type":"array","items":{"type":"string"},"minItems":1,"maxItems":100}},"required":["ids"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"updated":{"type":"number"},"skipped":{"type":"number"}},"required":["updated","skipped"]}}}}}}},"/api/v1/requests/bulk-resume":{"post":{"tags":["Requests"],"summary":"Resume multiple paused requests","requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"ids":{"type":"array","items":{"type":"string"},"minItems":1,"maxItems":100}},"required":["ids"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"updated":{"type":"number"},"skipped":{"type":"number"}},"required":["updated","skipped"]}}}}}}},"/api/v1/requests/{id}/cancel":{"post":{"tags":["Requests"],"summary":"Cancel a request (marks as done/failed and signals worker to exit)","responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"previousStatus":{"type":"string"},"status":{"type":"string"},"outcome":{"type":"string"}},"required":["id","previousStatus","status","outcome"]}}}}}}},"/api/v1/requests/bulk-cancel":{"post":{"tags":["Requests"],"summary":"Cancel multiple requests","requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"ids":{"type":"array","items":{"type":"string"},"minItems":1,"maxItems":100}},"required":["ids"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"cancelled":{"type":"number"},"skipped":{"type":"number"},"results":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"cancelled":{"type":"boolean"},"previousStatus":{"type":"string"},"error":{"type":"string"}},"required":["id","cancelled"]}}},"required":["cancelled","skipped","results"]}}}}}}},"/api/v1/requests/{id}/logs":{"get":{"tags":["Requests"],"summary":"Stream request logs (SSE)","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Server-sent event stream of log entries"},"404":{"description":"Not found"}}}},"/api/v1/requests/{id}/runs/{runId}/logs":{"get":{"tags":["Requests"],"summary":"Stream logs for a specific attempt (SSE)","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":true,"name":"runId","in":"path"}],"responses":{"200":{"description":"Server-sent event stream of log entries"},"404":{"description":"Not found"}}}},"/api/v1/requests/{id}/har":{"get":{"tags":["Requests"],"summary":"Download HAR file","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"HAR-format JSON file"},"404":{"description":"Not found"}}}},"/api/v1/requests/{id}/runs/{runId}/har":{"get":{"tags":["Requests"],"summary":"Download HAR file for a specific attempt","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":true,"name":"runId","in":"path"}],"responses":{"200":{"description":"HAR-format JSON file"},"404":{"description":"Not found"}}}},"/api/v1/requests/{id}/atif":{"get":{"tags":["Requests"],"summary":"Download ATIF trajectory file for a specific iteration","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","description":"The iteration number (1-based)"},"required":true,"description":"The iteration number (1-based)","name":"iteration","in":"query"}],"responses":{"200":{"description":"ATIF v1.7 trajectory JSON file"},"400":{"description":"Missing or invalid iteration"},"404":{"description":"Not found"}}}},"/api/v1/requests/{id}/runs/{runId}/atif":{"get":{"tags":["Requests"],"summary":"Download ATIF trajectory file for a specific attempt and iteration","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":true,"name":"runId","in":"path"},{"schema":{"type":"string","description":"The iteration number (1-based)"},"required":true,"description":"The iteration number (1-based)","name":"iteration","in":"query"}],"responses":{"200":{"description":"ATIF v1.7 trajectory JSON file"},"400":{"description":"Missing or invalid iteration"},"404":{"description":"Not found"}}}},"/api/v1/requests/{id}/video":{"get":{"tags":["Requests"],"summary":"Download session recording","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"WebM video recording (supports Range requests)"},"404":{"description":"Not found"}}}},"/api/v1/requests/{id}/runs/{runId}/video":{"get":{"tags":["Requests"],"summary":"Download session recording for a specific attempt","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":true,"name":"runId","in":"path"}],"responses":{"200":{"description":"WebM video recording (supports Range requests)"},"404":{"description":"Not found"}}}},"/api/v1/requests/{id}/tool-calls":{"get":{"tags":["Requests"],"summary":"Download per-iteration tool-calls JSONL","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"JSONL stream — one ToolCall per line"},"404":{"description":"Not found"}}}},"/api/v1/requests/{id}/runs/{runId}/tool-calls":{"get":{"tags":["Requests"],"summary":"Download per-iteration tool-calls JSONL for a specific attempt","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":true,"name":"runId","in":"path"}],"responses":{"200":{"description":"JSONL stream — one ToolCall per line"},"404":{"description":"Not found"}}}},"/api/v1/requests/{id}/snapshots/{iteration}":{"get":{"tags":["Requests"],"summary":"Download iteration snapshot","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":true,"name":"iteration","in":"path"}],"responses":{"200":{"description":"Gzipped snapshot archive"},"404":{"description":"Not found"}}}},"/api/v1/requests/{id}/runs/{runId}/snapshots/{iteration}":{"get":{"tags":["Requests"],"summary":"Download iteration snapshot for a specific attempt","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":true,"name":"runId","in":"path"},{"schema":{"type":"string"},"required":true,"name":"iteration","in":"path"}],"responses":{"200":{"description":"Gzipped snapshot archive"},"404":{"description":"Not found"}}}},"/api/v1/requests/{id}/archive":{"get":{"tags":["Requests"],"summary":"Download full run archive","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Gzipped run archive"},"404":{"description":"Not found"}}}},"/api/v1/requests/{id}/runs/{runId}/archive":{"get":{"tags":["Requests"],"summary":"Download full run archive for a specific attempt","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":true,"name":"runId","in":"path"}],"responses":{"200":{"description":"Gzipped run archive"},"404":{"description":"Not found"}}}},"/api/v1/criteria/generate-prompt":{"post":{"tags":["Criteria"],"summary":"Generate criterion prompt from behavior","parameters":[{"schema":{"type":"string","minLength":1,"description":"Optional project scope. When provided, a slug/id is resolved within that project (slugs may repeat across projects); when omitted, resolution falls back to a legacy global lookup for backward compatibility.","example":"00000000-0000-0000-0000-000000000000"},"required":false,"description":"Optional project scope. When provided, a slug/id is resolved within that project (slugs may repeat across projects); when omitted, resolution falls back to a legacy global lookup for backward compatibility.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"behavior":{"type":"string"},"currentId":{"type":"string"},"gates":{"type":"array","items":{"type":"string"}}},"required":["behavior"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"prompt":{"type":"string"},"suggestedId":{"type":"string"},"suggestedParents":{"type":"array","items":{"type":"string"}},"suggestedChildren":{"type":"array","items":{"type":"string"}}},"required":["prompt","suggestedId","suggestedParents","suggestedChildren"]}}}},"400":{"description":"Empty behavior string"},"503":{"description":"LLM not configured"}}}},"/api/v1/criteria/seed":{"post":{"tags":["Criteria"],"summary":"Seed criteria in bulk","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"criteria":{"type":"array","items":{"$ref":"#/components/schemas/CreateCriteriaInput"}}},"required":["criteria"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"seeded":{"type":"number"},"errors":{"type":"array","items":{"type":"string"}}},"required":["seeded","errors"]}}}},"400":{"description":"Seed batch would introduce a dependency cycle"}}}},"/api/v1/criteria":{"get":{"tags":["Criteria"],"summary":"List criteria","parameters":[{"schema":{"type":"string"},"required":false,"name":"q","in":"query"},{"schema":{"type":"string","description":"Comma-separated criterion IDs to include"},"required":false,"description":"Comma-separated criterion IDs to include","name":"ids","in":"query"},{"schema":{"type":"string","enum":["true","false"],"description":"When true and ids is set, also include dependency ancestors"},"required":false,"description":"When true and ids is set, also include dependency ancestors","name":"ancestors","in":"query"},{"schema":{"type":"string","enum":["gate","observation"],"description":"Filter by criterion kind"},"required":false,"description":"Filter by criterion kind","name":"kind","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/CriteriaResponse"}}}}}}},"post":{"tags":["Criteria"],"summary":"Create criterion","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateCriteriaInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CriteriaResponse"}}}},"409":{"description":"Criterion already exists"}}}},"/api/v1/criteria/mdp":{"get":{"tags":["Criteria"],"summary":"Compute MDP transitions","parameters":[{"schema":{"type":"string"},"required":false,"name":"criteria","in":"query"},{"schema":{"type":"string"},"required":false,"name":"features","in":"query"},{"schema":{"type":"string"},"required":false,"name":"since","in":"query"},{"schema":{"type":"string"},"required":false,"name":"worker","in":"query"},{"schema":{"type":"string"},"required":false,"name":"taskPromptId","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{},"additionalProperties":{}}}}}}}},"/api/v1/criteria/graph":{"get":{"tags":["Criteria"],"summary":"Get criteria DAG","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CriteriaGraph"}}}}}}},"/api/v1/criteria/{id}":{"get":{"tags":["Criteria"],"summary":"Get criterion","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CriteriaResponse"}}}},"404":{"description":"Criterion not found"}}},"put":{"tags":["Criteria"],"summary":"Update criterion","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateCriteriaInput"}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CriteriaResponse"}}}},"400":{"description":"Invalid dependency reference or self-reference"},"404":{"description":"Criterion not found"}}},"delete":{"tags":["Criteria"],"summary":"Soft-delete criterion","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"deleted":{"type":"boolean"}},"required":["id","deleted"]}}}},"404":{"description":"Criterion not found"},"409":{"description":"Criterion has dependents"}}}},"/api/v1/prompt-features/generate-prompt":{"post":{"tags":["Prompt Features"],"summary":"Generate prompt feature from behavior","parameters":[{"schema":{"type":"string","minLength":1,"description":"Optional project scope. When provided, a slug/id is resolved within that project (slugs may repeat across projects); when omitted, resolution falls back to a legacy global lookup for backward compatibility.","example":"00000000-0000-0000-0000-000000000000"},"required":false,"description":"Optional project scope. When provided, a slug/id is resolved within that project (slugs may repeat across projects); when omitted, resolution falls back to a legacy global lookup for backward compatibility.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"behavior":{"type":"string"},"currentId":{"type":"string"}},"required":["behavior"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"prompt":{"type":"string"}},"required":["prompt"]}}}},"400":{"description":"Empty behavior string"},"503":{"description":"LLM not configured"}}}},"/api/v1/prompt-features/seed":{"post":{"tags":["Prompt Features"],"summary":"Seed prompt features in bulk","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"features":{"type":"array","items":{"$ref":"#/components/schemas/CreatePromptFeatureInput"}}},"required":["features"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"seeded":{"type":"number"},"errors":{"type":"array","items":{"type":"string"}}},"required":["seeded","errors"]}}}}}}},"/api/v1/prompt-features/extract-from-text":{"post":{"tags":["Prompt Features"],"summary":"Extract features from text","parameters":[{"schema":{"type":"string","minLength":1,"description":"Optional project scope. When provided, a slug/id is resolved within that project (slugs may repeat across projects); when omitted, resolution falls back to a legacy global lookup for backward compatibility.","example":"00000000-0000-0000-0000-000000000000"},"required":false,"description":"Optional project scope. When provided, a slug/id is resolved within that project (slugs may repeat across projects); when omitted, resolution falls back to a legacy global lookup for backward compatibility.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"text":{"type":"string"},"model":{"type":"string"},"type":{"type":"string","enum":["select","agents.md"]}},"required":["text"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"features":{"type":"array","items":{"$ref":"#/components/schemas/PromptFeatureResult"}},"suggestedFeatures":{"type":"array","items":{"$ref":"#/components/schemas/SuggestedPromptFeature"}},"cached":{"type":"boolean"}},"required":["features","cached"]}}}},"400":{"description":"Empty text string"},"503":{"description":"LLM not configured"}}}},"/api/v1/prompt-features":{"get":{"tags":["Prompt Features"],"summary":"List features","parameters":[{"schema":{"type":"string"},"required":false,"name":"q","in":"query"},{"schema":{"type":"string","enum":["select","agents.md"]},"required":false,"name":"type","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/PromptFeatureResponse"}}}}}}},"post":{"tags":["Prompt Features"],"summary":"Create feature","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreatePromptFeatureInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PromptFeatureResponse"}}}},"400":{"description":"Invalid input"},"409":{"description":"Feature already exists"}}}},"/api/v1/prompt-features/{id}":{"get":{"tags":["Prompt Features"],"summary":"Get feature","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PromptFeatureResponse"}}}},"404":{"description":"Feature not found"}}},"put":{"tags":["Prompt Features"],"summary":"Update feature","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdatePromptFeatureInput"}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PromptFeatureResponse"}}}},"400":{"description":"Invalid input"},"404":{"description":"Feature not found"}}},"delete":{"tags":["Prompt Features"],"summary":"Soft-delete feature","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"deleted":{"type":"boolean"}},"required":["id","deleted"]}}}},"404":{"description":"Feature not found"}}}},"/api/v1/task-prompts/generate":{"post":{"tags":["Task Prompts"],"summary":"Generate task prompts","requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"description":{"type":"string"},"existingPrompt":{"type":"string"}}}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"tasks":{"type":"array","items":{"type":"string"}}},"required":["tasks"]}}}},"503":{"description":"LLM not configured"}}}},"/api/v1/task-prompts":{"get":{"tags":["Task Prompts"],"summary":"List task prompts","parameters":[{"schema":{"type":["number","null"]},"required":false,"name":"limit","in":"query"},{"schema":{"type":["number","null"]},"required":false,"name":"offset","in":"query"},{"schema":{"type":"string"},"required":false,"name":"search","in":"query"},{"schema":{"$ref":"#/components/schemas/PromptType"},"required":false,"name":"type","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"items":{"type":"array","items":{"$ref":"#/components/schemas/TaskPromptResponse"}},"total":{"type":"number"},"limit":{"type":"number"},"offset":{"type":"number"}},"required":["items","total","limit","offset"]}}}}}},"post":{"tags":["Task Prompts"],"summary":"Create or find task prompt","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateTaskPromptInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/TaskPromptResponse"}}}},"400":{"description":"Empty text string"}}}},"/api/v1/task-prompts/{id}":{"get":{"tags":["Task Prompts"],"summary":"Get task prompt","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/TaskPromptResponse"}}}},"404":{"description":"Task prompt not found"}}},"delete":{"tags":["Task Prompts"],"summary":"Soft-delete task prompt","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"deleted":{"type":"boolean"}},"required":["deleted"]}}}},"404":{"description":"Task prompt not found"}}}},"/api/v1/task-prompts/{id}/content":{"get":{"tags":["Task Prompts"],"summary":"Get resolved task prompt content","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"text":{"type":"string"}},"required":["id","text"]}}}},"404":{"description":"Task prompt not found"}}}},"/api/v1/task-prompts/{id}/extract-features":{"post":{"tags":["Task Prompts"],"summary":"Extract features from task prompt","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":false,"name":"force","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"model":{"type":"string"}}}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"taskPromptId":{"type":"string"},"features":{"type":"array","items":{"$ref":"#/components/schemas/PromptFeatureResult"}},"featuresExtractedAt":{"type":["string","null"],"format":"date-time"},"suggestedFeatures":{"type":"array","items":{"$ref":"#/components/schemas/SuggestedPromptFeature"}},"cached":{"type":"boolean"}},"required":["taskPromptId","features","cached"]}}}},"404":{"description":"Task prompt not found"},"503":{"description":"LLM not configured"}}}},"/api/v1/task-prompts/{id}/features/{featureId}":{"patch":{"tags":["Task Prompts"],"summary":"Toggle feature flag on task prompt","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":true,"name":"featureId","in":"path"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PatchTaskPromptFeatureInput"}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/TaskPromptResponse"}}}},"400":{"description":"Invalid detected value"},"404":{"description":"Task prompt or feature not found"}}}},"/api/v1/reports":{"post":{"tags":["Reports"],"summary":"Create report","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateReportInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportResponse"}}}},"400":{"description":"Invalid input"},"404":{"description":"Run or template not found"}}},"get":{"tags":["Reports"],"summary":"List reports","parameters":[{"schema":{"type":"string"},"required":false,"name":"requestId","in":"query"},{"schema":{"type":"string"},"required":false,"name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ReportResponse"}}}}}}}},"/api/v1/reports/bulk-create":{"post":{"tags":["Reports"],"summary":"Bulk create reports","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BulkCreateReportsInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ReportResponse"}}}}},"400":{"description":"Invalid input"}}}},"/api/v1/reports/bulk-status":{"post":{"tags":["Reports"],"summary":"Bulk get report statuses","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BulkReportStatusInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ReportResponse"}}}}},"400":{"description":"Invalid input"}}}},"/api/v1/reports/bulk-summary":{"post":{"tags":["Reports"],"summary":"Bulk get report summary per run","description":"Returns aggregated report status counts per run. Only the latest report per template is counted (re-triggers are deduplicated).","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BulkReportSummaryInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/BulkReportSummaryResponse"}}}},"400":{"description":"Invalid input"}}}},"/api/v1/reports/{id}":{"get":{"tags":["Reports"],"summary":"Get report","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportResponse"}}}},"404":{"description":"Report not found"}}}},"/api/v1/reports/{id}/logs":{"get":{"tags":["Reports"],"summary":"Stream report logs (SSE)","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Server-sent event stream of log entries"},"404":{"description":"Report not found"}}}},"/api/v1/reports/trigger":{"post":{"tags":["Reports"],"summary":"Trigger reports","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TriggerReportsInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"triggered":{"type":"number"},"reports":{"type":"array","items":{"$ref":"#/components/schemas/ReportResponse"}}},"required":["triggered","reports"]}}}},"400":{"description":"Invalid input"},"404":{"description":"Run not found"}}}},"/api/v1/reports/bulk-trigger":{"post":{"tags":["Reports"],"summary":"Bulk trigger reports","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BulkTriggerReportsInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"type":"object","properties":{},"additionalProperties":{}}}}}},"400":{"description":"Invalid input"}}}},"/api/v1/reports/{id}/insights":{"get":{"tags":["Reports"],"summary":"Get insights for report","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"allOf":[{"$ref":"#/components/schemas/InsightResponse"},{"type":"object","properties":{"referencedAt":{"type":["string","null"],"format":"date-time"},"isNew":{"type":"boolean"}}}]}}}}},"404":{"description":"Report not found"}}},"post":{"tags":["Reports"],"summary":"Link insight to report","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"insightId":{"type":"string"},"isNew":{"type":"boolean"}},"required":["insightId"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"insightId":{"type":"string"},"referencedAt":{"type":["string","null"],"format":"date-time"},"isNew":{"type":"boolean"}},"required":["insightId","referencedAt","isNew"]}}}},"404":{"description":"Report or insight not found"},"409":{"description":"Insight already referenced by this report"}}}},"/api/v1/profiles":{"post":{"tags":["Profiles"],"summary":"Create a new profile","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateProfileInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProfileWithVersionResponse"}}}}}},"get":{"tags":["Profiles"],"summary":"List profiles","parameters":[{"schema":{"type":"string"},"required":false,"name":"workerType","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ProfileWithVersionResponse"}}}}}}}},"/api/v1/profiles/{profileId}":{"get":{"tags":["Profiles"],"summary":"Get profile with latest version","parameters":[{"schema":{"type":"string"},"required":true,"name":"profileId","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProfileWithVersionResponse"}}}}}},"post":{"tags":["Profiles"],"summary":"Create new profile version","parameters":[{"schema":{"type":"string"},"required":true,"name":"profileId","in":"path"}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"workerType":{"type":"string"},"model":{"type":"string"},"reasoningEffort":{"type":"string"},"agentVersion":{"type":"string"},"mcpServers":{"type":"array","items":{"type":"string"}},"skillRevisions":{"type":"array","items":{"type":"string"}},"resources":{"type":"array","items":{"$ref":"#/components/schemas/ResourceBindingSpec"}},"extensions":{"type":"array","items":{"type":"string"}}},"required":["workerType","model"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProfileVersionResponse"}}}}}},"put":{"tags":["Profiles"],"summary":"Update profile identity","parameters":[{"schema":{"type":"string"},"required":true,"name":"profileId","in":"path"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateProfileIdentity"}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProfileResponse"}}}}}},"delete":{"tags":["Profiles"],"summary":"Delete profile","parameters":[{"schema":{"type":"string"},"required":true,"name":"profileId","in":"path"}],"responses":{"204":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string"}},"required":["message"]}}}}}}},"/api/v1/profiles/{profileId}/versions":{"get":{"tags":["Profiles"],"summary":"List profile versions","parameters":[{"schema":{"type":"string"},"required":true,"name":"profileId","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ProfileVersionResponse"}}}}}}}},"/api/v1/profiles/{profileId}/versions/{version}":{"get":{"tags":["Profiles"],"summary":"Get profile version","parameters":[{"schema":{"type":"string"},"required":true,"name":"profileId","in":"path"},{"schema":{"type":["number","null"]},"required":false,"name":"version","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProfileVersionResponse"}}}}}}},"/api/v1/report-templates/default-system-prompt":{"get":{"tags":["Report Templates"],"summary":"Get default system prompt","responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"content":{"type":"string"}},"required":["content"]}}}}}}},"/api/v1/report-templates/available-models":{"get":{"tags":["Report Templates"],"summary":"List models available for report generation","responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"type":"object","properties":{"modelId":{"type":"string"}},"required":["modelId"]}}}}}}}},"/api/v1/report-templates":{"get":{"tags":["Report Templates"],"summary":"List report templates","parameters":[{"schema":{"type":"string"},"required":false,"name":"q","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ReportTemplateResponse"}}}}}}},"post":{"tags":["Report Templates"],"summary":"Create report template","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateReportTemplateInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportTemplateResponse"}}}},"409":{"description":"Report template already exists"}}}},"/api/v1/report-templates/{id}":{"get":{"tags":["Report Templates"],"summary":"Get report template","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportTemplateResponse"}}}},"404":{"description":"Report template not found"}}},"put":{"tags":["Report Templates"],"summary":"Update report template","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateReportTemplateInput"}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportTemplateResponse"}}}},"404":{"description":"Report template not found"}}},"delete":{"tags":["Report Templates"],"summary":"Delete report template","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"204":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string"}},"required":["message"]}}}},"404":{"description":"Report template not found"}}}},"/api/v1/agents":{"get":{"tags":["Agents"],"summary":"List agents","parameters":[{"schema":{"type":"string"},"required":false,"name":"modelProvider","in":"query"},{"schema":{"type":"string","enum":["true","false"]},"required":false,"name":"includeDeleted","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/AgentResponse"}}}}}}},"post":{"tags":["Agents"],"summary":"Create or update agent (upsert)","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateAgentInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentResponse"}}}},"400":{"description":"Validation error"},"409":{"description":"Restored agent versions conflict with an active queue owner"}}}},"/api/v1/agents/{id}":{"get":{"tags":["Agents"],"summary":"Get agent","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","enum":["true","false"]},"required":false,"name":"includeDeleted","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentResponse"}}}},"404":{"description":"Agent not found"}}},"put":{"tags":["Agents"],"summary":"Update agent","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateAgentInput"}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentResponse"}}}},"400":{"description":"Validation error"},"404":{"description":"Agent not found"}}},"delete":{"tags":["Agents"],"summary":"Delete agent","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"204":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string"}},"required":["message"]}}}},"404":{"description":"Agent not found"}}}},"/api/v1/agents/{id}/versions":{"get":{"tags":["Agents"],"summary":"List agent versions","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":false,"name":"status","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/AgentVersion"}}}}},"404":{"description":"Agent not found"}}},"post":{"tags":["Agents"],"summary":"Register agent version (upsert)","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RegisterAgentVersionInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentVersion"}}}},"400":{"description":"Validation error"},"404":{"description":"Agent not found"},"409":{"description":"Queue is assigned to another agent"},"503":{"description":"Concurrent registration did not stabilize"}}}},"/api/v1/agents/{id}/versions/{agentVersion}":{"patch":{"tags":["Agents"],"summary":"Patch agent version","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":true,"name":"agentVersion","in":"path"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PatchAgentVersionInput"}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentVersion"}}}},"400":{"description":"Invalid status value"},"404":{"description":"Agent or version not found"},"409":{"description":"Queue is assigned to another agent"},"503":{"description":"Concurrent activation did not stabilize"}}}},"/api/v1/models":{"get":{"tags":["Models"],"summary":"List models","parameters":[{"schema":{"type":"string"},"required":false,"name":"agentId","in":"query"},{"schema":{"type":"string"},"required":false,"name":"provider","in":"query"},{"schema":{"type":"string","enum":["active","disappeared"]},"required":false,"name":"status","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ModelResponse"}}}}}}}},"/api/v1/models/{id}":{"get":{"tags":["Models"],"summary":"Get model","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ModelResponse"}}}}}}},"/api/v1/models/sync":{"post":{"tags":["Models"],"summary":"Sync models from provider","requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"agentId":{"type":"string"},"provider":{"type":"string"},"models":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"providerAvailableFrom":{"type":"string"},"providerEndOfLife":{"type":"string"},"metadata":{"type":"object","additionalProperties":{}},"capabilities":{"type":"object","properties":{"reasoningEffort":{"type":"array","items":{"type":"string"}},"toolCalls":{"type":"boolean"},"vision":{"type":"boolean"},"streaming":{"type":"boolean"},"adaptiveThinking":{"type":"boolean"},"maxThinkingBudget":{"type":"number"}}}},"required":["id"]}},"scannedAt":{"type":"string"}},"required":["agentId","provider","models","scannedAt"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"added":{"type":"array","items":{"type":"string"}},"removed":{"type":"array","items":{"type":"string"}},"unchanged":{"type":"array","items":{"type":"string"}}},"required":["added","removed","unchanged"]}}}}}}},"/api/v1/mcp/servers":{"get":{"tags":["MCP Servers"],"summary":"List MCP servers","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/McpServerResponse"}}}}}}},"post":{"tags":["MCP Servers"],"summary":"Create MCP server","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"_id":{"type":"string","pattern":"^[a-z0-9]([a-z0-9-]*[a-z0-9])?$"},"name":{"type":"string"},"type":{"type":"string","enum":["sse","http","stdio"]},"url":{"type":"string"},"command":{"type":"string"},"args":{"type":"array","items":{"type":"string"}},"env":{"type":"object","additionalProperties":{"type":"string"}},"headers":{"type":"array","items":{"$ref":"#/components/schemas/McpServerHeader"}},"sessionMode":{"type":"string","enum":["stateful","stateless"]},"version":{"type":"string"},"description":{"type":"string"}},"required":["_id","name","type"]}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/McpServerResponse"}}}}}}},"/api/v1/mcp/servers/{id}":{"get":{"tags":["MCP Servers"],"summary":"Get MCP server","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/McpServerResponse"}}}}}},"put":{"tags":["MCP Servers"],"summary":"Update MCP server","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateMcpServerInput"}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/McpServerResponse"}}}}}},"delete":{"tags":["MCP Servers"],"summary":"Delete MCP server","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"204":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string"}},"required":["message"]}}}}}}},"/api/v1/skills":{"get":{"tags":["Skills"],"summary":"List all skills","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/SkillResponse"}}}}}}},"post":{"tags":["Skills"],"summary":"Create or import a skill","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateSkillInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SkillResponse"}}}}}}},"/api/v1/skills/search":{"get":{"tags":["Skills"],"summary":"Search skills (internal + external)","parameters":[{"schema":{"type":"string"},"required":true,"name":"q","in":"query"},{"schema":{"type":"string"},"required":false,"name":"limit","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/SkillSearchResult"}}}}},"400":{"description":"Missing query parameter"}}}},"/api/v1/skills/search/external":{"get":{"tags":["Skills"],"summary":"Search external skills registry","parameters":[{"schema":{"type":"string"},"required":true,"name":"q","in":"query"},{"schema":{"type":"string"},"required":false,"name":"limit","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Optional project scope. When provided, external results are de-duplicated only against skills already installed in that project."},"required":false,"description":"Optional project scope. When provided, external results are de-duplicated only against skills already installed in that project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/SkillSearchResult"}}}}},"400":{"description":"Missing query parameter"}}}},"/api/v1/skills/discover":{"get":{"tags":["Skills"],"summary":"Discover skills in a GitHub repository","parameters":[{"schema":{"type":"string"},"required":true,"name":"source","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/SkillDiscoveryResult"}}}}},"400":{"description":"Missing or malformed source parameter"},"404":{"description":"Repository not found"},"502":{"description":"GitHub API error"}}}},"/api/v1/skills/{id}(*)/revisions":{"get":{"tags":["Skills"],"summary":"List skill revisions","parameters":[{"schema":{"type":"string"},"required":false,"name":"limit","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/SkillRevisionResponse"}}}}},"404":{"description":"Skill not found"}}}},"/api/v1/skills/{id}(*)":{"get":{"tags":["Skills"],"summary":"Get skill by slug","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SkillResponse"}}}},"404":{"description":"Skill not found"}}},"delete":{"tags":["Skills"],"summary":"Soft-delete a skill","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"204":{"description":"Success"},"404":{"description":"Skill not found"}}}},"/api/v1/skill-revisions/by-ref/{ref}(*)/archive":{"get":{"tags":["Skill Revisions"],"summary":"Download skill revision archive","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Binary tar.gz archive"},"404":{"description":"Skill revision or archive not found"},"500":{"description":"Blob storage error"}}}},"/api/v1/skill-revisions/by-ref/{ref}(*)":{"get":{"tags":["Skill Revisions"],"summary":"Get skill revision by ref","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SkillRevisionResponse"}}}},"404":{"description":"Skill revision not found"}}}},"/api/v1/skill-revisions/{id}":{"get":{"tags":["Skill Revisions"],"summary":"Get skill revision by ID","responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SkillRevisionResponse"}}}},"404":{"description":"Skill revision not found"}}}},"/api/v1/skills/{id}(*)/resolve":{"post":{"tags":["Skills"],"summary":"Trigger skill resolution","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SkillRevisionResponse"}}}},"404":{"description":"Skill not found"},"500":{"description":"Blob storage error"}}}},"/api/v1/codebases":{"get":{"tags":["Codebases"],"summary":"List all codebases","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/CodebaseResponse"}}}}}}},"post":{"tags":["Codebases"],"summary":"Create a codebase (archive codebases require the archive file)","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"201":{"description":"Success"},"400":{"description":"Invalid input or missing archive"}}}},"/api/v1/codebases/{id}":{"get":{"tags":["Codebases"],"summary":"Get a codebase","responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CodebaseResponse"}}}},"404":{"description":"Codebase not found"}}},"patch":{"tags":["Codebases"],"summary":"Update a codebase","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateCodebaseInput"}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CodebaseResponse"}}}},"404":{"description":"Codebase not found"}}},"delete":{"tags":["Codebases"],"summary":"Delete a codebase","responses":{"204":{"description":"Success"},"404":{"description":"Codebase not found"}}}},"/api/v1/codebases/{id}/revisions":{"get":{"tags":["Codebases"],"summary":"List codebase revisions","parameters":[{"schema":{"type":"string"},"required":false,"name":"limit","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/CodebaseRevisionResponse"}}}}},"404":{"description":"Codebase not found"}}},"post":{"tags":["Codebases"],"summary":"Resolve a new git codebase revision","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ResolveCodebaseRevisionInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CodebaseRevisionResponse"}}}},"400":{"description":"Not a git codebase"},"404":{"description":"Codebase not found"},"502":{"description":"GitHub resolution failed"}}}},"/api/v1/codebases/{id}/upload":{"post":{"tags":["Codebases"],"summary":"Upload a codebase archive as a new revision","responses":{"201":{"description":"Success"},"400":{"description":"Missing archive or not an archive codebase"},"404":{"description":"Codebase not found"}}}},"/api/v1/codebase-revisions/{id}/archive":{"get":{"tags":["Codebase Revisions"],"summary":"Download codebase revision archive","responses":{"200":{"description":"Binary tar.gz archive"},"404":{"description":"Revision or archive not found"},"500":{"description":"Blob storage error"}}}},"/api/v1/codebase-revisions/{id}":{"get":{"tags":["Codebase Revisions"],"summary":"Get codebase revision by id","responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CodebaseRevisionResponse"}}}},"404":{"description":"Revision not found"}}}},"/api/v1/resources":{"get":{"tags":["Resources"],"summary":"List all resources","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ResourceResponse"}}}}}}},"post":{"tags":["Resources"],"summary":"Create a resource and its first revision","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateResourceInput"}}}},"responses":{"201":{"description":"Success"},"400":{"description":"Invalid input"},"409":{"description":"Resource slug or revision ref already exists in this project"}}}},"/api/v1/resources/{id}":{"get":{"tags":["Resources"],"summary":"Get a resource","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ResourceResponse"}}}},"404":{"description":"Resource not found"}}},"patch":{"tags":["Resources"],"summary":"Update a resource","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateResourceInput"}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ResourceResponse"}}}},"404":{"description":"Resource not found"}}},"delete":{"tags":["Resources"],"summary":"Delete a resource","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"204":{"description":"Success"},"404":{"description":"Resource not found"}}}},"/api/v1/resources/{id}/revisions":{"get":{"tags":["Resource Revisions"],"summary":"List resource revisions","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"},{"schema":{"type":"string"},"required":false,"name":"limit","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ResourceRevisionResponse"}}}}},"404":{"description":"Resource not found"}}},"post":{"tags":["Resource Revisions"],"summary":"Create a resource revision","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateResourceRevisionInput"}}}},"responses":{"201":{"description":"Success"},"404":{"description":"Resource not found"},"409":{"description":"Resource revision ref already exists in this project"}}}},"/api/v1/resources/{id}/revisions/latest":{"get":{"tags":["Resource Revisions"],"summary":"Get the latest resource revision","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ResourceRevisionResponse"}}}},"404":{"description":"Revision not found"}}}},"/api/v1/resources/{id}/revisions/{revisionNumber}":{"get":{"tags":["Resource Revisions"],"summary":"Get a resource revision by resource and revision number","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":true,"name":"revisionNumber","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ResourceRevisionResponse"}}}},"404":{"description":"Revision not found"}}}},"/api/v1/resources/revisions/{id}":{"get":{"tags":["Resource Revisions"],"summary":"Get resource revision by id","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ResourceRevisionResponse"}}}},"404":{"description":"Revision not found"}}}},"/api/v1/extensions":{"get":{"tags":["Extensions"],"summary":"List all extensions","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ExtensionResponse"}}}}}}},"post":{"tags":["Extensions"],"summary":"Create or import an extension","parameters":[{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateExtensionInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExtensionResponse"}}}}}}},"/api/v1/extensions/search":{"get":{"tags":["Extensions"],"summary":"Search extensions (internal + marketplace)","parameters":[{"schema":{"type":"string"},"required":true,"name":"q","in":"query"},{"schema":{"type":"string"},"required":false,"name":"limit","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ExtensionSearchResult"}}}}},"400":{"description":"Missing query parameter"}}}},"/api/v1/extensions/{id}":{"get":{"tags":["Extensions"],"summary":"Get extension by ID","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExtensionResponse"}}}}}},"put":{"tags":["Extensions"],"summary":"Update extension","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateExtensionInput"}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExtensionResponse"}}}}}},"delete":{"tags":["Extensions"],"summary":"Delete extension","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"204":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string"}},"required":["message"]}}}}}}},"/api/v1/extensions/{id}/versions":{"get":{"tags":["Extensions"],"summary":"List available versions for an extension","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"},{"schema":{"type":"string"},"required":false,"name":"preRelease","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ExtensionVersionInfo"}}}}}}}},"/api/v1/insights":{"get":{"tags":["Insights"],"summary":"List insights","parameters":[{"schema":{"type":"string"},"required":false,"name":"q","in":"query"},{"schema":{"type":"string"},"required":false,"name":"blocked","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/InsightResponse"}}}}}}},"post":{"tags":["Insights"],"summary":"Create insight","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateInsightInput"}}}},"responses":{"201":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InsightResponse"}}}}}}},"/api/v1/insights/search":{"get":{"tags":["Insights"],"summary":"Search insights","parameters":[{"schema":{"type":"string"},"required":true,"name":"q","in":"query"},{"schema":{"type":"string"},"required":false,"name":"blocked","in":"query"},{"schema":{"type":"string","minLength":1,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","example":"00000000-0000-0000-0000-000000000000"},"required":true,"description":"Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.","name":"projectId","in":"query"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/InsightResponse"}}}}}}}},"/api/v1/insights/{id}":{"get":{"tags":["Insights"],"summary":"Get insight","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InsightResponse"}}}},"404":{"description":"Insight not found"}}},"put":{"tags":["Insights"],"summary":"Update insight","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateInsightInput"}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InsightResponse"}}}},"404":{"description":"Insight not found"}}},"delete":{"tags":["Insights"],"summary":"Delete insight","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"204":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string"}},"required":["message"]}}}},"404":{"description":"Insight not found"}}}},"/api/v1/insights/{id}/upvote":{"post":{"tags":["Insights"],"summary":"Upvote insight","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InsightResponse"}}}},"404":{"description":"Insight not found"}}}},"/api/v1/insights/{id}/downvote":{"post":{"tags":["Insights"],"summary":"Downvote insight","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InsightResponse"}}}},"404":{"description":"Insight not found"}}}},"/api/v1/insights/{id}/block":{"post":{"tags":["Insights"],"summary":"Block insight","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InsightResponse"}}}},"404":{"description":"Insight not found"}}}},"/api/v1/insights/{id}/unblock":{"post":{"tags":["Insights"],"summary":"Unblock insight","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InsightResponse"}}}},"404":{"description":"Insight not found"}}}},"/api/v1/insights/{id}/reports":{"get":{"tags":["Insights"],"summary":"Get reports referencing insight","parameters":[{"schema":{"type":"string"},"required":true,"name":"id","in":"path"}],"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ReportResponse"}}}}},"404":{"description":"Insight not found"}}}},"/api/v1/feature-flags":{"get":{"tags":["Feature Flags"],"summary":"List feature flags","responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/FeatureFlagResponse"}}}}}}}},"/api/v1/feature-flags/{key}":{"put":{"tags":["Feature Flags"],"summary":"Update feature flag","parameters":[{"schema":{"type":"string"},"required":true,"name":"key","in":"path"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateFeatureFlagInput"}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FeatureFlagResponse"}}}}}}}},"webhooks":{}} \ No newline at end of file From 0220a1173fa76b4e96fac60df10437e00097b62a Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Tue, 13 Oct 2026 16:26:29 +0200 Subject: [PATCH 043/210] feat(submissions): add Portal and CLI workflows Navigate successful submits to a Submission Detail shell, link grouped runs and run detail back to their parent submission, surface readiness and blocking pairs, and add CLI list/get/history/retry parity with Storybook coverage. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 99f84f04-d3b0-40f1-a254-4dfbd21e4d87 --- apps/cli/src/commands/submission.ts | 206 ++++++++++++++++++ apps/cli/src/index.ts | 2 + apps/portal/src/App.tsx | 2 + .../SubmissionStatusCard.stories.tsx | 81 +++++++ .../components/SubmissionStatusCard.test.tsx | 69 ++++++ .../src/components/SubmissionStatusCard.tsx | 55 +++++ apps/portal/src/lib/api.ts | 25 ++- apps/portal/src/pages/RunDetail.tsx | 15 +- apps/portal/src/pages/RunsList.tsx | 52 +++-- apps/portal/src/pages/SubmissionDetail.tsx | 164 ++++++++++++++ apps/portal/src/pages/SubmitRun.tsx | 8 +- apps/portal/src/types.ts | 69 +++++- 12 files changed, 715 insertions(+), 33 deletions(-) create mode 100644 apps/cli/src/commands/submission.ts create mode 100644 apps/portal/src/components/SubmissionStatusCard.stories.tsx create mode 100644 apps/portal/src/components/SubmissionStatusCard.test.tsx create mode 100644 apps/portal/src/components/SubmissionStatusCard.tsx create mode 100644 apps/portal/src/pages/SubmissionDetail.tsx diff --git a/apps/cli/src/commands/submission.ts b/apps/cli/src/commands/submission.ts new file mode 100644 index 000000000..52b6c4b7a --- /dev/null +++ b/apps/cli/src/commands/submission.ts @@ -0,0 +1,206 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { Command } from "commander"; +import { configureHelp } from "../utils/helpFormatter.js"; +import { formatData, isMachineReadable } from "../utils/formatters.js"; +import type { DisplayField, OutputFormat } from "../utils/types.js"; +import { + getDefaultApiUrl, + withOutputOption, + withProjectOption, +} from "../utils/shared.js"; +import { requireProjectId } from "../utils/config.js"; +import { apiFetch } from "../utils/api-client.js"; +import { errorText, label, successText, value } from "../utils/style.js"; + +interface SubmissionSummary { + submissionId: string; + submissionRunId: string; + attemptNumber: number; + readiness: string; + createdAt: string; + requestIds: string[]; + requests: Array<{ + requestId: string; + runId: string; + task: string; + status: string; + outcome?: string; + }>; + blocking: Array<{ + requestId: string; + runId: string; + reason: string; + }>; +} + +async function responseJson(response: Response): Promise { + return response.json() as Promise; +} + +async function throwApiError(response: Response): Promise { + const body = await responseJson<{ error?: string }>(response); + throw new Error(body.error ?? `HTTP ${response.status}`); +} + +const fields: DisplayField[] = [ + { key: "submissionId", label: "Submission" }, + { key: "attemptNumber", label: "Attempt" }, + { key: "readiness", label: "Readiness" }, + { + key: "requestIds", + label: "Runs", + formatter: (row: Record) => + String((row.requestIds as string[] | undefined)?.length ?? 0), + }, + { key: "createdAt", label: "Created" }, +]; + +export function registerSubmissionCommands(program: Command): void { + const submission = program + .command("submission") + .description("Inspect and retry grouped run submissions") + .action(() => submission.help()); + configureHelp(submission); + + withProjectOption( + withOutputOption( + submission + .command("list") + .description("List submissions") + .option("-u, --url ", "API base URL", getDefaultApiUrl()), + ), + ).action(async (options) => { + try { + const projectId = requireProjectId(options.project); + const response = await apiFetch(options.url, "/submissions", { projectId }); + if (!response.ok) await throwApiError(response); + const body = await responseJson<{ submissions: SubmissionSummary[] }>(response); + console.log( + formatData(body.submissions, fields, (options.output ?? "table") as OutputFormat), + ); + } catch (error) { + console.error(errorText("Error:"), error instanceof Error ? error.message : error); + process.exitCode = 1; + } + }); + + withOutputOption( + submission + .command("get") + .description("Get a submission and its current request/run vector") + .argument("", "Submission ID") + .option("-u, --url ", "API base URL", getDefaultApiUrl()), + ).action(async (id: string, options) => { + try { + const response = await apiFetch( + options.url, + `/submissions/${encodeURIComponent(id)}`, + ); + if (!response.ok) await throwApiError(response); + const doc = await responseJson(response); + const format = (options.output ?? "table") as OutputFormat; + if (isMachineReadable(format)) { + console.log(formatData([doc], fields, format)); + return; + } + console.log(`${label("Submission:")} ${value(doc.submissionId)}`); + console.log(`${label("Attempt:")} ${value(String(doc.attemptNumber))}`); + console.log(`${label("Readiness:")} ${value(doc.readiness)}`); + console.log(`${label("Submission run:")} ${value(doc.submissionRunId)}`); + for (const request of doc.requests) { + console.log( + ` ${value(request.requestId)} ${request.status}` + + `${request.outcome ? `/${request.outcome}` : ""} run=${request.runId}`, + ); + } + for (const blocking of doc.blocking) { + console.log( + ` blocked ${blocking.requestId}/${blocking.runId}: ${blocking.reason}`, + ); + } + } catch (error) { + console.error(errorText("Error:"), error instanceof Error ? error.message : error); + process.exitCode = 1; + } + }); + + withOutputOption( + submission + .command("runs") + .description("List current and archived submission attempts") + .argument("", "Submission ID") + .option("-u, --url ", "API base URL", getDefaultApiUrl()), + ).action(async (id: string, options) => { + try { + const response = await apiFetch( + options.url, + `/submissions/${encodeURIComponent(id)}/runs`, + ); + if (!response.ok) await throwApiError(response); + const body = await responseJson<{ + runs: Array<{ + _id: string; + attemptNumber: number; + createdAt: string; + requests: unknown[]; + supersededReason?: string; + }>; + }>(response); + const runFields: DisplayField[] = [ + { key: "_id", label: "Submission Run" }, + { key: "attemptNumber", label: "Attempt" }, + { + key: "requests", + label: "Runs", + formatter: (row: Record) => + String((row.requests as unknown[] | undefined)?.length ?? 0), + }, + { key: "supersededReason", label: "Superseded" }, + { key: "createdAt", label: "Created" }, + ]; + console.log( + formatData(body.runs, runFields, (options.output ?? "table") as OutputFormat), + ); + } catch (error) { + console.error(errorText("Error:"), error instanceof Error ? error.message : error); + process.exitCode = 1; + } + }); + + submission + .command("retry") + .description("Retry the current submission processing attempt") + .argument("", "Submission ID") + .requiredOption("--submission-run ", "Current submission run ID") + .option("-u, --url ", "API base URL", getDefaultApiUrl()) + .action(async (id: string, options) => { + try { + const response = await apiFetch( + options.url, + `/submissions/${encodeURIComponent(id)}/retry`, + { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ submissionRunId: options.submissionRun }), + }, + ); + if (!response.ok) await throwApiError(response); + const result = await responseJson<{ + submissionRunId: string; + attemptNumber: number; + readiness: string; + }>(response); + console.log( + successText( + `Submission retry started: attempt ${result.attemptNumber} (${result.submissionRunId}, ${result.readiness})`, + ), + ); + } catch (error) { + console.error(errorText("Error:"), error instanceof Error ? error.message : error); + process.exitCode = 1; + } + }); +} + diff --git a/apps/cli/src/index.ts b/apps/cli/src/index.ts index 399f12266..6d59d10a6 100644 --- a/apps/cli/src/index.ts +++ b/apps/cli/src/index.ts @@ -25,6 +25,7 @@ import { registerTaskPromptCommands } from "./commands/task-prompt.js"; import { registerProfileCommands } from "./commands/profile.js"; import { registerProjectCommands } from "./commands/project.js"; import { registerSecretCommands } from "./commands/secret.js"; +import { registerSubmissionCommands } from "./commands/submission.js"; import { registerUpdateCommand } from "./commands/update.js"; import { checkForUpdates } from "./utils/update-check.js"; import { errorText } from "./utils/style.js"; @@ -70,6 +71,7 @@ configureHelp(program); registerSecretCommands(program); registerProjectCommands(program); registerRunCommands(program); +registerSubmissionCommands(program); registerCriteriaCommands(program); registerPromptFeatureCommands(program); registerReportCommands(program); diff --git a/apps/portal/src/App.tsx b/apps/portal/src/App.tsx index 26d5f1d74..56e6a2d79 100644 --- a/apps/portal/src/App.tsx +++ b/apps/portal/src/App.tsx @@ -6,6 +6,7 @@ import { Layout } from "@/components/Layout"; import { RunsList } from "@/pages/RunsList"; import { RunDetail } from "@/pages/RunDetail"; import { SubmitRun } from "@/pages/SubmitRun"; +import { SubmissionDetail } from "@/pages/SubmissionDetail"; import { CriteriaList } from "@/pages/CriteriaList"; import { CriterionDetail } from "@/pages/CriterionDetail"; import { CriterionPreviewPanel } from "@/pages/CriterionPreviewPanel"; @@ -85,6 +86,7 @@ export function App() { } /> } /> + } /> }> } /> diff --git a/apps/portal/src/components/SubmissionStatusCard.stories.tsx b/apps/portal/src/components/SubmissionStatusCard.stories.tsx new file mode 100644 index 000000000..04d8a6365 --- /dev/null +++ b/apps/portal/src/components/SubmissionStatusCard.stories.tsx @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import type { Meta, StoryObj } from "@storybook/react-vite"; +import { SubmissionStatusCard } from "./SubmissionStatusCard"; +import type { Submission } from "@/types"; + +const submission: Submission = { + submissionId: "submission-123", + projectId: "project-123", + requestIds: ["request-1", "request-2"], + createdAt: new Date().toISOString(), + submissionRunId: "submission-run-1", + attemptNumber: 2, + readiness: "processing", + requests: [ + { + requestId: "request-1", + runId: "run-1", + task: "Implement the feature", + status: "done", + outcome: "succeeded", + workerType: "coder-acp-copilot", + }, + { + requestId: "request-2", + runId: "run-2", + task: "Implement the feature", + status: "done", + outcome: "failed", + workerType: "coder-acp-copilot", + }, + ], + dependencyProjection: [ + { + requestId: "request-1", + runId: "run-1", + handlerId: "pp-observations", + state: "ready", + }, + { + requestId: "request-2", + runId: "run-2", + handlerId: "pp-observations", + state: "ready", + }, + ], + blocking: [], + handlerProgress: { + "pp-readout": { status: "processing", version: 1 }, + }, +}; + +const meta = { + title: "Submissions/SubmissionStatusCard", + component: SubmissionStatusCard, + args: { submission }, +} satisfies Meta; + +export default meta; +type Story = StoryObj; + +export const Processing: Story = {}; + +export const Blocked: Story = { + args: { + submission: { + ...submission, + readiness: "blocked", + blocking: [ + { + requestId: "request-2", + runId: "run-2", + handlerId: "pp-observations", + reason: "dependency-failed", + }, + ], + }, + }, +}; + diff --git a/apps/portal/src/components/SubmissionStatusCard.test.tsx b/apps/portal/src/components/SubmissionStatusCard.test.tsx new file mode 100644 index 000000000..8ec046bb0 --- /dev/null +++ b/apps/portal/src/components/SubmissionStatusCard.test.tsx @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +// @vitest-environment happy-dom +import { cleanup, render, screen } from "@testing-library/react"; +import { afterEach, describe, expect, it } from "vitest"; +import type { Submission } from "@/types"; +import { SubmissionStatusCard } from "./SubmissionStatusCard"; + +afterEach(cleanup); + +describe("SubmissionStatusCard", () => { + it("renders readiness and exact observation progress", () => { + const submission: Submission = { + submissionId: "submission-1", + projectId: "project-1", + requestIds: ["request-1", "request-2"], + createdAt: new Date().toISOString(), + submissionRunId: "submission-run-1", + attemptNumber: 3, + readiness: "blocked", + requests: [ + { + requestId: "request-1", + runId: "run-1", + task: "Task", + status: "done", + workerType: "worker", + }, + { + requestId: "request-2", + runId: "run-2", + task: "Task", + status: "done", + workerType: "worker", + }, + ], + dependencyProjection: [ + { + requestId: "request-1", + runId: "run-1", + handlerId: "pp-observations", + state: "ready", + }, + { + requestId: "request-2", + runId: "run-2", + handlerId: "pp-observations", + state: "failed", + }, + ], + blocking: [ + { + requestId: "request-2", + runId: "run-2", + handlerId: "pp-observations", + reason: "dependency-failed", + }, + ], + }; + + render(); + + expect(screen.getByText("blocked")).toBeDefined(); + expect(screen.getByText("3")).toBeDefined(); + expect(screen.getByText("1/2")).toBeDefined(); + }); +}); + diff --git a/apps/portal/src/components/SubmissionStatusCard.tsx b/apps/portal/src/components/SubmissionStatusCard.tsx new file mode 100644 index 000000000..6eca73210 --- /dev/null +++ b/apps/portal/src/components/SubmissionStatusCard.tsx @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { Badge } from "@/components/ui/badge"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import type { Submission } from "@/types"; + +const readinessVariant: Record< + Submission["readiness"], + "default" | "secondary" | "destructive" | "outline" +> = { + waiting: "secondary", + ready: "outline", + blocked: "destructive", + processing: "default", + done: "default", + failed: "destructive", +}; + +export function SubmissionStatusCard({ + submission, +}: { + submission: Submission; +}) { + const ready = submission.dependencyProjection.filter( + (dependency) => dependency.state === "ready", + ).length; + return ( + + + Processing + + {submission.readiness} + + + +
+
Attempt
+
{submission.attemptNumber}
+
+
+
Observations ready
+
+ {ready}/{submission.requests.length} +
+
+
+
Blocking runs
+
{submission.blocking.length}
+
+
+
+ ); +} + diff --git a/apps/portal/src/lib/api.ts b/apps/portal/src/lib/api.ts index 32e1d4a7d..1258ac38e 100644 --- a/apps/portal/src/lib/api.ts +++ b/apps/portal/src/lib/api.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import type { Run, RunState, CriteriaDocument, CriteriaGraphData, GeneratePromptResponse, AnalysisResponse, PromptFeatureDocument, Report, BulkReportStatus, BulkReportSummary, ReportTemplate, ReportTrigger, ReportTemplateSystemPrompt, KeyDocument, KeyValidationResult, CreateKeyRequest, UpdateKeyRequest, CodingAgent, AgentVersion, McpServerDocument, CreateMcpServerRequest, UpdateMcpServerRequest, BulkResubmitOverrides, Insight, InsightWithReference, TaskPrompt, TaskPromptFeatureExtractionResult, Model, FeatureFlag, SkillDocument, SkillSearchResult, SkillDiscoveryResult, SkillRevisionDocument, CodebaseDocument, CodebaseRevisionDocument, CodebaseSourceType, ResourceDocument, ResourceRevisionDocument, ResourceBindingSpec, CreateResourceBody, CreateResourceRevisionBody, ExtensionDocument, ExtensionSearchResult, ExtensionVersionInfo, MdpResponse, AccountDocument, CreateAccountRequest, UpdateAccountRequest, ProfileWithVersion, ProfileVersionDocument, ProfileDocument, RunGroup, RunFacetsResponse, CursorPaginatedResponse, IterationOp, GateConfig, GateId, PromptType, RunSortField, RunSortDir, CriterionKind, TaxonomyElementId, CriterionSubject } from "@/types"; +import type { Run, RunState, CriteriaDocument, CriteriaGraphData, GeneratePromptResponse, AnalysisResponse, PromptFeatureDocument, Report, BulkReportStatus, BulkReportSummary, ReportTemplate, ReportTrigger, ReportTemplateSystemPrompt, KeyDocument, KeyValidationResult, CreateKeyRequest, UpdateKeyRequest, CodingAgent, AgentVersion, McpServerDocument, CreateMcpServerRequest, UpdateMcpServerRequest, BulkResubmitOverrides, Insight, InsightWithReference, TaskPrompt, TaskPromptFeatureExtractionResult, Model, FeatureFlag, SkillDocument, SkillSearchResult, SkillDiscoveryResult, SkillRevisionDocument, CodebaseDocument, CodebaseRevisionDocument, CodebaseSourceType, ResourceDocument, ResourceRevisionDocument, ResourceBindingSpec, CreateResourceBody, CreateResourceRevisionBody, ExtensionDocument, ExtensionSearchResult, ExtensionVersionInfo, MdpResponse, AccountDocument, CreateAccountRequest, UpdateAccountRequest, ProfileWithVersion, ProfileVersionDocument, ProfileDocument, RunGroup, RunFacetsResponse, CursorPaginatedResponse, IterationOp, GateConfig, GateId, PromptType, RunSortField, RunSortDir, CriterionKind, TaxonomyElementId, CriterionSubject, Submission } from "@/types"; import type { Project, CreateProjectRequest, UpdateProjectRequest } from "@/types"; import { qs } from "./url"; @@ -231,7 +231,7 @@ export const api = { gates?: GateConfig[]; codebase?: string; codebaseRevisionId?: string; - }): Promise<(Run & { message: string }) | { ids: string[]; count: number; message: string }> => { + }): Promise<(Run & { message: string; submissionId: string }) | { ids: string[]; count: number; message: string; submissionId: string }> => { const { worker, ...payload } = body; const url = worker ? `/requests?worker=${encodeURIComponent(worker)}` : `/requests`; return request(url, { @@ -240,6 +240,27 @@ export const api = { }, { scoped: true }); }, + listSubmissions: (): Promise<{ submissions: Submission[] }> => + request("/submissions", undefined, { scoped: true }), + + getSubmission: (id: string): Promise => + request(`/submissions/${id}`), + + retrySubmission: ( + id: string, + submissionRunId: string, + ): Promise<{ + submissionId: string; + submissionRunId: string; + attemptNumber: number; + readiness: Submission["readiness"]; + blocking: Submission["blocking"]; + }> => + request(`/submissions/${id}/retry`, { + method: "POST", + body: JSON.stringify({ submissionRunId }), + }), + /** Soft-delete a run */ deleteRun: (id: string): Promise<{ id: string; deleted: boolean }> => { return request(`/requests/${id}`, { method: "DELETE" }); diff --git a/apps/portal/src/pages/RunDetail.tsx b/apps/portal/src/pages/RunDetail.tsx index 8cd9ab00e..9eaed350f 100644 --- a/apps/portal/src/pages/RunDetail.tsx +++ b/apps/portal/src/pages/RunDetail.tsx @@ -531,7 +531,7 @@ export function RunDetail() { (activeRun?.observationResults?.length ?? 0) > 0; const hasConfiguredObservations = (run?.observations?.length ?? 0) > 0; // Aggregate enrichment status across the whole post-processing DAG so the - // "Enriched" badge waits for pp-taxonomy instead of flipping after pp-atif. + // "Enriched" badge waits for pp-observations instead of flipping after pp-atif. const enrichmentStatus = useMemo( () => deriveEnrichmentStatus(activeRun, hasConfiguredObservations), [activeRun, hasConfiguredObservations], @@ -905,6 +905,19 @@ export function RunDetail() { /> )} + {run.submissionId && ( + + {run.submissionId.slice(0, 8)} + + )} + /> + )} {run.maxIterations && } {(() => { const totalDuration = activeRun?.turns?.reduce((sum, t) => sum + (t.durationMs ?? 0), 0); diff --git a/apps/portal/src/pages/RunsList.tsx b/apps/portal/src/pages/RunsList.tsx index 27b685df5..c7257fc97 100644 --- a/apps/portal/src/pages/RunsList.tsx +++ b/apps/portal/src/pages/RunsList.tsx @@ -1350,7 +1350,12 @@ export function RunsList() { hidden: columnVisibility.isHidden("submission"), cell: (r) => r.submissionId ? ( - + event.stopPropagation()} + > + + ) : ( — ), @@ -2666,31 +2671,36 @@ export function RunsList() { ? (profileNameById.get(groupKey) ?? formatId(groupKey)) : groupKey; return ( -
+ {groupBy === "submissionId" && groupKey !== "no-submission" && ( + + View submission + + )} {runs.length} run{runs.length !== 1 ? "s" : ""} - - {expanded ? "Click to collapse" : "Click to expand"} -
- + ); }, }} diff --git a/apps/portal/src/pages/SubmissionDetail.tsx b/apps/portal/src/pages/SubmissionDetail.tsx new file mode 100644 index 000000000..5dd5cab46 --- /dev/null +++ b/apps/portal/src/pages/SubmissionDetail.tsx @@ -0,0 +1,164 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { ArrowLeft, FileText, RotateCcw } from "lucide-react"; +import { Link, useParams } from "react-router-dom"; +import { toast } from "sonner"; +import { SubmissionStatusCard } from "@/components/SubmissionStatusCard"; +import { ShortId } from "@/components/ShortId"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { api } from "@/lib/api"; +import { formatDate } from "@/lib/utils"; + +export function SubmissionDetail() { + const { id } = useParams<{ id: string }>(); + const queryClient = useQueryClient(); + const submissionQuery = useQuery({ + queryKey: ["submission", id], + queryFn: () => api.getSubmission(id!), + enabled: Boolean(id), + refetchInterval: (query) => { + const readiness = query.state.data?.readiness; + return readiness === "done" || readiness === "failed" || readiness === "blocked" + ? false + : 5_000; + }, + }); + const retry = useMutation({ + mutationFn: () => + api.retrySubmission( + submissionQuery.data!.submissionId, + submissionQuery.data!.submissionRunId, + ), + onSuccess: () => { + toast.success("Submission processing restarted"); + void queryClient.invalidateQueries({ queryKey: ["submission", id] }); + }, + onError: (error) => { + toast.error(error instanceof Error ? error.message : "Retry failed"); + }, + }); + + if (submissionQuery.isLoading) { + return
Loading submission…
; + } + if (submissionQuery.isError || !submissionQuery.data) { + return ( +
+

Submission could not be loaded.

+
+ ); + } + + const submission = submissionQuery.data; + return ( +
+
+
+ +
+

Submission

+ +
+

+ Created {formatDate(submission.createdAt)} +

+
+ +
+ + + + {submission.blocking.length > 0 && ( + + + Blocking dependencies + + + {submission.blocking.map((blocking) => ( +
+ + {blocking.requestId.slice(0, 8)} + + {blocking.reason} + + {blocking.runId} + +
+ ))} +
+
+ )} + + + + Runs + + + {submission.requests.map((request) => { + const dependency = submission.dependencyProjection.find( + (item) => + item.requestId === request.requestId && item.runId === request.runId, + ); + return ( + +
+
+ + {request.task} +
+
+ {request.requestId} · {request.runId} +
+
+
+ {request.status} + + {dependency?.state ?? "waiting"} + +
+ + ); + })} +
+
+
+ ); +} + diff --git a/apps/portal/src/pages/SubmitRun.tsx b/apps/portal/src/pages/SubmitRun.tsx index ec6b639ea..b6c51baeb 100644 --- a/apps/portal/src/pages/SubmitRun.tsx +++ b/apps/portal/src/pages/SubmitRun.tsx @@ -667,13 +667,7 @@ export function SubmitRun() { const submitMutation = useMutation({ mutationFn: api.submitRun, onSuccess: (data) => { - if ("ids" in data && data.ids.length > 1) { - navigate("/runs"); - } else if ("id" in data) { - navigate(`/runs/${data.id}`); - } else { - navigate("/runs"); - } + navigate(`/submissions/${data.submissionId}`); }, }); diff --git a/apps/portal/src/types.ts b/apps/portal/src/types.ts index 51a91eae0..1ee0d61f0 100644 --- a/apps/portal/src/types.ts +++ b/apps/portal/src/types.ts @@ -126,7 +126,7 @@ export interface OsInfo { /** * Per-handler post-processing status in the DAG (issue #1147). Keys in - * `RunState.handlerStatus` are handler IDs (e.g. "pp-atif", "pp-taxonomy"). + * `RunState.handlerStatus` are handler IDs (e.g. "pp-atif", "pp-observations"). */ export interface HandlerRunStatus { status: "queued" | "processing" | "done" | "failed"; @@ -173,7 +173,7 @@ export interface RunState { postProcessorStatus?: "queued" | "processing" | "done" | "failed"; /** * Per-handler post-processing status keyed by handler ID (e.g. "pp-atif", - * "pp-taxonomy"). Drives the aggregate "Enriched" badge so it only flips to + * "pp-observations"). Drives the aggregate "Enriched" badge so it only flips to * done once every handler in the DAG is terminal — not after the first * handler (pp-atif) completes. The legacy `postProcessorStatus` scalar only * tracks pp-atif and is kept for backward compatibility. @@ -225,6 +225,71 @@ export interface Run { gateSummaries?: GateRunSummary[]; } +export type SubmissionReadiness = + | "waiting" + | "ready" + | "blocked" + | "processing" + | "done" + | "failed"; + +export interface SubmissionDependencyProjection { + requestId: string; + runId: string; + handlerId: string; + state: "waiting" | "ready" | "failed" | "blocked"; + version?: number; + updatedAt?: string; + error?: string; +} + +export interface SubmissionBlockingDetail { + requestId: string; + runId: string; + handlerId: string; + reason: + | "request-missing" + | "run-changed" + | "dependency-failed" + | "dependency-blocked"; + error?: string; +} + +export interface SubmissionRequestSummary { + requestId: string; + runId: string; + task: string; + status: string; + outcome?: string; + workerType: string; + model?: string; + profileId?: string; +} + +export interface Submission { + submissionId: string; + projectId: string; + requestIds: string[]; + createdAt: string; + updatedAt?: string; + submissionRunId: string; + attemptNumber: number; + readiness: SubmissionReadiness; + requests: SubmissionRequestSummary[]; + dependencyProjection: SubmissionDependencyProjection[]; + blocking: SubmissionBlockingDetail[]; + handlerProgress?: Record< + string, + { + status: "queued" | "processing" | "done" | "failed"; + version?: number; + updatedAt?: string; + error?: string; + } + >; + report?: { reportId?: string; url?: string; updatedAt?: string }; +} + export interface CursorPaginatedResponse { data: T[]; limit: number; From a88da9788be4c0f3fcaf6c46fa71edfd5c797923 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Tue, 13 Oct 2026 16:26:42 +0200 Subject: [PATCH 044/210] style(submissions): normalize file endings Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 99f84f04-d3b0-40f1-a254-4dfbd21e4d87 --- apps/cli/src/commands/submission.ts | 2 -- apps/portal/src/components/SubmissionStatusCard.stories.tsx | 2 -- apps/portal/src/components/SubmissionStatusCard.test.tsx | 1 - apps/portal/src/components/SubmissionStatusCard.tsx | 1 - apps/portal/src/pages/SubmissionDetail.tsx | 2 -- .../db-migrations/src/034-create-submission-indexes.test.ts | 1 - 6 files changed, 9 deletions(-) diff --git a/apps/cli/src/commands/submission.ts b/apps/cli/src/commands/submission.ts index 52b6c4b7a..835e7f3ed 100644 --- a/apps/cli/src/commands/submission.ts +++ b/apps/cli/src/commands/submission.ts @@ -34,7 +34,6 @@ interface SubmissionSummary { reason: string; }>; } - async function responseJson(response: Response): Promise { return response.json() as Promise; } @@ -203,4 +202,3 @@ export function registerSubmissionCommands(program: Command): void { } }); } - diff --git a/apps/portal/src/components/SubmissionStatusCard.stories.tsx b/apps/portal/src/components/SubmissionStatusCard.stories.tsx index 04d8a6365..0c465e7e9 100644 --- a/apps/portal/src/components/SubmissionStatusCard.stories.tsx +++ b/apps/portal/src/components/SubmissionStatusCard.stories.tsx @@ -50,7 +50,6 @@ const submission: Submission = { "pp-readout": { status: "processing", version: 1 }, }, }; - const meta = { title: "Submissions/SubmissionStatusCard", component: SubmissionStatusCard, @@ -78,4 +77,3 @@ export const Blocked: Story = { }, }, }; - diff --git a/apps/portal/src/components/SubmissionStatusCard.test.tsx b/apps/portal/src/components/SubmissionStatusCard.test.tsx index 8ec046bb0..b735e762e 100644 --- a/apps/portal/src/components/SubmissionStatusCard.test.tsx +++ b/apps/portal/src/components/SubmissionStatusCard.test.tsx @@ -66,4 +66,3 @@ describe("SubmissionStatusCard", () => { expect(screen.getByText("1/2")).toBeDefined(); }); }); - diff --git a/apps/portal/src/components/SubmissionStatusCard.tsx b/apps/portal/src/components/SubmissionStatusCard.tsx index 6eca73210..f711bdd1c 100644 --- a/apps/portal/src/components/SubmissionStatusCard.tsx +++ b/apps/portal/src/components/SubmissionStatusCard.tsx @@ -52,4 +52,3 @@ export function SubmissionStatusCard({ ); } - diff --git a/apps/portal/src/pages/SubmissionDetail.tsx b/apps/portal/src/pages/SubmissionDetail.tsx index 5dd5cab46..a4a7b67bf 100644 --- a/apps/portal/src/pages/SubmissionDetail.tsx +++ b/apps/portal/src/pages/SubmissionDetail.tsx @@ -52,7 +52,6 @@ export function SubmissionDetail() { ); } - const submission = submissionQuery.data; return (
@@ -161,4 +160,3 @@ export function SubmissionDetail() {
); } - diff --git a/packages/db-migrations/src/034-create-submission-indexes.test.ts b/packages/db-migrations/src/034-create-submission-indexes.test.ts index 1fd59c8bd..efcd2017f 100644 --- a/packages/db-migrations/src/034-create-submission-indexes.test.ts +++ b/packages/db-migrations/src/034-create-submission-indexes.test.ts @@ -49,4 +49,3 @@ describe("migration 034: CreateSubmissionIndexes", () => { ); }); }); - From 57c76344b18e886986375cee8e815d562c577d82 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Thu, 15 Oct 2026 22:11:48 -0700 Subject: [PATCH 045/210] feat(shared): add canonical experiment storage Introduce the Experiment aggregate, bounded request payload schemas, deterministic Cosmos-safe chunk routing/layout, persistence CAS and repair primitives, focused tests, and migration indexes. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 8fe76b9e-1205-4910-b51b-e8fa51538125 --- docs/architecture/db-migrations.md | 1 + ...-create-experiment-storage-indexes.test.ts | 42 ++ .../034-create-experiment-storage-indexes.ts | 41 ++ .../db-migrations/src/required-migrations.ts | 2 +- packages/shared/package.json | 5 + .../src/experiments/experiment-store.test.ts | 193 +++++ .../src/experiments/experiment-store.ts | 683 ++++++++++++++++++ .../experiments/fixed-payload-store.test.ts | 130 ++++ .../src/experiments/fixed-payload-store.ts | 316 ++++++++ packages/shared/src/experiments/index.ts | 9 + .../shared/src/experiments/layout.test.ts | 112 +++ packages/shared/src/experiments/layout.ts | 123 ++++ .../shared/src/experiments/routing.test.ts | 34 + packages/shared/src/experiments/routing.ts | 51 ++ .../shared/src/experiments/schemas.test.ts | 80 ++ packages/shared/src/experiments/schemas.ts | 170 +++++ packages/shared/src/experiments/types.ts | 149 ++++ packages/shared/src/index.ts | 2 +- 18 files changed, 2141 insertions(+), 2 deletions(-) create mode 100644 packages/db-migrations/src/034-create-experiment-storage-indexes.test.ts create mode 100644 packages/db-migrations/src/migrations/034-create-experiment-storage-indexes.ts create mode 100644 packages/shared/src/experiments/experiment-store.test.ts create mode 100644 packages/shared/src/experiments/experiment-store.ts create mode 100644 packages/shared/src/experiments/fixed-payload-store.test.ts create mode 100644 packages/shared/src/experiments/fixed-payload-store.ts create mode 100644 packages/shared/src/experiments/index.ts create mode 100644 packages/shared/src/experiments/layout.test.ts create mode 100644 packages/shared/src/experiments/layout.ts create mode 100644 packages/shared/src/experiments/routing.test.ts create mode 100644 packages/shared/src/experiments/routing.ts create mode 100644 packages/shared/src/experiments/schemas.test.ts create mode 100644 packages/shared/src/experiments/schemas.ts create mode 100644 packages/shared/src/experiments/types.ts diff --git a/docs/architecture/db-migrations.md b/docs/architecture/db-migrations.md index d01bcc5aa..fc7cfd9a8 100644 --- a/docs/architecture/db-migrations.md +++ b/docs/architecture/db-migrations.md @@ -118,6 +118,7 @@ When you run a command: | `031-migrate-services-to-handler-dag` | Replaces the legacy single `post-processor` service row with per-handler service registrations and dependencies | | `032-add-handler-status-index` | Adds a handler-specific dispatch index for `pp-atif` polling | | `033-backfill-handler-status` | Backfills `run.handlerStatus.pp-atif` from deprecated `run.postProcessorStatus` / `run.postProcessorVersion` fields | +| `034-create-experiment-storage-indexes` | Adds the project paging and immutable execution-history indexes for canonical Experiment storage; request payload chunks remain point-read by deterministic `_id` only | ### Migration 029: users identity uniqueness diff --git a/packages/db-migrations/src/034-create-experiment-storage-indexes.test.ts b/packages/db-migrations/src/034-create-experiment-storage-indexes.test.ts new file mode 100644 index 000000000..c180b94ad --- /dev/null +++ b/packages/db-migrations/src/034-create-experiment-storage-indexes.test.ts @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import type { Db } from "mongodb"; +import { describe, expect, it, vi } from "vitest"; +import { CreateExperimentStorageIndexes } from "./migrations/034-create-experiment-storage-indexes.js"; + +function collection() { + return { createIndex: vi.fn(async () => "index") }; +} + +describe("migration 034: experiment storage indexes", () => { + it("creates only project paging and execution history indexes", async () => { + const experiments = collection(); + const executions = collection(); + const chunks = collection(); + const db = { + collection: vi.fn((name: string) => { + if (name === "experiments") return experiments; + if (name === "experiment-executions") return executions; + if (name === "experiment-chunks") return chunks; + throw new Error(`Unexpected collection ${name}`); + }), + } as unknown as Db; + + await new CreateExperimentStorageIndexes().up(db); + + expect(experiments.createIndex).toHaveBeenCalledWith( + { projectId: 1, _id: 1 }, + {}, + ); + expect(executions.createIndex).toHaveBeenCalledWith( + { projectId: 1 }, + {}, + ); + expect(executions.createIndex).toHaveBeenCalledWith( + { experimentId: 1, attemptNumber: -1 }, + {}, + ); + expect(chunks.createIndex).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/db-migrations/src/migrations/034-create-experiment-storage-indexes.ts b/packages/db-migrations/src/migrations/034-create-experiment-storage-indexes.ts new file mode 100644 index 000000000..aa643319e --- /dev/null +++ b/packages/db-migrations/src/migrations/034-create-experiment-storage-indexes.ts @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import type { Db } from "mongodb"; +import type { MigrationInterface } from "mongo-migrate-ts"; +import { ensureIndex } from "../cosmos-index-helpers.js"; + +const TAG = "034"; + +export class CreateExperimentStorageIndexes implements MigrationInterface { + async up(db: Db): Promise { + await ensureIndex( + db.collection("experiments"), + { projectId: 1, _id: 1 }, + {}, + "experiments", + TAG, + ); + await ensureIndex( + db.collection("experiment-executions"), + { projectId: 1 }, + {}, + "experiment-executions", + TAG, + ); + await ensureIndex( + db.collection("experiment-executions"), + { experimentId: 1, attemptNumber: -1 }, + {}, + "experiment-executions", + TAG, + ); + console.log(`[${TAG}] Experiment storage indexes complete`); + } + + async down(_db: Db): Promise { + console.log( + `[${TAG}-down] Skipping index changes - drop experiment indexes manually if needed`, + ); + } +} diff --git a/packages/db-migrations/src/required-migrations.ts b/packages/db-migrations/src/required-migrations.ts index bee754391..8d513270e 100644 --- a/packages/db-migrations/src/required-migrations.ts +++ b/packages/db-migrations/src/required-migrations.ts @@ -46,7 +46,7 @@ export const REQUIRED_MIGRATIONS: readonly string[] = [ "031-migrate-services-to-handler-dag.ts", "032-add-handler-status-index.ts", "033-backfill-handler-status.ts", - "034-create-submission-indexes.ts", + "034-create-experiment-storage-indexes.ts", "021-backfill-criteria-kind.ts", "022-backfill-criteria-subject.ts", ]; diff --git a/packages/shared/package.json b/packages/shared/package.json index db86b934f..155cb5643 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -44,6 +44,11 @@ "source": "./src/criteria/criteria-provider-factory.ts", "types": "./dist/criteria/criteria-provider-factory.d.ts", "import": "./dist/criteria/criteria-provider-factory.js" + }, + "./experiments": { + "source": "./src/experiments/index.ts", + "types": "./dist/experiments/index.d.ts", + "import": "./dist/experiments/index.js" } }, "scripts": { diff --git a/packages/shared/src/experiments/experiment-store.test.ts b/packages/shared/src/experiments/experiment-store.test.ts new file mode 100644 index 000000000..ef925baa0 --- /dev/null +++ b/packages/shared/src/experiments/experiment-store.test.ts @@ -0,0 +1,193 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import type { Collection, Document } from "mongodb"; +import { describe, expect, it } from "vitest"; +import { ExperimentStore } from "./experiment-store.js"; +import { + EXPERIMENT_STORAGE_PROFILE_VERSION, + type ExperimentDocument, + type ExperimentExecutionHistoryDocument, +} from "./types.js"; + +function getPath(source: object, path: string): unknown { + let value: unknown = source; + for (const segment of path.split(".")) { + if (typeof value !== "object" || value === null) return undefined; + value = (value as Record)[segment]; + } + return value; +} + +function setPath(target: object, path: string, value: unknown): void { + const segments = path.split("."); + let current = target as Record; + for (const segment of segments.slice(0, -1)) { + const next = current[segment]; + if (typeof next !== "object" || next === null) { + current[segment] = {}; + } + current = current[segment] as Record; + } + current[segments.at(-1)!] = value; +} + +function matches(document: object, filter: Document): boolean { + return Object.entries(filter).every(([path, expected]) => { + const actual = getPath(document, path); + if ( + typeof expected === "object" && + expected !== null && + "$exists" in expected + ) { + return ( + (actual !== undefined) === + Boolean((expected as { $exists: unknown }).$exists) + ); + } + return actual === expected; + }); +} + +function atomicCollection(initial: ExperimentDocument) { + let document = structuredClone(initial); + return { + current: () => structuredClone(document), + async findOne(filter: Document) { + return matches(document, filter) ? structuredClone(document) : null; + }, + async findOneAndUpdate( + filter: Document, + update: { + $set?: Record; + $inc?: Record; + }, + ) { + if (!matches(document, filter)) return null; + const next = structuredClone(document); + for (const [path, value] of Object.entries(update.$set ?? {})) { + setPath(next, path, value); + } + for (const [path, increment] of Object.entries(update.$inc ?? {})) { + const value = getPath(next, path); + if (typeof value !== "number") throw new Error(`Non-number ${path}`); + setPath(next, path, value + increment); + } + document = next; + return structuredClone(document); + }, + }; +} + +function experiment(): ExperimentDocument { + const now = new Date("2026-01-01T00:00:00.000Z"); + return { + _id: "experiment-1", + experimentId: "experiment-1", + projectId: "project-1", + metadata: { name: "Experiment" }, + storageProfileVersion: EXPERIMENT_STORAGE_PROFILE_VERSION, + stateVersion: 2, + revision: { + experimentRevisionId: "revision-1", + revisionNumber: 1, + memberCount: 1, + membershipFingerprint: "membership", + definitionFingerprint: "definition", + createdAt: now, + }, + execution: { + experimentExecutionId: "execution-1", + attemptNumber: 1, + version: 1, + requests: { + storage: "inline", + entryCount: 1, + payloadFingerprint: "payload", + entries: [ + { + requestId: "request-1", + runId: "run-1", + dependencies: [], + blockers: [], + }, + ], + }, + vectorFingerprint: "vector", + handlerSummary: { + report: { status: "queued", version: 1, updatedAt: now }, + }, + blocking: [], + createdAt: now, + updatedAt: now, + }, + createdAt: now, + updatedAt: now, + finalizedAt: now, + }; +} + +describe("ExperimentStore CAS contracts", () => { + it("allows exactly one winner in a writer-freezer race", async () => { + const experiments = atomicCollection(experiment()); + const store = new ExperimentStore({ + experiments: + experiments as unknown as Collection, + executions: + {} as Collection, + chunks: {} as Collection, + }); + + const [writer, freezer] = await Promise.all([ + store.claimHandler({ + projectId: "project-1", + experimentId: "experiment-1", + experimentExecutionId: "execution-1", + expectedExecutionVersion: 1, + handlerId: "report", + handlerVersion: 1, + }), + store.freezeCurrent({ + projectId: "project-1", + experimentId: "experiment-1", + experimentExecutionId: "execution-1", + expectedExecutionVersion: 1, + }), + ]); + + expect([writer, freezer].filter(Boolean)).toHaveLength(1); + expect(experiments.current().execution.version).toBe(2); + expect(experiments.current().stateVersion).toBe(3); + }); + + it("requires project, execution identity, and version on claims", async () => { + const experiments = atomicCollection(experiment()); + const store = new ExperimentStore({ + experiments: + experiments as unknown as Collection, + executions: + {} as Collection, + chunks: {} as Collection, + }); + await expect( + store.claimHandler({ + projectId: "wrong-project", + experimentId: "experiment-1", + experimentExecutionId: "execution-1", + expectedExecutionVersion: 1, + handlerId: "report", + handlerVersion: 1, + }), + ).resolves.toBeNull(); + await expect( + store.claimHandler({ + projectId: "project-1", + experimentId: "experiment-1", + experimentExecutionId: "wrong-execution", + expectedExecutionVersion: 1, + handlerId: "report", + handlerVersion: 1, + }), + ).resolves.toBeNull(); + }); +}); diff --git a/packages/shared/src/experiments/experiment-store.ts b/packages/shared/src/experiments/experiment-store.ts new file mode 100644 index 000000000..43b13ca7f --- /dev/null +++ b/packages/shared/src/experiments/experiment-store.ts @@ -0,0 +1,683 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import type { Collection, Document } from "mongodb"; +import { FixedPayloadStore } from "./fixed-payload-store.js"; +import { + ExperimentDocumentSchema, + ExperimentExecutionHistoryDocumentSchema, + ExperimentExecutionSchema, + ExperimentMetadataSchema, + ExperimentRequestStateSchema, + ExperimentRevisionSchema, +} from "./schemas.js"; +import { fingerprintExperimentPayload } from "./routing.js"; +import { + EXPERIMENT_STORAGE_PROFILE_VERSION, + type ExperimentDocument, + type ExperimentExecution, + type ExperimentExecutionHistoryDocument, + type ExperimentHandlerStatus, + type ExperimentMetadata, + type ExperimentPage, + type ExperimentRequestState, + type ExperimentRevision, + type FixedPayload, +} from "./types.js"; + +export interface ExperimentCollections { + experiments: Collection; + executions: Collection; + chunks: Collection; +} + +export interface CreateExperimentInput { + experimentId: string; + projectId: string; + metadata: ExperimentMetadata; + revision: ExperimentRevision; + experimentExecutionId: string; + requests: readonly ExperimentRequestState[]; + handlerSummary?: ExperimentExecution["handlerSummary"]; + blocking?: ExperimentExecution["blocking"]; + now?: Date; +} + +export interface RolloverExperimentInput { + projectId: string; + experimentId: string; + expectedExperimentExecutionId: string; + expectedExecutionVersion: number; + nextExperimentExecutionId: string; + requests: readonly ExperimentRequestState[]; + reason: "rollover" | "retry"; + now?: Date; +} + +function parseExperiment(value: unknown): ExperimentDocument { + return ExperimentDocumentSchema.parse(value) as ExperimentDocument; +} + +function parseExecution(value: unknown): ExperimentExecution { + return ExperimentExecutionSchema.parse(value) as ExperimentExecution; +} + +function parseHistory(value: unknown): ExperimentExecutionHistoryDocument { + return ExperimentExecutionHistoryDocumentSchema.parse( + value, + ) as ExperimentExecutionHistoryDocument; +} + +function assertHandlerId(handlerId: string): void { + if ( + handlerId.length === 0 || + handlerId.length > 200 || + handlerId.includes(".") || + handlerId.startsWith("$") + ) { + throw new Error(`Invalid experiment handler id '${handlerId}'`); + } +} + +function comparable(value: unknown): string { + return JSON.stringify(value, (_key, item: unknown) => + item instanceof Date ? item.toISOString() : item, + ); +} + +export class ExperimentStore { + private readonly payloads: FixedPayloadStore; + + constructor(private readonly collections: ExperimentCollections) { + this.payloads = new FixedPayloadStore(collections.chunks); + } + + async createPending(input: CreateExperimentInput): Promise { + const now = input.now ?? new Date(); + const metadata = ExperimentMetadataSchema.parse( + input.metadata, + ) as ExperimentMetadata; + const revision = ExperimentRevisionSchema.parse( + input.revision, + ) as ExperimentRevision; + const requests = input.requests.map((request) => + ExperimentRequestStateSchema.parse(request), + ) as ExperimentRequestState[]; + if (revision.memberCount !== requests.length) { + throw new Error( + `Revision memberCount ${revision.memberCount} does not match request count ${requests.length}`, + ); + } + + const identity = { + projectId: input.projectId, + experimentId: input.experimentId, + ownerId: input.experimentExecutionId, + generation: 1, + }; + const shell = (payload: FixedPayload): object => ({ + _id: input.experimentId, + experimentId: input.experimentId, + projectId: input.projectId, + metadata, + storageProfileVersion: EXPERIMENT_STORAGE_PROFILE_VERSION, + stateVersion: 1, + revision, + execution: { + experimentExecutionId: input.experimentExecutionId, + attemptNumber: 1, + version: 1, + requests: payload, + vectorFingerprint: fingerprintExperimentPayload(requests), + handlerSummary: input.handlerSummary ?? {}, + blocking: input.blocking ?? [], + createdAt: now, + updatedAt: now, + }, + createdAt: now, + updatedAt: now, + }); + const payload = await this.payloads.prepareRequests({ + identity, + entries: requests, + inlineDocument: shell, + now, + }); + const document = parseExperiment(shell(payload)); + await this.collections.experiments.updateOne( + { _id: document._id } as Document, + { $setOnInsert: document } as Document, + { upsert: true }, + ); + const raw: unknown = await this.collections.experiments.findOne({ + _id: document._id, + } as Document); + if (!raw) { + throw new Error(`Experiment ${document.experimentId} was not persisted`); + } + const persisted = parseExperiment(raw); + if ( + persisted.projectId !== document.projectId || + persisted.execution.experimentExecutionId !== + document.execution.experimentExecutionId || + persisted.execution.vectorFingerprint !== + document.execution.vectorFingerprint || + persisted.revision.experimentRevisionId !== + document.revision.experimentRevisionId || + persisted.revision.revisionNumber !== document.revision.revisionNumber || + persisted.revision.membershipFingerprint !== + document.revision.membershipFingerprint || + persisted.revision.definitionFingerprint !== + document.revision.definitionFingerprint || + persisted.storageProfileVersion !== EXPERIMENT_STORAGE_PROFILE_VERSION + ) { + throw new Error( + `Experiment ${document.experimentId} already exists with different immutable identity`, + ); + } + return persisted; + } + + async finalizeCreation(input: { + projectId: string; + experimentId: string; + expectedExperimentExecutionId: string; + expectedStateVersion: number; + now?: Date; + }): Promise { + const current = await this.getRaw(input.projectId, input.experimentId); + if ( + !current || + current.execution.experimentExecutionId !== + input.expectedExperimentExecutionId + ) { + return null; + } + if (current.finalizedAt) return current; + if (current.stateVersion !== input.expectedStateVersion) return null; + await this.payloads.verifyCompleteSet( + this.executionIdentity(current), + current.execution.requests, + ); + const now = input.now ?? new Date(); + const updated = await this.collections.experiments.findOneAndUpdate( + { + _id: input.experimentId, + projectId: input.projectId, + stateVersion: input.expectedStateVersion, + "execution.experimentExecutionId": + input.expectedExperimentExecutionId, + finalizedAt: { $exists: false }, + } as Document, + { + $set: { finalizedAt: now, updatedAt: now }, + $inc: { stateVersion: 1 }, + } as Document, + { returnDocument: "after" }, + ); + if (updated) return parseExperiment(updated); + const raced = await this.getRaw(input.projectId, input.experimentId); + return raced?.finalizedAt ? raced : null; + } + + async get( + projectId: string, + experimentId: string, + ): Promise { + const raw: unknown = await this.collections.experiments.findOne({ + _id: experimentId, + projectId, + finalizedAt: { $exists: true }, + } as Document); + return raw ? parseExperiment(raw) : null; + } + + async listPage(input: { + projectId: string; + limit?: number; + afterExperimentId?: string; + }): Promise { + const limit = Math.min(Math.max(input.limit ?? 50, 1), 100); + const filter: Document = { + projectId: input.projectId, + finalizedAt: { $exists: true }, + ...(input.afterExperimentId + ? { _id: { $gt: input.afterExperimentId } } + : {}), + }; + const raw = await this.collections.experiments + .find(filter) + .sort({ _id: 1 }) + .limit(limit + 1) + .toArray(); + const parsed = raw.map(parseExperiment); + const hasMore = parsed.length > limit; + const experiments = parsed.slice(0, limit); + return { + experiments, + ...(hasMore + ? { nextCursor: experiments.at(-1)?.experimentId } + : {}), + }; + } + + async getExecution(input: { + projectId: string; + experimentId: string; + experimentExecutionId: string; + }): Promise { + const experiment = await this.get(input.projectId, input.experimentId); + if ( + experiment?.execution.experimentExecutionId === + input.experimentExecutionId + ) { + return experiment.execution; + } + const raw: unknown = await this.collections.executions.findOne({ + _id: input.experimentExecutionId, + projectId: input.projectId, + experimentId: input.experimentId, + } as Document); + return raw ? parseHistory(raw) : null; + } + + async listExecutionHistory(input: { + projectId: string; + experimentId: string; + limit?: number; + }): Promise { + const limit = Math.min(Math.max(input.limit ?? 50, 1), 100); + const raw = await this.collections.executions + .find({ + projectId: input.projectId, + experimentId: input.experimentId, + } as Document) + .sort({ attemptNumber: -1 }) + .limit(limit) + .toArray(); + return raw.map(parseHistory); + } + + async claimHandler(input: { + projectId: string; + experimentId: string; + experimentExecutionId: string; + expectedExecutionVersion: number; + handlerId: string; + handlerVersion: number; + now?: Date; + }): Promise { + assertHandlerId(input.handlerId); + const now = input.now ?? new Date(); + const path = `execution.handlerSummary.${input.handlerId}`; + const updated = await this.collections.experiments.findOneAndUpdate( + { + _id: input.experimentId, + projectId: input.projectId, + finalizedAt: { $exists: true }, + "execution.experimentExecutionId": + input.experimentExecutionId, + "execution.version": input.expectedExecutionVersion, + "execution.frozenAt": { $exists: false }, + "execution.rollover": { $exists: false }, + [`${path}.status`]: "queued", + [`${path}.version`]: input.handlerVersion, + } as Document, + { + $set: { + [path]: { + status: "processing", + version: input.handlerVersion, + updatedAt: now, + }, + "execution.startedAt": now, + "execution.updatedAt": now, + updatedAt: now, + }, + $inc: { "execution.version": 1, stateVersion: 1 }, + } as Document, + { returnDocument: "after" }, + ); + return updated ? parseExperiment(updated) : null; + } + + async completeHandler(input: { + projectId: string; + experimentId: string; + experimentExecutionId: string; + expectedExecutionVersion: number; + handlerId: string; + handlerVersion: number; + status: Extract; + error?: string; + now?: Date; + }): Promise { + assertHandlerId(input.handlerId); + const now = input.now ?? new Date(); + const path = `execution.handlerSummary.${input.handlerId}`; + const updated = await this.collections.experiments.findOneAndUpdate( + { + _id: input.experimentId, + projectId: input.projectId, + "execution.experimentExecutionId": + input.experimentExecutionId, + "execution.version": input.expectedExecutionVersion, + "execution.rollover": { $exists: false }, + "execution.frozenAt": { $exists: false }, + [`${path}.status`]: "processing", + [`${path}.version`]: input.handlerVersion, + } as Document, + { + $set: { + [path]: { + status: input.status, + version: input.handlerVersion, + updatedAt: now, + ...(input.error ? { error: input.error } : {}), + }, + "execution.updatedAt": now, + "execution.finishedAt": now, + updatedAt: now, + }, + $inc: { "execution.version": 1, stateVersion: 1 }, + } as Document, + { returnDocument: "after" }, + ); + return updated ? parseExperiment(updated) : null; + } + + async freezeCurrent(input: { + projectId: string; + experimentId: string; + experimentExecutionId: string; + expectedExecutionVersion: number; + now?: Date; + }): Promise { + const now = input.now ?? new Date(); + const updated = await this.collections.experiments.findOneAndUpdate( + { + _id: input.experimentId, + projectId: input.projectId, + "execution.experimentExecutionId": + input.experimentExecutionId, + "execution.version": input.expectedExecutionVersion, + "execution.frozenAt": { $exists: false }, + "execution.rollover": { $exists: false }, + } as Document, + { + $set: { + "execution.frozenAt": now, + "execution.updatedAt": now, + updatedAt: now, + }, + $inc: { "execution.version": 1, stateVersion: 1 }, + } as Document, + { returnDocument: "after" }, + ); + return updated ? parseExperiment(updated) : null; + } + + async archiveCurrent(input: { + projectId: string; + experimentId: string; + experimentExecutionId: string; + now?: Date; + }): Promise { + const experiment = await this.getRaw(input.projectId, input.experimentId); + if ( + !experiment || + experiment.execution.experimentExecutionId !== + input.experimentExecutionId || + !experiment.execution.frozenAt + ) { + return null; + } + return this.archive(experiment, input.now ?? new Date()); + } + + async rollover(input: RolloverExperimentInput): Promise { + const experiment = await this.getRaw(input.projectId, input.experimentId); + if ( + !experiment || + experiment.execution.experimentExecutionId !== + input.expectedExperimentExecutionId || + experiment.execution.version !== input.expectedExecutionVersion || + !experiment.execution.frozenAt + ) { + return null; + } + const now = input.now ?? new Date(); + const requests = input.requests.map((request) => + ExperimentRequestStateSchema.parse(request), + ) as ExperimentRequestState[]; + const generation = experiment.execution.attemptNumber + 1; + const payload = await this.payloads.prepareRequests({ + identity: { + projectId: input.projectId, + experimentId: input.experimentId, + ownerId: input.nextExperimentExecutionId, + generation, + }, + entries: requests, + inlineDocument: (candidate) => ({ + ...experiment, + execution: this.nextExecution( + experiment.execution, + input.nextExperimentExecutionId, + candidate, + requests, + now, + ), + }), + now, + }); + const nextExecution = this.nextExecution( + experiment.execution, + input.nextExperimentExecutionId, + payload, + requests, + now, + ); + const claimed = await this.collections.experiments.findOneAndUpdate( + { + _id: input.experimentId, + projectId: input.projectId, + "execution.experimentExecutionId": + input.expectedExperimentExecutionId, + "execution.version": input.expectedExecutionVersion, + "execution.frozenAt": { $exists: true }, + "execution.rollover": { $exists: false }, + } as Document, + { + $set: { + "execution.rollover": { + nextExecution, + reason: input.reason, + claimedAt: now, + }, + "execution.updatedAt": now, + updatedAt: now, + }, + $inc: { "execution.version": 1, stateVersion: 1 }, + } as Document, + { returnDocument: "after" }, + ); + if (!claimed) return null; + return this.repairRollover(input.projectId, input.experimentId); + } + + async retryCurrent(input: Omit): Promise { + const experiment = await this.getRaw(input.projectId, input.experimentId); + if ( + !experiment || + experiment.execution.experimentExecutionId !== + input.expectedExperimentExecutionId + ) { + return null; + } + const requests = await this.payloads.readRequests( + this.executionIdentity(experiment), + experiment.execution.requests, + ); + return this.rollover({ ...input, requests, reason: "retry" }); + } + + async discardStale(input: { + projectId: string; + experimentId: string; + experimentExecutionId: string; + expectedExecutionVersion: number; + reason: string; + now?: Date; + }): Promise { + const now = input.now ?? new Date(); + const updated = await this.collections.experiments.findOneAndUpdate( + { + _id: input.experimentId, + projectId: input.projectId, + "execution.experimentExecutionId": + input.experimentExecutionId, + "execution.version": input.expectedExecutionVersion, + "execution.rollover": { $exists: false }, + "execution.discardedAt": { $exists: false }, + } as Document, + { + $set: { + "execution.discardedAt": now, + "execution.discardReason": input.reason.slice(0, 2_048), + "execution.updatedAt": now, + updatedAt: now, + }, + $inc: { "execution.version": 1, stateVersion: 1 }, + } as Document, + { returnDocument: "after" }, + ); + return updated ? parseExperiment(updated) : null; + } + + async repairRollover( + projectId: string, + experimentId: string, + ): Promise { + const experiment = await this.getRaw(projectId, experimentId); + const rollover = experiment?.execution.rollover; + if (!experiment || !rollover) return experiment; + const next = parseExecution(rollover.nextExecution); + await this.payloads.verifyCompleteSet( + { + projectId, + experimentId, + ownerId: next.experimentExecutionId, + generation: next.attemptNumber, + }, + next.requests, + ); + await this.archive(experiment, rollover.claimedAt); + const now = new Date(); + const updated = await this.collections.experiments.findOneAndUpdate( + { + _id: experimentId, + projectId, + "execution.experimentExecutionId": + experiment.execution.experimentExecutionId, + "execution.rollover.nextExecution.experimentExecutionId": + next.experimentExecutionId, + } as Document, + { + $set: { execution: next, updatedAt: now }, + $inc: { stateVersion: 1 }, + } as Document, + { returnDocument: "after" }, + ); + if (updated) return parseExperiment(updated); + return this.getRaw(projectId, experimentId); + } + + private async getRaw( + projectId: string, + experimentId: string, + ): Promise { + const raw: unknown = await this.collections.experiments.findOne({ + _id: experimentId, + projectId, + } as Document); + return raw ? parseExperiment(raw) : null; + } + + private executionIdentity(experiment: ExperimentDocument) { + return { + projectId: experiment.projectId, + experimentId: experiment.experimentId, + ownerId: experiment.execution.experimentExecutionId, + generation: experiment.execution.attemptNumber, + }; + } + + private nextExecution( + current: ExperimentExecution, + experimentExecutionId: string, + requests: FixedPayload, + entries: ExperimentRequestState[], + now: Date, + ): ExperimentExecution { + return { + experimentExecutionId, + attemptNumber: current.attemptNumber + 1, + version: 1, + requests, + vectorFingerprint: fingerprintExperimentPayload(entries), + handlerSummary: {}, + blocking: [], + createdAt: now, + updatedAt: now, + }; + } + + private async archive( + experiment: ExperimentDocument, + archivedAt: Date, + ): Promise { + const rollover = experiment.execution.rollover; + const { + rollover: _rollover, + ...execution + } = experiment.execution; + const history = parseHistory({ + ...execution, + _id: execution.experimentExecutionId, + experimentId: experiment.experimentId, + projectId: experiment.projectId, + storageProfileVersion: experiment.storageProfileVersion, + revision: experiment.revision, + archivedAt, + ...(rollover + ? { + supersededAt: rollover.claimedAt, + supersededByExperimentExecutionId: + rollover.nextExecution.experimentExecutionId, + supersededReason: rollover.reason, + } + : {}), + }); + await this.collections.executions.updateOne( + { _id: history._id } as Document, + { $setOnInsert: history } as Document, + { upsert: true }, + ); + const raw: unknown = await this.collections.executions.findOne({ + _id: history._id, + } as Document); + if (!raw) { + throw new Error( + `Experiment execution history ${history._id} was not persisted`, + ); + } + const persisted = parseHistory(raw); + if (comparable(persisted) !== comparable(history)) { + throw new Error( + `Experiment execution history ${history._id} is immutable and does not match`, + ); + } + return persisted; + } +} diff --git a/packages/shared/src/experiments/fixed-payload-store.test.ts b/packages/shared/src/experiments/fixed-payload-store.test.ts new file mode 100644 index 000000000..9339dbecb --- /dev/null +++ b/packages/shared/src/experiments/fixed-payload-store.test.ts @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import type { Collection, Document } from "mongodb"; +import { describe, expect, it } from "vitest"; +import { FixedPayloadStore } from "./fixed-payload-store.js"; +import type { ExperimentRequestState } from "./types.js"; + +function request(index: number): ExperimentRequestState { + return { + requestId: `request-${index}`, + runId: `run-${index}`, + dependencies: [], + blockers: [], + }; +} + +function chunkCollection(failAt?: number) { + const documents = new Map(); + let writes = 0; + return { + documents, + async updateOne( + filter: Document, + update: { $setOnInsert: Document }, + ) { + writes += 1; + if (writes === failAt) throw new Error("injected write failure"); + const id = String(filter._id); + if (!documents.has(id)) documents.set(id, structuredClone(update.$setOnInsert)); + return { matchedCount: 1, modifiedCount: 1 }; + }, + async findOne(filter: Document) { + return documents.get(String(filter._id)) ?? null; + }, + async deleteMany(filter: { _id: { $in: string[] } }) { + let deletedCount = 0; + for (const id of filter._id.$in) { + if (documents.delete(id)) deletedCount += 1; + } + return { deletedCount }; + }, + }; +} + +describe("FixedPayloadStore", () => { + const identity = { + projectId: "project-1", + experimentId: "experiment-1", + ownerId: "execution-1", + generation: 1, + }; + + it("has identical logical reads for inline and chunked payloads", async () => { + const entries = Array.from({ length: 60 }, (_, index) => request(index)); + const collection = chunkCollection(); + const store = new FixedPayloadStore( + collection as unknown as Collection, + ); + const inline = await store.prepareRequests({ + identity, + entries, + inlineDocument: (payload) => ({ payload }), + }); + expect(inline.storage).toBe("inline"); + expect(await store.readRequests(identity, inline)).toEqual(entries); + + const chunked = await store.prepareRequests({ + identity: { ...identity, ownerId: "execution-2", generation: 2 }, + entries, + inlineDocument: (payload) => ({ + payload, + padding: "x".repeat(256 * 1024), + }), + }); + expect(chunked.storage).toBe("chunked"); + expect( + await store.readRequests( + { ...identity, ownerId: "execution-2", generation: 2 }, + chunked, + ), + ).toEqual(entries); + }); + + it("fails before returning a publishable descriptor on a partial write", async () => { + const collection = chunkCollection(2); + const store = new FixedPayloadStore( + collection as unknown as Collection, + ); + await expect( + store.prepareRequests({ + identity, + entries: Array.from({ length: 100 }, (_, index) => ({ + ...request(index), + dependencies: [ + { + handlerId: "obs", + state: "ready", + error: "x".repeat(1_800), + }, + ], + })), + inlineDocument: (payload) => ({ + payload, + padding: "x".repeat(256 * 1024), + }), + }), + ).rejects.toThrow("injected write failure"); + expect(collection.documents.size).toBe(1); + }); + + it("rejects deterministic-id identity mismatches", async () => { + const collection = chunkCollection(); + const store = new FixedPayloadStore( + collection as unknown as Collection, + ); + const payload = await store.prepareRequests({ + identity, + entries: [request(1)], + inlineDocument: (value) => ({ + value, + padding: "x".repeat(256 * 1024), + }), + }); + expect(payload.storage).toBe("chunked"); + await expect( + store.readRequests({ ...identity, projectId: "other-project" }, payload), + ).rejects.toThrow(/identity mismatch/); + }); +}); diff --git a/packages/shared/src/experiments/fixed-payload-store.ts b/packages/shared/src/experiments/fixed-payload-store.ts new file mode 100644 index 000000000..9d7b91340 --- /dev/null +++ b/packages/shared/src/experiments/fixed-payload-store.ts @@ -0,0 +1,316 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import type { Collection, Document } from "mongodb"; +import { z } from "zod"; +import { selectFixedPayloadLayout } from "./layout.js"; +import { + ExperimentRequestStateSchema, +} from "./schemas.js"; +import { + computeExperimentChunkId, + fingerprintExperimentPayload, +} from "./routing.js"; +import { + EXPERIMENT_REQUEST_BUCKET_ASSIGNMENT_VERSION, + EXPERIMENT_STORAGE_PROFILE_VERSION, + type ExperimentRequestState, + type FixedPayload, +} from "./types.js"; + +interface ExperimentChunkDocument { + _id: string; + projectId: string; + experimentId: string; + kind: "requests"; + ownerId: string; + generation: number; + chunkIndex: number; + bucketCount: number; + storageProfileVersion: typeof EXPERIMENT_STORAGE_PROFILE_VERSION; + assignmentVersion: typeof EXPERIMENT_REQUEST_BUCKET_ASSIGNMENT_VERSION; + payloadFingerprint: string; + entries: Array<{ position: number; state: ExperimentRequestState }>; + createdAt: Date; +} + +const ExperimentChunkDocumentSchema = z + .object({ + _id: z.string().min(1), + projectId: z.string().min(1), + experimentId: z.string().min(1), + kind: z.literal("requests"), + ownerId: z.string().min(1), + generation: z.number().int().positive(), + chunkIndex: z.number().int().nonnegative(), + bucketCount: z.number().int().positive(), + storageProfileVersion: z.literal(EXPERIMENT_STORAGE_PROFILE_VERSION), + assignmentVersion: z.literal( + EXPERIMENT_REQUEST_BUCKET_ASSIGNMENT_VERSION, + ), + payloadFingerprint: z.string().min(1), + entries: z.array( + z + .object({ + position: z.number().int().nonnegative(), + state: ExperimentRequestStateSchema, + }) + .strict(), + ), + createdAt: z.coerce.date(), + }) + .strict(); + +export interface FixedPayloadIdentity { + projectId: string; + experimentId: string; + ownerId: string; + generation: number; +} + +function sameChunk( + left: ExperimentChunkDocument, + right: ExperimentChunkDocument, +): boolean { + return ( + left._id === right._id && + left.projectId === right.projectId && + left.experimentId === right.experimentId && + left.kind === right.kind && + left.ownerId === right.ownerId && + left.generation === right.generation && + left.chunkIndex === right.chunkIndex && + left.bucketCount === right.bucketCount && + left.storageProfileVersion === right.storageProfileVersion && + left.assignmentVersion === right.assignmentVersion && + left.payloadFingerprint === right.payloadFingerprint && + fingerprintExperimentPayload(left.entries) === + fingerprintExperimentPayload(right.entries) + ); +} + +export class FixedPayloadStore { + constructor( + private readonly chunks: Collection, + ) {} + + async prepareRequests(input: { + identity: FixedPayloadIdentity; + entries: readonly ExperimentRequestState[]; + inlineDocument: (payload: FixedPayload) => object; + now?: Date; + }): Promise> { + if (input.identity.generation < 1) { + throw new Error("Fixed payload generation must be positive"); + } + const entries = input.entries.map((entry) => + ExperimentRequestStateSchema.parse(entry), + ); + const payloadFingerprint = fingerprintExperimentPayload(entries); + const positionByRequestId = new Map( + entries.map((entry, position) => [entry.requestId, position]), + ); + const layout = selectFixedPayloadLayout({ + entries, + inlineDocument: (inlineEntries) => + input.inlineDocument({ + storage: "inline", + entryCount: inlineEntries.length, + payloadFingerprint, + entries: inlineEntries, + }), + chunkDocument: (chunkIndex, bucketCount, bucketEntries) => + this.chunkDocument({ + identity: input.identity, + chunkIndex, + bucketCount, + entries: bucketEntries.map((state) => ({ + position: positionByRequestId.get(state.requestId)!, + state, + })), + payloadFingerprint, + createdAt: input.now ?? new Date(0), + }), + }); + if (layout.storage === "inline") { + return { + storage: "inline", + entryCount: entries.length, + payloadFingerprint, + entries, + }; + } + + const createdAt = input.now ?? new Date(); + const documents = layout.buckets.map((bucketEntries, chunkIndex) => + this.chunkDocument({ + identity: input.identity, + chunkIndex, + bucketCount: layout.bucketCount, + entries: bucketEntries.map((state) => ({ + position: positionByRequestId.get(state.requestId)!, + state, + })), + payloadFingerprint, + createdAt, + }), + ); + for (const document of documents) { + await this.chunks.updateOne( + { _id: document._id } as Document, + { $setOnInsert: document } as Document, + { upsert: true }, + ); + } + await this.assertDocuments(documents); + return { + storage: "chunked", + entryCount: entries.length, + payloadFingerprint, + assignmentVersion: EXPERIMENT_REQUEST_BUCKET_ASSIGNMENT_VERSION, + bucketCount: layout.bucketCount, + chunkIds: documents.map((document) => document._id), + }; + } + + async readRequests( + identity: FixedPayloadIdentity, + payload: FixedPayload, + ): Promise { + if (payload.storage === "inline") { + const entries = payload.entries.map((entry) => + ExperimentRequestStateSchema.parse(entry), + ); + this.assertPayloadFingerprint(payload, entries); + return entries; + } + const documents: ExperimentChunkDocument[] = []; + for (const chunkId of payload.chunkIds) { + const raw: unknown = await this.chunks.findOne({ _id: chunkId } as Document); + if (!raw) throw new Error(`Missing experiment chunk ${chunkId}`); + const document = ExperimentChunkDocumentSchema.parse( + raw, + ) as ExperimentChunkDocument; + this.assertIdentity(document, identity, payload); + documents.push(document); + } + documents.sort((left, right) => left.chunkIndex - right.chunkIndex); + const positioned = documents + .flatMap((document) => document.entries) + .sort((left, right) => left.position - right.position); + if ( + positioned.some((entry, index) => entry.position !== index) + ) { + throw new Error("Experiment payload positions are incomplete or duplicated"); + } + const entries = positioned.map((entry) => entry.state); + if (entries.length !== payload.entryCount) { + throw new Error( + `Experiment payload expected ${payload.entryCount} entries but loaded ${entries.length}`, + ); + } + this.assertPayloadFingerprint(payload, entries); + return entries; + } + + async verifyCompleteSet( + identity: FixedPayloadIdentity, + payload: FixedPayload, + ): Promise { + await this.readRequests(identity, payload); + } + + async discardUnpublished( + payload: FixedPayload, + ): Promise { + if (payload.storage === "inline") return 0; + const result = await this.chunks.deleteMany({ + _id: { $in: payload.chunkIds }, + } as Document); + return result.deletedCount; + } + + private chunkDocument(input: { + identity: FixedPayloadIdentity; + chunkIndex: number; + bucketCount: number; + entries: Array<{ position: number; state: ExperimentRequestState }>; + payloadFingerprint: string; + createdAt: Date; + }): ExperimentChunkDocument { + return { + _id: computeExperimentChunkId({ + ...input.identity, + kind: "requests", + chunkIndex: input.chunkIndex, + }), + ...input.identity, + kind: "requests", + chunkIndex: input.chunkIndex, + bucketCount: input.bucketCount, + storageProfileVersion: EXPERIMENT_STORAGE_PROFILE_VERSION, + assignmentVersion: EXPERIMENT_REQUEST_BUCKET_ASSIGNMENT_VERSION, + payloadFingerprint: input.payloadFingerprint, + entries: input.entries, + createdAt: input.createdAt, + }; + } + + private async assertDocuments( + expected: ExperimentChunkDocument[], + ): Promise { + for (const expectedDocument of expected) { + const raw: unknown = await this.chunks.findOne({ + _id: expectedDocument._id, + } as Document); + if (!raw) { + throw new Error( + `Experiment chunk ${expectedDocument._id} was not persisted`, + ); + } + const actual = ExperimentChunkDocumentSchema.parse( + raw, + ) as ExperimentChunkDocument; + if (!sameChunk(actual, expectedDocument)) { + throw new Error( + `Experiment chunk ${expectedDocument._id} identity or content mismatch`, + ); + } + } + } + + private assertIdentity( + document: ExperimentChunkDocument, + identity: FixedPayloadIdentity, + payload: Extract, { storage: "chunked" }>, + ): void { + const expectedId = computeExperimentChunkId({ + ...identity, + kind: "requests", + chunkIndex: document.chunkIndex, + }); + if ( + document._id !== expectedId || + document.projectId !== identity.projectId || + document.experimentId !== identity.experimentId || + document.ownerId !== identity.ownerId || + document.generation !== identity.generation || + document.bucketCount !== payload.bucketCount || + document.assignmentVersion !== payload.assignmentVersion || + document.payloadFingerprint !== payload.payloadFingerprint + ) { + throw new Error(`Experiment chunk ${document._id} identity mismatch`); + } + } + + private assertPayloadFingerprint( + payload: FixedPayload, + entries: ExperimentRequestState[], + ): void { + if ( + fingerprintExperimentPayload(entries) !== payload.payloadFingerprint + ) { + throw new Error("Experiment payload fingerprint mismatch"); + } + } +} diff --git a/packages/shared/src/experiments/index.ts b/packages/shared/src/experiments/index.ts new file mode 100644 index 000000000..acdbd6b87 --- /dev/null +++ b/packages/shared/src/experiments/index.ts @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +export * from "./types.js"; +export * from "./schemas.js"; +export * from "./routing.js"; +export * from "./layout.js"; +export * from "./fixed-payload-store.js"; +export * from "./experiment-store.js"; diff --git a/packages/shared/src/experiments/layout.test.ts b/packages/shared/src/experiments/layout.test.ts new file mode 100644 index 000000000..41db38862 --- /dev/null +++ b/packages/shared/src/experiments/layout.test.ts @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { describe, expect, it } from "vitest"; +import { + EXPERIMENT_STORAGE_PROFILE, + bsonSize, + selectFixedPayloadLayout, +} from "./layout.js"; +import type { ExperimentRequestState } from "./types.js"; + +function request(index: number, error = ""): ExperimentRequestState { + return { + requestId: `request-${index}`, + runId: `run-${index}`, + dependencies: [ + { + handlerId: "observations", + state: "ready", + ...(error ? { error } : {}), + }, + ], + blockers: [], + }; +} + +describe("experiment fixed payload layout", () => { + it("chooses inline at the exact target and chunks one byte above it", () => { + const entries = [request(1)]; + const base = bsonSize({ entries, padding: "" }); + const exactPadding = "x".repeat( + EXPERIMENT_STORAGE_PROFILE.targetDocumentBytes - base, + ); + const exact = selectFixedPayloadLayout({ + entries, + inlineDocument: (value) => ({ entries: value, padding: exactPadding }), + chunkDocument: (chunkIndex, bucketCount, value) => ({ + chunkIndex, + bucketCount, + entries: value, + }), + }); + expect(exact.bsonBytes[0]).toBe( + EXPERIMENT_STORAGE_PROFILE.targetDocumentBytes, + ); + expect(exact.storage).toBe("inline"); + + const adjacent = selectFixedPayloadLayout({ + entries, + inlineDocument: (value) => ({ + entries: value, + padding: `${exactPadding}x`, + }), + chunkDocument: (chunkIndex, bucketCount, value) => ({ + chunkIndex, + bucketCount, + entries: value, + }), + }); + expect(adjacent.storage).toBe("chunked"); + expect(adjacent.bucketCount).toBe(1); + }); + + it("selects the first safe bucket count after recomputing distribution", () => { + const entries = Array.from({ length: 120 }, (_, index) => + request(index, "x".repeat(3_000)), + ); + const layout = selectFixedPayloadLayout({ + entries, + inlineDocument: (value) => ({ + entries: value, + padding: "x".repeat(EXPERIMENT_STORAGE_PROFILE.targetDocumentBytes), + }), + chunkDocument: (chunkIndex, bucketCount, value) => ({ + chunkIndex, + bucketCount, + entries: value, + }), + }); + expect(layout.storage).toBe("chunked"); + // Three is the count-only lower bound; the hash distribution overloads + // one bucket, so four is the first count that satisfies the BSON budget. + expect(layout.bucketCount).toBe(4); + expect(layout.bsonBytes.every((size) => size < 256 * 1024)).toBe(true); + }); + + it("rejects oversized entries and duplicate request ids", () => { + const oversized = request(1, "x".repeat(4_096)); + expect(() => + selectFixedPayloadLayout({ + entries: [oversized], + inlineDocument: (entries) => ({ entries }), + chunkDocument: (chunkIndex, bucketCount, entries) => ({ + chunkIndex, + bucketCount, + entries, + }), + }), + ).toThrow(/maximum/); + expect(() => + selectFixedPayloadLayout({ + entries: [request(1), request(1)], + inlineDocument: (entries) => ({ entries }), + chunkDocument: (chunkIndex, bucketCount, entries) => ({ + chunkIndex, + bucketCount, + entries, + }), + }), + ).toThrow(/Duplicate/); + }); +}); diff --git a/packages/shared/src/experiments/layout.ts b/packages/shared/src/experiments/layout.ts new file mode 100644 index 000000000..c2ce92b07 --- /dev/null +++ b/packages/shared/src/experiments/layout.ts @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { BSON } from "mongodb"; +import { assignExperimentRequestBucket } from "./routing.js"; +import type { ExperimentRequestState } from "./types.js"; + +export const EXPERIMENT_STORAGE_PROFILE = Object.freeze({ + maxDocumentBytes: 2 * 1024 * 1024, + targetDocumentBytes: 256 * 1024, + maxRequestEntryBytes: 4 * 1024, + metadataReserveBytes: (256 * 1024) / 16, + loadFactor: 0.8, + maxBucketSearch: 65_536, +}); + +export interface FixedPayloadLayout { + storage: "inline" | "chunked"; + bucketCount: number; + buckets: ExperimentRequestState[][]; + bsonBytes: number[]; +} + +export function bsonSize(value: object): number { + return BSON.calculateObjectSize(value); +} + +function payloadBudgetBytes(): number { + return Math.floor( + (EXPERIMENT_STORAGE_PROFILE.targetDocumentBytes - + EXPERIMENT_STORAGE_PROFILE.metadataReserveBytes) * + EXPERIMENT_STORAGE_PROFILE.loadFactor, + ); +} + +export function selectFixedPayloadLayout(input: { + entries: readonly ExperimentRequestState[]; + inlineDocument: (entries: ExperimentRequestState[]) => object; + chunkDocument: ( + chunkIndex: number, + bucketCount: number, + entries: ExperimentRequestState[], + ) => object; +}): FixedPayloadLayout { + const entries = input.entries.map((entry) => structuredClone(entry)); + const ids = new Set(); + for (const entry of entries) { + if (ids.has(entry.requestId)) { + throw new Error(`Duplicate experiment requestId '${entry.requestId}'`); + } + ids.add(entry.requestId); + const bytes = bsonSize({ + position: Number.MAX_SAFE_INTEGER, + state: entry, + }); + if (bytes > EXPERIMENT_STORAGE_PROFILE.maxRequestEntryBytes) { + throw new Error( + `Experiment request ${entry.requestId} is ${bytes} bytes; maximum is ${EXPERIMENT_STORAGE_PROFILE.maxRequestEntryBytes}`, + ); + } + } + + const inlineBytes = bsonSize(input.inlineDocument(entries)); + if ( + inlineBytes <= EXPERIMENT_STORAGE_PROFILE.targetDocumentBytes && + inlineBytes <= EXPERIMENT_STORAGE_PROFILE.maxDocumentBytes + ) { + return { + storage: "inline", + bucketCount: 0, + buckets: [entries], + bsonBytes: [inlineBytes], + }; + } + if (entries.length === 0) { + throw new Error("An empty fixed payload must be stored inline"); + } + + const budget = payloadBudgetBytes(); + const maxEntriesPerBucket = Math.max( + 1, + Math.floor( + budget / EXPERIMENT_STORAGE_PROFILE.maxRequestEntryBytes, + ), + ); + const firstBucketCount = Math.ceil(entries.length / maxEntriesPerBucket); + const lastBucketCount = Math.min( + entries.length, + EXPERIMENT_STORAGE_PROFILE.maxBucketSearch, + ); + + for ( + let bucketCount = firstBucketCount; + bucketCount <= lastBucketCount; + bucketCount += 1 + ) { + const buckets = Array.from( + { length: bucketCount }, + () => [] as ExperimentRequestState[], + ); + for (const entry of entries) { + buckets[ + assignExperimentRequestBucket(entry.requestId, bucketCount) + ]!.push(entry); + } + const bsonBytes = buckets.map((bucket, chunkIndex) => + bsonSize(input.chunkDocument(chunkIndex, bucketCount, bucket)), + ); + if ( + buckets.every((bucket) => bucket.length <= maxEntriesPerBucket) && + bsonBytes.every( + (bytes) => + bytes <= budget && + bytes <= EXPERIMENT_STORAGE_PROFILE.maxDocumentBytes, + ) + ) { + return { storage: "chunked", bucketCount, buckets, bsonBytes }; + } + } + throw new Error( + `No safe experiment request layout found within ${EXPERIMENT_STORAGE_PROFILE.maxBucketSearch} buckets`, + ); +} diff --git a/packages/shared/src/experiments/routing.test.ts b/packages/shared/src/experiments/routing.test.ts new file mode 100644 index 000000000..4c696f0f1 --- /dev/null +++ b/packages/shared/src/experiments/routing.test.ts @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { describe, expect, it } from "vitest"; +import { + assignExperimentRequestBucket, + computeExperimentChunkId, +} from "./routing.js"; + +describe("experiment routing", () => { + it("matches the sha256-mod-v1 golden assignment", () => { + expect(assignExperimentRequestBucket("request-123", 17)).toBe(15); + expect(assignExperimentRequestBucket("request-123", 17)).toBe(15); + }); + + it("matches the deterministic canonical tuple chunk id", () => { + expect( + computeExperimentChunkId({ + projectId: "p", + experimentId: "e", + kind: "requests", + ownerId: "x", + generation: 2, + chunkIndex: 3, + }), + ).toBe("ec_v1_nFlNA4koLtvQvUwoexRibIpfKx89eMnNfsFCPFXfIkU"); + }); + + it("rejects invalid bucket counts", () => { + expect(() => assignExperimentRequestBucket("request-1", 0)).toThrow( + /positive safe integer/, + ); + }); +}); diff --git a/packages/shared/src/experiments/routing.ts b/packages/shared/src/experiments/routing.ts new file mode 100644 index 000000000..bd9afd8fe --- /dev/null +++ b/packages/shared/src/experiments/routing.ts @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { createHash } from "node:crypto"; + +const REQUEST_BUCKET_HASH_PREFIX = "experiment-request-bucket:v1\0"; + +function sha256(value: string): Buffer { + return createHash("sha256").update(value, "utf8").digest(); +} + +export function assignExperimentRequestBucket( + requestId: string, + bucketCount: number, +): number { + if (!Number.isSafeInteger(bucketCount) || bucketCount <= 0) { + throw new Error("bucketCount must be a positive safe integer"); + } + const digest = sha256(`${REQUEST_BUCKET_HASH_PREFIX}${requestId}`); + let unsignedBigEndian = 0n; + for (const byte of digest) { + unsignedBigEndian = (unsignedBigEndian << 8n) + BigInt(byte); + } + return Number(unsignedBigEndian % BigInt(bucketCount)); +} + +export function computeExperimentChunkId(input: { + projectId: string; + experimentId: string; + kind: string; + ownerId: string; + generation: number; + chunkIndex: number; +}): string { + const canonical = JSON.stringify([ + "sha256-v1", + input.projectId, + input.experimentId, + input.kind, + input.ownerId, + input.generation, + input.chunkIndex, + ]); + return `ec_v1_${sha256(canonical).toString("base64url")}`; +} + +export function fingerprintExperimentPayload(value: unknown): string { + return createHash("sha256") + .update(JSON.stringify(value), "utf8") + .digest("base64url"); +} diff --git a/packages/shared/src/experiments/schemas.test.ts b/packages/shared/src/experiments/schemas.test.ts new file mode 100644 index 000000000..9a4b6fb2d --- /dev/null +++ b/packages/shared/src/experiments/schemas.test.ts @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { describe, expect, it } from "vitest"; +import { + ExperimentDocumentSchema, + ExperimentRequestStateSchema, +} from "./schemas.js"; + +describe("experiment schemas", () => { + it("parses the bounded request leaf and rejects recursive or unknown data", () => { + expect( + ExperimentRequestStateSchema.parse({ + requestId: "request-1", + runId: "run-1", + dependencies: [{ handlerId: "obs", state: "ready" }], + blockers: [], + }), + ).toMatchObject({ requestId: "request-1", runId: "run-1" }); + expect(() => + ExperimentRequestStateSchema.parse({ + requestId: "request-1", + runId: "run-1", + dependencies: [], + blockers: [], + requests: [], + }), + ).toThrow(); + expect(() => + ExperimentRequestStateSchema.parse({ + requestId: "request-1", + runId: "run-1", + dependencies: [], + blockers: Array.from({ length: 33 }, () => ({ + handlerId: "obs", + reason: "dependency-blocked", + })), + }), + ).toThrow(); + }); + + it("rejects an unknown storage profile at the document boundary", () => { + expect(() => + ExperimentDocumentSchema.parse({ + _id: "experiment-1", + experimentId: "experiment-1", + projectId: "project-1", + metadata: { name: "Experiment" }, + storageProfileVersion: "future-profile", + stateVersion: 1, + revision: { + experimentRevisionId: "revision-1", + revisionNumber: 1, + memberCount: 0, + membershipFingerprint: "m", + definitionFingerprint: "d", + createdAt: new Date(), + }, + execution: { + experimentExecutionId: "execution-1", + attemptNumber: 1, + version: 1, + requests: { + storage: "inline", + entryCount: 0, + payloadFingerprint: "f", + entries: [], + }, + vectorFingerprint: "v", + handlerSummary: {}, + blocking: [], + createdAt: new Date(), + updatedAt: new Date(), + }, + createdAt: new Date(), + updatedAt: new Date(), + }), + ).toThrow(); + }); +}); diff --git a/packages/shared/src/experiments/schemas.ts b/packages/shared/src/experiments/schemas.ts new file mode 100644 index 000000000..8491cf493 --- /dev/null +++ b/packages/shared/src/experiments/schemas.ts @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { z } from "zod"; +import { + EXPERIMENT_REQUEST_BUCKET_ASSIGNMENT_VERSION, + EXPERIMENT_STORAGE_PROFILE_VERSION, +} from "./types.js"; + +const IdSchema = z.string().trim().min(1).max(200); +const ErrorSchema = z.string().max(2_048); + +export const ExperimentDependencyProjectionSchema = z + .object({ + handlerId: IdSchema, + state: z.enum(["waiting", "ready", "failed", "blocked"]), + version: z.number().int().nonnegative().optional(), + updatedAt: z.coerce.date().optional(), + error: ErrorSchema.optional(), + }) + .strict(); + +export const ExperimentBlockerSchema = z + .object({ + handlerId: IdSchema, + reason: z.enum([ + "request-missing", + "run-changed", + "dependency-not-ready", + "dependency-failed", + "dependency-blocked", + ]), + error: ErrorSchema.optional(), + }) + .strict(); + +export const ExperimentRequestStateSchema = z + .object({ + requestId: IdSchema, + runId: IdSchema, + dependencies: z.array(ExperimentDependencyProjectionSchema).max(32), + blockers: z.array(ExperimentBlockerSchema).max(32), + }) + .strict(); + +export const ExperimentMetadataSchema = z + .object({ + name: z.string().trim().min(1).max(256), + description: z.string().max(4_096).optional(), + tags: z.array(z.string().trim().min(1).max(64)).max(32).optional(), + createdBy: IdSchema.optional(), + }) + .strict(); + +export const ExperimentRevisionSchema = z + .object({ + experimentRevisionId: IdSchema, + revisionNumber: z.number().int().min(1), + memberCount: z.number().int().nonnegative(), + membershipFingerprint: IdSchema, + definitionFingerprint: IdSchema, + createdAt: z.coerce.date(), + }) + .strict(); + +export const ExperimentHandlerSummarySchema = z + .object({ + status: z.enum(["queued", "processing", "done", "failed"]), + version: z.number().int().nonnegative(), + updatedAt: z.coerce.date(), + error: ErrorSchema.optional(), + }) + .strict(); + +export const ExperimentFixedRequestPayloadSchema = z.discriminatedUnion( + "storage", + [ + z + .object({ + storage: z.literal("inline"), + entryCount: z.number().int().nonnegative(), + payloadFingerprint: IdSchema, + entries: z.array(ExperimentRequestStateSchema), + }) + .strict() + .refine((value) => value.entryCount === value.entries.length, { + message: "Inline entryCount must equal entries.length", + }), + z + .object({ + storage: z.literal("chunked"), + entryCount: z.number().int().positive(), + payloadFingerprint: IdSchema, + assignmentVersion: z.literal( + EXPERIMENT_REQUEST_BUCKET_ASSIGNMENT_VERSION, + ), + bucketCount: z.number().int().positive(), + chunkIds: z.array(IdSchema).min(1), + }) + .strict() + .refine((value) => value.bucketCount === value.chunkIds.length, { + message: "Chunked bucketCount must equal chunkIds.length", + }), + ], +); + +const ExperimentExecutionBaseSchema = z + .object({ + experimentExecutionId: IdSchema, + attemptNumber: z.number().int().min(1), + version: z.number().int().min(1), + requests: ExperimentFixedRequestPayloadSchema, + vectorFingerprint: IdSchema, + handlerSummary: z + .record(IdSchema, ExperimentHandlerSummarySchema) + .refine((value) => Object.keys(value).length <= 64, { + message: "handlerSummary is limited to 64 handlers", + }), + blocking: z.array(ExperimentBlockerSchema).max(32), + createdAt: z.coerce.date(), + updatedAt: z.coerce.date(), + startedAt: z.coerce.date().optional(), + finishedAt: z.coerce.date().optional(), + frozenAt: z.coerce.date().optional(), + discardedAt: z.coerce.date().optional(), + discardReason: z.string().max(2_048).optional(), + supersededAt: z.coerce.date().optional(), + supersededByExperimentExecutionId: IdSchema.optional(), + supersededReason: z.enum(["rollover", "retry"]).optional(), + }) + .strict(); + +export const ExperimentExecutionSchema: z.ZodType = ExperimentExecutionBaseSchema + .extend({ + rollover: z + .object({ + nextExecution: ExperimentExecutionBaseSchema, + reason: z.enum(["rollover", "retry"]), + claimedAt: z.coerce.date(), + }) + .strict() + .optional(), + }) + .strict(); + +export const ExperimentDocumentSchema = z + .object({ + _id: IdSchema, + experimentId: IdSchema, + projectId: IdSchema, + metadata: ExperimentMetadataSchema, + storageProfileVersion: z.literal(EXPERIMENT_STORAGE_PROFILE_VERSION), + stateVersion: z.number().int().min(1), + revision: ExperimentRevisionSchema, + execution: ExperimentExecutionSchema, + createdAt: z.coerce.date(), + updatedAt: z.coerce.date(), + finalizedAt: z.coerce.date().optional(), + }) + .strict(); + +export const ExperimentExecutionHistoryDocumentSchema = + ExperimentExecutionBaseSchema.extend({ + _id: IdSchema, + experimentId: IdSchema, + projectId: IdSchema, + storageProfileVersion: z.literal(EXPERIMENT_STORAGE_PROFILE_VERSION), + revision: ExperimentRevisionSchema, + archivedAt: z.coerce.date(), + }).strict(); diff --git a/packages/shared/src/experiments/types.ts b/packages/shared/src/experiments/types.ts new file mode 100644 index 000000000..e31b2f328 --- /dev/null +++ b/packages/shared/src/experiments/types.ts @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +export const EXPERIMENT_STORAGE_PROFILE_VERSION = "cosmos-mongo-2mb-v1" as const; +export const EXPERIMENT_REQUEST_BUCKET_ASSIGNMENT_VERSION = + "sha256-mod-v1" as const; + +export type ExperimentStorageProfileVersion = + typeof EXPERIMENT_STORAGE_PROFILE_VERSION; + +export interface InlineFixedPayload { + storage: "inline"; + entryCount: number; + payloadFingerprint: string; + entries: T[]; +} + +export interface ChunkedFixedPayload { + storage: "chunked"; + entryCount: number; + payloadFingerprint: string; + assignmentVersion: typeof EXPERIMENT_REQUEST_BUCKET_ASSIGNMENT_VERSION; + bucketCount: number; + chunkIds: string[]; +} + +export type FixedPayload = + | InlineFixedPayload + | ChunkedFixedPayload; + +export type ExperimentDependencyState = + | "waiting" + | "ready" + | "failed" + | "blocked"; + +export interface ExperimentDependencyProjection { + handlerId: string; + state: ExperimentDependencyState; + version?: number; + updatedAt?: Date; + error?: string; +} + +export type ExperimentBlockerReason = + | "request-missing" + | "run-changed" + | "dependency-not-ready" + | "dependency-failed" + | "dependency-blocked"; + +export interface ExperimentBlocker { + handlerId: string; + reason: ExperimentBlockerReason; + error?: string; +} + +/** Bounded, nonrecursive leaf stored in an experiment execution request vector. */ +export interface ExperimentRequestState { + requestId: string; + runId: string; + dependencies: ExperimentDependencyProjection[]; + blockers: ExperimentBlocker[]; +} + +export interface ExperimentMetadata { + name: string; + description?: string; + tags?: string[]; + createdBy?: string; +} + +export interface ExperimentRevision { + experimentRevisionId: string; + revisionNumber: number; + memberCount: number; + membershipFingerprint: string; + definitionFingerprint: string; + createdAt: Date; +} + +export type ExperimentHandlerStatus = + | "queued" + | "processing" + | "done" + | "failed"; + +export interface ExperimentHandlerSummary { + status: ExperimentHandlerStatus; + version: number; + updatedAt: Date; + error?: string; +} + +export interface ExperimentRolloverClaim { + nextExecution: ExperimentExecution; + reason: "rollover" | "retry"; + claimedAt: Date; +} + +export interface ExperimentExecution { + experimentExecutionId: string; + attemptNumber: number; + version: number; + requests: FixedPayload; + vectorFingerprint: string; + handlerSummary: Record; + blocking: ExperimentBlocker[]; + createdAt: Date; + updatedAt: Date; + startedAt?: Date; + finishedAt?: Date; + frozenAt?: Date; + discardedAt?: Date; + discardReason?: string; + supersededAt?: Date; + supersededByExperimentExecutionId?: string; + supersededReason?: "rollover" | "retry"; + rollover?: ExperimentRolloverClaim; +} + +export interface ExperimentDocument { + _id: string; + experimentId: string; + projectId: string; + metadata: ExperimentMetadata; + storageProfileVersion: ExperimentStorageProfileVersion; + stateVersion: number; + revision: ExperimentRevision; + execution: ExperimentExecution; + createdAt: Date; + updatedAt: Date; + finalizedAt?: Date; +} + +export interface ExperimentExecutionHistoryDocument + extends Omit { + _id: string; + experimentId: string; + projectId: string; + storageProfileVersion: ExperimentStorageProfileVersion; + revision: ExperimentRevision; + archivedAt: Date; +} + +export interface ExperimentPage { + experiments: ExperimentDocument[]; + nextCursor?: string; +} diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index fae65d02f..94bfa7c85 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -20,7 +20,7 @@ export * from "./codebases/index.js"; export * from "./resources/index.js"; export * from "./extensions/index.js"; export * from "./projects/index.js"; -export * from "./submissions/index.js"; +export * from "./experiments/index.js"; export * from "./agent-version.js"; export * from "./resolve-agent-version.js"; export * from "./resolve-agent-target.js"; From e25164129a9cae1fb3a2e9507876bc2d48e419a0 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Thu, 15 Oct 2026 22:42:56 -0700 Subject: [PATCH 046/210] refactor(experiments): remove submission model Replace imported Submission persistence surfaces with Experiment correlation and handler types. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 92d03055-789e-48b7-9a44-6de5b357f486 --- .../src/034-create-submission-indexes.test.ts | 51 -- .../034-create-submission-indexes.ts | 67 -- packages/shared/src/schemas/index.ts | 1 - packages/shared/src/schemas/request.ts | 12 +- packages/shared/src/schemas/submission.ts | 182 ----- .../shared/src/scripts/register-handler.ts | 10 +- packages/shared/src/submissions/index.ts | 5 - .../submission-coordinator.test.ts | 693 ------------------ .../src/submissions/submission-coordinator.ts | 573 --------------- .../src/submissions/submission-state.test.ts | 155 ---- .../src/submissions/submission-state.ts | 184 ----- packages/shared/src/types/types.ts | 131 +--- 12 files changed, 28 insertions(+), 2036 deletions(-) delete mode 100644 packages/db-migrations/src/034-create-submission-indexes.test.ts delete mode 100644 packages/db-migrations/src/migrations/034-create-submission-indexes.ts delete mode 100644 packages/shared/src/schemas/submission.ts delete mode 100644 packages/shared/src/submissions/index.ts delete mode 100644 packages/shared/src/submissions/submission-coordinator.test.ts delete mode 100644 packages/shared/src/submissions/submission-coordinator.ts delete mode 100644 packages/shared/src/submissions/submission-state.test.ts delete mode 100644 packages/shared/src/submissions/submission-state.ts diff --git a/packages/db-migrations/src/034-create-submission-indexes.test.ts b/packages/db-migrations/src/034-create-submission-indexes.test.ts deleted file mode 100644 index efcd2017f..000000000 --- a/packages/db-migrations/src/034-create-submission-indexes.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { Db } from "mongodb"; -import { describe, expect, it, vi } from "vitest"; -import { CreateSubmissionIndexes } from "./migrations/034-create-submission-indexes.js"; - -function collection() { - return { - createIndex: vi.fn(async () => "index"), - }; -} - -describe("migration 034: CreateSubmissionIndexes", () => { - it("creates submission, history, dispatch, and recovery indexes", async () => { - const submissions = collection(); - const submissionRuns = collection(); - const requests = collection(); - const db = { - collection: vi.fn((name: string) => { - if (name === "submissions") return submissions; - if (name === "submission-runs") return submissionRuns; - if (name === "requests") return requests; - throw new Error(`Unexpected collection ${name}`); - }), - } as unknown as Db; - - await new CreateSubmissionIndexes().up(db); - - expect(submissions.createIndex).toHaveBeenCalledWith( - { projectId: 1, createdAt: -1, _id: -1 }, - {}, - ); - expect(submissions.createIndex).toHaveBeenCalledWith( - { "run.handlerStatus.pp-readout.status": 1 }, - {}, - ); - expect(submissionRuns.createIndex).toHaveBeenCalledWith( - { submissionId: 1, attemptNumber: -1 }, - {}, - ); - expect(requests.createIndex).toHaveBeenCalledWith( - { submissionFinalizedAt: 1 }, - {}, - ); - expect(requests.createIndex).toHaveBeenCalledWith( - { submissionId: 1, projectId: 1, submissionRequestIndex: 1, _id: 1 }, - {}, - ); - }); -}); diff --git a/packages/db-migrations/src/migrations/034-create-submission-indexes.ts b/packages/db-migrations/src/migrations/034-create-submission-indexes.ts deleted file mode 100644 index 8ceb836e9..000000000 --- a/packages/db-migrations/src/migrations/034-create-submission-indexes.ts +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { Db } from "mongodb"; -import type { MigrationInterface } from "mongo-migrate-ts"; -import { ensureIndex } from "../cosmos-index-helpers.js"; - -const TAG = "034"; - -export class CreateSubmissionIndexes implements MigrationInterface { - async up(db: Db): Promise { - const submissions = db.collection("submissions"); - await ensureIndex( - submissions, - { projectId: 1, createdAt: -1, _id: -1 }, - {}, - "submissions", - TAG, - ); - await ensureIndex( - submissions, - { "run.handlerStatus.pp-readout.status": 1 }, - {}, - "submissions", - TAG, - ); - - const submissionRuns = db.collection("submission-runs"); - await ensureIndex( - submissionRuns, - { submissionId: 1 }, - {}, - "submission-runs", - TAG, - ); - await ensureIndex( - submissionRuns, - { submissionId: 1, attemptNumber: -1 }, - {}, - "submission-runs", - TAG, - ); - - const requests = db.collection("requests"); - await ensureIndex( - requests, - { submissionFinalizedAt: 1 }, - {}, - "requests", - TAG, - ); - await ensureIndex( - requests, - { submissionId: 1, projectId: 1, submissionRequestIndex: 1, _id: 1 }, - {}, - "requests", - TAG, - ); - console.log(`[${TAG}] Submission indexes complete`); - } - - async down(_db: Db): Promise { - console.log( - `[${TAG}-down] Skipping index changes - drop submission indexes manually if needed`, - ); - } -} diff --git a/packages/shared/src/schemas/index.ts b/packages/shared/src/schemas/index.ts index 52a7bed3f..cb1df8b4c 100644 --- a/packages/shared/src/schemas/index.ts +++ b/packages/shared/src/schemas/index.ts @@ -22,4 +22,3 @@ export * from "./account.js"; export * from "./feature-flag.js"; export * from "./profile.js"; export * from "./project.js"; -export * from "./submission.js"; diff --git a/packages/shared/src/schemas/request.ts b/packages/shared/src/schemas/request.ts index 5aefb2466..ac7766f2d 100644 --- a/packages/shared/src/schemas/request.ts +++ b/packages/shared/src/schemas/request.ts @@ -180,11 +180,13 @@ export const RequestResponseSchema = z agentVersion: z.string().optional(), profileId: z.string().optional(), profileVersionId: z.string().optional(), - submissionId: z.string().optional(), - submissionExpectedRequestCount: z.number().int().min(1).optional(), - submissionRequestIndex: z.number().int().min(0).optional(), - submissionInitialRunId: z.string().optional(), - submissionFinalizedAt: z.coerce.date().optional(), + experimentId: z.string().optional(), + experimentRevisionId: z.string().optional(), + experimentExecutionId: z.string().optional(), + experimentExpectedRequestCount: z.number().int().min(1).optional(), + experimentRequestIndex: z.number().int().min(0).optional(), + experimentInitialRunId: z.string().optional(), + experimentFinalizedAt: z.coerce.date().optional(), priority: z.number().int().default(0), gates: z.array(GateConfigSchema).optional(), observations: z.array(z.string()).optional(), diff --git a/packages/shared/src/schemas/submission.ts b/packages/shared/src/schemas/submission.ts deleted file mode 100644 index 3558ae603..000000000 --- a/packages/shared/src/schemas/submission.ts +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { z } from "zod"; -import { extendZodWithOpenApi } from "@asteasolutions/zod-to-openapi"; - -extendZodWithOpenApi(z); - -export const SubmissionRequestRefSchema = z - .object({ - requestId: z.string(), - runId: z.string(), - }) - .openapi("SubmissionRequestRef"); - -export const SubmissionDependencyStateSchema = z.enum([ - "waiting", - "ready", - "failed", - "blocked", -]); - -export const SubmissionDependencyProjectionSchema = z - .object({ - requestId: z.string(), - runId: z.string(), - handlerId: z.string(), - state: SubmissionDependencyStateSchema, - version: z.number().optional(), - updatedAt: z.coerce.date().optional(), - error: z.string().optional(), - }) - .openapi("SubmissionDependencyProjection"); - -export const SubmissionBlockingDetailSchema = z - .object({ - requestId: z.string(), - runId: z.string(), - handlerId: z.string(), - reason: z.enum([ - "request-missing", - "run-changed", - "dependency-not-ready", - "dependency-failed", - "dependency-blocked", - ]), - error: z.string().optional(), - }) - .openapi("SubmissionBlockingDetail"); - -export const SubmissionHandlerStatusSchema = z - .object({ - status: z.enum(["queued", "processing", "done", "failed"]), - version: z.number().optional(), - updatedAt: z.coerce.date().optional(), - error: z.string().optional(), - }) - .openapi("SubmissionHandlerStatus"); - -export const SubmissionReportPointerSchema = z - .object({ - reportId: z.string().optional(), - url: z.string().optional(), - updatedAt: z.coerce.date().optional(), - }) - .openapi("SubmissionReportPointer"); - -export const SubmissionRolloverClaimSchema = z.object({ - nextSubmissionRunId: z.string(), - vectorFingerprint: z.string(), - requests: z.array(SubmissionRequestRefSchema), - reason: z.enum(["request-vector-changed", "manual-retry"]), - claimedAt: z.coerce.date(), -}); - -export const SubmissionRunStateSchema = z - .object({ - _id: z.string(), - attemptNumber: z.number().int().min(1), - vectorFingerprint: z.string(), - requests: z.array(SubmissionRequestRefSchema), - createdAt: z.coerce.date(), - updatedAt: z.coerce.date().optional(), - startedAt: z.coerce.date().optional(), - finishedAt: z.coerce.date().optional(), - dependencyProjection: z.array(SubmissionDependencyProjectionSchema).default([]), - handlerStatus: z.record(z.string(), SubmissionHandlerStatusSchema).optional(), - blocking: z.array(SubmissionBlockingDetailSchema).default([]), - report: SubmissionReportPointerSchema.optional(), - reconcileAfter: z.coerce.date().optional(), - rollover: SubmissionRolloverClaimSchema.optional(), - supersededAt: z.coerce.date().optional(), - supersededBySubmissionRunId: z.string().optional(), - supersededReason: z.enum(["request-vector-changed", "manual-retry"]).optional(), - }) - .openapi("SubmissionRunState"); - -export const SubmissionDocumentSchema = z - .object({ - _id: z.string(), - submissionId: z.string(), - projectId: z.string(), - requestIds: z.array(z.string()).min(1), - createdAt: z.coerce.date(), - updatedAt: z.coerce.date().optional(), - run: SubmissionRunStateSchema, - }) - .openapi("SubmissionDocument"); - -export const SubmissionRunHistoryDocumentSchema = SubmissionRunStateSchema.extend({ - submissionId: z.string(), - projectId: z.string(), -}).openapi("SubmissionRunHistoryDocument"); - -export const SubmissionRunResponseSchema = SubmissionRunStateSchema.omit({ - reconcileAfter: true, - rollover: true, -}) - .extend({ - submissionId: z.string().optional(), - projectId: z.string().optional(), - }) - .openapi("SubmissionRunResponse"); - -export const SubmissionReadinessSchema = z.enum([ - "waiting", - "ready", - "blocked", - "processing", - "done", - "failed", -]); - -export const SubmissionRequestSummarySchema = z - .object({ - requestId: z.string(), - runId: z.string(), - task: z.string(), - status: z.string(), - outcome: z.string().optional(), - workerType: z.string(), - model: z.string().optional(), - profileId: z.string().optional(), - }) - .openapi("SubmissionRequestSummary"); - -export const SubmissionResponseSchema = z - .object({ - submissionId: z.string(), - projectId: z.string(), - requestIds: z.array(z.string()), - createdAt: z.coerce.date(), - updatedAt: z.coerce.date().optional(), - submissionRunId: z.string(), - attemptNumber: z.number().int(), - readiness: SubmissionReadinessSchema, - requests: z.array(SubmissionRequestSummarySchema), - dependencyProjection: z.array(SubmissionDependencyProjectionSchema), - blocking: z.array(SubmissionBlockingDetailSchema), - handlerProgress: z.record(z.string(), SubmissionHandlerStatusSchema).optional(), - report: SubmissionReportPointerSchema.optional(), - supersededAt: z.coerce.date().optional(), - supersededBySubmissionRunId: z.string().optional(), - supersededReason: z.enum(["request-vector-changed", "manual-retry"]).optional(), - }) - .openapi("SubmissionResponse"); - -export const SubmissionListResponseSchema = z - .object({ - submissions: z.array(SubmissionResponseSchema), - }) - .openapi("SubmissionListResponse"); - -export const SubmissionRetryResponseSchema = z - .object({ - submissionId: z.string(), - submissionRunId: z.string(), - attemptNumber: z.number().int(), - readiness: SubmissionReadinessSchema, - blocking: z.array(SubmissionBlockingDetailSchema), - }) - .openapi("SubmissionRetryResponse"); diff --git a/packages/shared/src/scripts/register-handler.ts b/packages/shared/src/scripts/register-handler.ts index 730b860f6..cc06045df 100644 --- a/packages/shared/src/scripts/register-handler.ts +++ b/packages/shared/src/scripts/register-handler.ts @@ -42,9 +42,9 @@ export function parseHandlerDocument(raw: unknown): ServiceHandlerDocument { if (!isNonEmptyString(doc._id)) { throw new Error("handler.yaml: '_id' is required"); } - if (doc.type !== "post-process-handler" && doc.type !== "submission-handler") { + if (doc.type !== "post-process-handler" && doc.type !== "experiment-handler") { throw new Error( - "handler.yaml: 'type' must be 'post-process-handler' or 'submission-handler'", + "handler.yaml: 'type' must be 'post-process-handler' or 'experiment-handler'", ); } if (typeof doc.version !== "number" || !Number.isFinite(doc.version)) { @@ -72,15 +72,15 @@ export function parseHandlerDocument(raw: unknown): ServiceHandlerDocument { autoBackfill: doc.autoBackfill, dependsOn: dependsOn as string[], }; - if (doc.type === "submission-handler") { + if (doc.type === "experiment-handler") { if (doc.dependencyMode !== "all-runs") { throw new Error( - "handler.yaml: submission handlers require dependencyMode: 'all-runs'", + "handler.yaml: experiment handlers require dependencyMode: 'all-runs'", ); } return { ...common, - type: "submission-handler", + type: "experiment-handler", dependencyMode: "all-runs", }; } diff --git a/packages/shared/src/submissions/index.ts b/packages/shared/src/submissions/index.ts deleted file mode 100644 index 5aa35026a..000000000 --- a/packages/shared/src/submissions/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -export * from "./submission-state.js"; -export * from "./submission-coordinator.js"; diff --git a/packages/shared/src/submissions/submission-coordinator.test.ts b/packages/shared/src/submissions/submission-coordinator.test.ts deleted file mode 100644 index d44b4c12e..000000000 --- a/packages/shared/src/submissions/submission-coordinator.test.ts +++ /dev/null @@ -1,693 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { describe, expect, it, vi } from "vitest"; -import type { Collection } from "mongodb"; -import type { - RequestDocument, - ServiceHandlerDocument, - SubmissionDocument, - SubmissionRunHistoryDocument, -} from "../types/types.js"; -import { - SubmissionCoordinator, - claimSubmissionHandler, - completeSubmissionHandler, - ensureNativeSubmission, -} from "./submission-coordinator.js"; - -function queryResult(items: T[]) { - return { - project: () => queryResult(items), - sort: () => queryResult(items), - limit: () => queryResult(items), - toArray: async () => items, - }; -} - -describe("submission coordinator persistence", () => { - it("creates a native submission idempotently with the exact initial vector", async () => { - let stored: SubmissionDocument | null = null; - const updateOne = vi.fn(async ( - _filter: unknown, - update: { $setOnInsert: SubmissionDocument }, - ) => { - stored ??= update.$setOnInsert; - return { matchedCount: stored ? 1 : 0, modifiedCount: 0 }; - }); - const findOne = vi.fn(async () => stored); - const submissions = { - updateOne, - findOne, - } as unknown as Collection; - - const first = await ensureNativeSubmission({ - collections: { submissions }, - submissionId: "submission-1", - projectId: "project-1", - requests: [ - { requestId: "request-1", runId: "run-1" }, - { requestId: "request-2", runId: "run-2" }, - ], - createdAt: new Date("2026-01-01T00:00:00Z"), - }); - const second = await ensureNativeSubmission({ - collections: { submissions }, - submissionId: "submission-1", - projectId: "project-1", - requests: [ - { requestId: "request-1", runId: "run-1" }, - { requestId: "request-2", runId: "run-2" }, - ], - createdAt: new Date("2026-01-01T00:00:00Z"), - }); - - expect(first).toEqual(second); - expect(first.requestIds).toEqual(["request-1", "request-2"]); - expect(first.run.requests).toEqual([ - { requestId: "request-1", runId: "run-1" }, - { requestId: "request-2", runId: "run-2" }, - ]); - expect(first.run._id).toBe(second.run._id); - expect(updateOne).toHaveBeenCalledTimes(2); - }); - - it("rejects an idempotency key reused with a different immutable vector", async () => { - const stored: SubmissionDocument = { - _id: "submission-1", - submissionId: "submission-1", - projectId: "project-1", - requestIds: ["request-1"], - createdAt: new Date(), - run: { - _id: "submission-run-1", - attemptNumber: 1, - vectorFingerprint: "fingerprint", - requests: [{ requestId: "request-1", runId: "run-1" }], - createdAt: new Date(), - dependencyProjection: [], - blocking: [], - }, - }; - const submissions = { - updateOne: vi.fn(async () => ({ matchedCount: 1, modifiedCount: 0 })), - findOne: vi.fn(async () => stored), - } as unknown as Collection; - - await expect( - ensureNativeSubmission({ - collections: { submissions }, - submissionId: "submission-1", - projectId: "project-1", - requests: [{ requestId: "request-1", runId: "different-run" }], - }), - ).rejects.toThrow("different immutable request vector"); - }); - - it("scopes claims and completions to the exact embedded submission run", async () => { - const findOneAndUpdate = vi.fn(async (_filter: unknown, _update: unknown) => null); - const updateOne = vi.fn(async (_filter: unknown, _update: unknown) => ({ - modifiedCount: 0, - })); - const submissions = { - findOneAndUpdate, - updateOne, - } as unknown as Collection; - - expect( - await claimSubmissionHandler({ - submissions, - submissionId: "submission-1", - submissionRunId: "stale-run", - handlerId: "pp-readout", - version: 1, - }), - ).toBeNull(); - expect(findOneAndUpdate.mock.calls[0]?.[0]).toMatchObject({ - _id: "submission-1", - "run._id": "stale-run", - "run.rollover": { $exists: false }, - }); - - expect( - await completeSubmissionHandler({ - submissions, - submissionId: "submission-1", - submissionRunId: "stale-run", - handlerId: "pp-readout", - status: "done", - version: 1, - }), - ).toBe(false); - expect(updateOne.mock.calls[0]?.[0]).toMatchObject({ - _id: "submission-1", - "run._id": "stale-run", - "run.rollover": { $exists: false }, - "run.handlerStatus.pp-readout.status": "processing", - }); - }); - - it("defers reconciliation while a bulk retry replaces its request vector", async () => { - const submission: SubmissionDocument = { - _id: "submission-1", - submissionId: "submission-1", - projectId: "project-1", - requestIds: ["request-1"], - createdAt: new Date(), - run: { - _id: "submission-run-1", - attemptNumber: 1, - vectorFingerprint: "old-vector", - requests: [{ requestId: "request-1", runId: "run-1" }], - createdAt: new Date(), - reconcileAfter: new Date(Date.now() + 60_000), - dependencyProjection: [], - blocking: [], - }, - }; - const requestsFind = vi.fn(); - const archiveInsert = vi.fn(); - const coordinator = new SubmissionCoordinator({ - requests: { - find: requestsFind, - } as unknown as Collection, - submissions: { - findOne: vi.fn(async () => submission), - } as unknown as Collection, - submissionRuns: { - insertOne: archiveInsert, - } as unknown as Collection, - services: {} as Collection, - }); - - const result = await coordinator.reconcile("submission-1"); - - expect(result?.rolled).toBe(false); - expect(requestsFind).not.toHaveBeenCalled(); - expect(archiveInsert).not.toHaveBeenCalled(); - }); - - it("resumes an interrupted drift rollover without double-rolling a manual retry", async () => { - const requestDocs: RequestDocument[] = [ - { - _id: "request-1", - projectId: "project-1", - scenario: { task: "Task", criteria: ["criterion"] }, - workerType: "worker", - createdAt: new Date(), - priority: 0, - submissionId: "submission-1", - run: { - _id: "run-2", - attemptNumber: 2, - status: "done", - outcome: "failed", - handlerStatus: { - "pp-observations": { status: "done", version: 2 }, - unrelated: { status: "failed" }, - }, - }, - }, - ]; - let submission: SubmissionDocument = { - _id: "submission-1", - submissionId: "submission-1", - projectId: "project-1", - requestIds: ["request-1"], - createdAt: new Date(), - run: { - _id: "submission-run-1", - attemptNumber: 1, - vectorFingerprint: "old-vector", - requests: [{ requestId: "request-1", runId: "run-1" }], - createdAt: new Date(), - dependencyProjection: [], - blocking: [], - }, - }; - const history: SubmissionRunHistoryDocument[] = []; - const services: ServiceHandlerDocument[] = [ - { - _id: "pp-atif", - type: "post-process-handler", - version: 1, - queue: "post-processor", - selector: "atif", - autoBackfill: true, - dependsOn: [], - }, - { - _id: "pp-observations", - type: "post-process-handler", - version: 2, - queue: "post-processor", - selector: "observations", - autoBackfill: true, - dependsOn: ["pp-atif"], - }, - { - _id: "pp-readout", - type: "submission-handler", - version: 1, - queue: "readout", - selector: "readout", - autoBackfill: false, - dependsOn: ["pp-observations"], - dependencyMode: "all-runs", - }, - ]; - const submissions = { - findOne: vi.fn(async () => structuredClone(submission)), - updateOne: vi.fn(async () => ({ matchedCount: 1, modifiedCount: 1 })), - findOneAndUpdate: vi.fn(async ( - filter: Record, - update: { $set: Record }, - ) => { - if (filter["run._id"] && filter["run._id"] !== submission.run._id) return null; - if (update.$set["run.rollover"]) { - submission = { - ...submission, - updatedAt: update.$set.updatedAt as Date, - run: { - ...submission.run, - rollover: update.$set[ - "run.rollover" - ] as SubmissionDocument["run"]["rollover"], - updatedAt: update.$set["run.updatedAt"] as Date, - }, - }; - } else if (update.$set.run) { - rollAttempts++; - if (rollAttempts === 1) return null; - submission = { - ...submission, - run: update.$set.run as SubmissionDocument["run"], - updatedAt: update.$set.updatedAt as Date, - }; - } else { - submission = { - ...submission, - updatedAt: update.$set.updatedAt as Date, - run: { - ...submission.run, - dependencyProjection: update.$set[ - "run.dependencyProjection" - ] as SubmissionDocument["run"]["dependencyProjection"], - blocking: update.$set[ - "run.blocking" - ] as SubmissionDocument["run"]["blocking"], - updatedAt: update.$set["run.updatedAt"] as Date, - }, - }; - } - return structuredClone(submission); - }), - } as unknown as Collection; - let rollAttempts = 0; - const enqueue = vi.fn(async ( - _service: ServiceHandlerDocument, - _message: { submissionId: string; submissionRunId: string; type: string }, - ) => undefined); - const archiveUpdate = vi.fn(async ( - _filter: unknown, - update: { $setOnInsert: SubmissionRunHistoryDocument }, - ) => { - if (!history.some((item) => item._id === update.$setOnInsert._id)) { - history.push(update.$setOnInsert); - } - return { matchedCount: 1, modifiedCount: 1 }; - }); - const coordinator = new SubmissionCoordinator( - { - requests: { - find: vi.fn(() => queryResult(requestDocs)), - } as unknown as Collection, - submissions, - submissionRuns: { - updateOne: archiveUpdate, - } as unknown as Collection, - services: { - find: vi.fn(() => - queryResult(services.filter((service) => service.type === "post-process-handler")), - ), - findOne: vi.fn(async () => - services.find((service) => service._id === "pp-readout") ?? null, - ), - } as unknown as Collection, - }, - enqueue, - ); - - const result = await coordinator.retryCurrent( - "submission-1", - "submission-run-1", - ); - - expect(result?.rolled).toBe(true); - expect(result?.submission.run.attemptNumber).toBe(2); - expect(result?.submission.run.requests).toEqual([ - { requestId: "request-1", runId: "run-2" }, - ]); - expect(result?.submission.run.dependencyProjection[0]).toMatchObject({ - runId: "run-2", - state: "ready", - version: 2, - }); - expect(history).toHaveLength(1); - expect(archiveUpdate).toHaveBeenCalledTimes(2); - expect(history[0]).toMatchObject({ - _id: "submission-run-1", - supersededBySubmissionRunId: result?.submission.run._id, - supersededReason: "request-vector-changed", - }); - expect(enqueue).toHaveBeenCalledTimes(1); - expect(enqueue.mock.calls[0]?.[1]).toMatchObject({ - submissionId: "submission-1", - submissionRunId: result?.submission.run._id, - }); - }); - - it("links immutable history only to CAS-winning successors under concurrent vector drift", async () => { - const request = (runId: string, attemptNumber: number): RequestDocument => ({ - _id: "request-1", - projectId: "project-1", - scenario: { task: "Task", criteria: ["criterion"] }, - workerType: "worker", - createdAt: new Date(), - priority: 0, - submissionId: "submission-1", - run: { - _id: runId, - attemptNumber, - status: "done", - }, - }); - let submission: SubmissionDocument = { - _id: "submission-1", - submissionId: "submission-1", - projectId: "project-1", - requestIds: ["request-1"], - createdAt: new Date(), - run: { - _id: "submission-run-1", - attemptNumber: 1, - vectorFingerprint: "initial", - requests: [{ requestId: "request-1", runId: "run-1" }], - createdAt: new Date(), - dependencyProjection: [], - blocking: [], - }, - }; - const history = new Map(); - const submissions = { - findOne: vi.fn(async () => structuredClone(submission)), - updateOne: vi.fn(async () => ({ matchedCount: 1, modifiedCount: 1 })), - findOneAndUpdate: vi.fn(async ( - filter: Record, - update: { $set: Record }, - ) => { - if (filter["run._id"] !== submission.run._id) return null; - if (update.$set["run.rollover"]) { - if (submission.run.rollover) return null; - submission = { - ...submission, - run: { - ...submission.run, - rollover: update.$set[ - "run.rollover" - ] as SubmissionDocument["run"]["rollover"], - }, - }; - } else if (update.$set.run) { - if ( - filter["run.rollover.nextSubmissionRunId"] !== - submission.run.rollover?.nextSubmissionRunId - ) { - return null; - } - submission = { - ...submission, - run: update.$set.run as SubmissionDocument["run"], - }; - } else { - submission = { - ...submission, - run: { - ...submission.run, - dependencyProjection: update.$set[ - "run.dependencyProjection" - ] as SubmissionDocument["run"]["dependencyProjection"], - blocking: update.$set[ - "run.blocking" - ] as SubmissionDocument["run"]["blocking"], - }, - }; - } - return structuredClone(submission); - }), - } as unknown as Collection; - const submissionRuns = { - updateOne: vi.fn(async ( - filter: { _id: string }, - update: { $setOnInsert: SubmissionRunHistoryDocument }, - ) => { - if (!history.has(filter._id)) { - history.set(filter._id, structuredClone(update.$setOnInsert)); - } - return { matchedCount: 1, modifiedCount: 1 }; - }), - } as unknown as Collection; - const services = { - find: vi.fn(() => queryResult([])), - findOne: vi.fn(async () => null), - } as unknown as Collection; - let firstCoordinatorReads = 0; - const coordinatorA = new SubmissionCoordinator({ - requests: { - find: vi.fn(() => - queryResult([ - firstCoordinatorReads++ === 0 - ? request("run-2", 2) - : request("run-3", 3), - ]), - ), - } as unknown as Collection, - submissions, - submissionRuns, - services, - }); - const coordinatorB = new SubmissionCoordinator({ - requests: { - find: vi.fn(() => queryResult([request("run-3", 3)])), - } as unknown as Collection, - submissions, - submissionRuns, - services, - }); - - await Promise.all([ - coordinatorA.reconcile("submission-1"), - coordinatorB.reconcile("submission-1"), - ]); - - expect(submission.run.requests).toEqual([ - { requestId: "request-1", runId: "run-3" }, - ]); - expect(submission.run.rollover).toBeUndefined(); - expect(history.size).toBe(2); - const knownRunIds = new Set([...history.keys(), submission.run._id]); - for (const archived of history.values()) { - expect(knownRunIds.has(archived.supersededBySubmissionRunId!)).toBe(true); - } - }); - - it("repairs an interrupted claimed rollover on the next polling reconciliation", async () => { - const requestDocument: RequestDocument = { - _id: "request-1", - projectId: "project-1", - scenario: { task: "Task", criteria: ["criterion"] }, - workerType: "worker", - createdAt: new Date(), - priority: 0, - submissionId: "submission-1", - run: { - _id: "run-2", - attemptNumber: 2, - status: "done", - }, - }; - let submission: SubmissionDocument = { - _id: "submission-1", - submissionId: "submission-1", - projectId: "project-1", - requestIds: ["request-1"], - createdAt: new Date(), - run: { - _id: "submission-run-1", - attemptNumber: 1, - vectorFingerprint: "initial", - requests: [{ requestId: "request-1", runId: "run-1" }], - createdAt: new Date(), - dependencyProjection: [], - blocking: [], - }, - }; - const history = new Map(); - let interruptReplacement = true; - const submissions = { - findOne: vi.fn(async () => structuredClone(submission)), - updateOne: vi.fn(async () => ({ matchedCount: 1, modifiedCount: 1 })), - findOneAndUpdate: vi.fn(async ( - filter: Record, - update: { $set: Record }, - ) => { - if (filter["run._id"] !== submission.run._id) return null; - if (update.$set["run.rollover"]) { - if (submission.run.rollover) return null; - submission = { - ...submission, - run: { - ...submission.run, - rollover: update.$set[ - "run.rollover" - ] as SubmissionDocument["run"]["rollover"], - }, - }; - } else if (update.$set.run) { - if (interruptReplacement) { - interruptReplacement = false; - throw new Error("simulated process interruption"); - } - submission = { - ...submission, - run: update.$set.run as SubmissionDocument["run"], - }; - } else { - submission = { - ...submission, - run: { - ...submission.run, - dependencyProjection: update.$set[ - "run.dependencyProjection" - ] as SubmissionDocument["run"]["dependencyProjection"], - blocking: update.$set[ - "run.blocking" - ] as SubmissionDocument["run"]["blocking"], - }, - }; - } - return structuredClone(submission); - }), - } as unknown as Collection; - const submissionRuns = { - updateOne: vi.fn(async ( - filter: { _id: string }, - update: { $setOnInsert: SubmissionRunHistoryDocument }, - ) => { - if (!history.has(filter._id)) { - history.set(filter._id, structuredClone(update.$setOnInsert)); - } - return { matchedCount: 1, modifiedCount: 1 }; - }), - } as unknown as Collection; - const collections = { - requests: { - find: vi.fn(() => queryResult([requestDocument])), - } as unknown as Collection, - submissions, - submissionRuns, - services: { - find: vi.fn(() => queryResult([])), - findOne: vi.fn(async () => null), - } as unknown as Collection, - }; - - await expect( - new SubmissionCoordinator(collections).reconcile("submission-1"), - ).rejects.toThrow("simulated process interruption"); - expect(submission.run.rollover).toBeDefined(); - expect(history.size).toBe(1); - - const repaired = await new SubmissionCoordinator(collections).reconcile( - "submission-1", - ); - - expect(repaired?.submission.run.attemptNumber).toBe(2); - expect(repaired?.submission.run.requests).toEqual([ - { requestId: "request-1", runId: "run-2" }, - ]); - expect(repaired?.submission.run.rollover).toBeUndefined(); - expect(history.get("submission-run-1")?.supersededBySubmissionRunId).toBe( - repaired?.submission.run._id, - ); - }); - - it("recovers an interrupted final submission write only for complete native request groups", async () => { - const requests: RequestDocument[] = [ - { - _id: "request-1", - projectId: "project-1", - scenario: { task: "Task", criteria: ["criterion"] }, - workerType: "worker", - createdAt: new Date(), - priority: 0, - submissionId: "submission-1", - submissionExpectedRequestCount: 2, - submissionRequestIndex: 0, - submissionInitialRunId: "run-1", - run: { _id: "retried-run", attemptNumber: 2, status: "pending" }, - }, - { - _id: "request-2", - projectId: "project-1", - scenario: { task: "Task", criteria: ["criterion"] }, - workerType: "worker", - createdAt: new Date(), - priority: 0, - submissionId: "submission-1", - submissionExpectedRequestCount: 2, - submissionRequestIndex: 1, - submissionInitialRunId: "run-2", - run: { _id: "run-2", attemptNumber: 1, status: "pending" }, - }, - ]; - let stored: SubmissionDocument | null = null; - const updateMany = vi.fn(async () => ({ modifiedCount: 2 })); - const coordinator = new SubmissionCoordinator({ - requests: { - find: vi.fn(() => queryResult(requests)), - updateMany, - } as unknown as Collection, - submissions: { - findOne: vi.fn(async () => stored), - updateOne: vi.fn(async ( - _filter: unknown, - update: { $setOnInsert: SubmissionDocument }, - ) => { - stored ??= update.$setOnInsert; - return { upsertedCount: 1 }; - }), - } as unknown as Collection, - submissionRuns: {} as Collection, - services: {} as Collection, - }); - - expect(await coordinator.recoverMissingNativeSubmissions()).toBe(1); - expect(stored).not.toBeNull(); - const recovered = stored as SubmissionDocument | null; - expect(recovered?.requestIds).toEqual(["request-1", "request-2"]); - expect(recovered?.run.requests).toEqual([ - { requestId: "request-1", runId: "run-1" }, - { requestId: "request-2", runId: "run-2" }, - ]); - expect(await coordinator.recoverMissingNativeSubmissions()).toBe(1); - expect(updateMany).toHaveBeenCalledTimes(2); - expect(updateMany).toHaveBeenCalledWith( - expect.objectContaining({ - submissionId: "submission-1", - submissionFinalizedAt: { $exists: false }, - }), - expect.objectContaining({ $set: { submissionFinalizedAt: expect.any(Date) } }), - ); - }); -}); diff --git a/packages/shared/src/submissions/submission-coordinator.ts b/packages/shared/src/submissions/submission-coordinator.ts deleted file mode 100644 index 5720a744a..000000000 --- a/packages/shared/src/submissions/submission-coordinator.ts +++ /dev/null @@ -1,573 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { v5 as uuidv5 } from "uuid"; -import type { Collection, Document } from "mongodb"; -import type { - HandlerServiceDocument, - RequestDocument, - SubmissionDocument, - SubmissionHandlerServiceDocument, - SubmissionQueueMessagePayload, - SubmissionReportPointer, - SubmissionRunHistoryDocument, - SubmissionRunState, - ServiceHandlerDocument, -} from "../types/types.js"; -import { - OBSERVATIONS_HANDLER_ID, - READOUT_HANDLER_ID, - computeSubmissionVectorFingerprint, - deriveSubmissionReadiness, - projectSubmissionDependency, -} from "./submission-state.js"; - -const SUBMISSION_RUN_NAMESPACE = "6b0f8a6a-5cda-4cb4-bcc4-79bb0ac7f54d"; - -export interface SubmissionCollections { - requests: Collection; - submissions: Collection; - submissionRuns: Collection; - services: Collection; -} - -export type EnqueueSubmission = ( - service: SubmissionHandlerServiceDocument, - message: SubmissionQueueMessagePayload, -) => Promise; - -export interface ReconcileSubmissionResult { - submission: SubmissionDocument; - readiness: ReturnType; - rolled: boolean; - dispatched: boolean; -} - -function submissionRunId( - submissionId: string, - attemptNumber: number, - vectorFingerprint: string, -): string { - return uuidv5( - `${submissionId}:${attemptNumber}:${vectorFingerprint}`, - SUBMISSION_RUN_NAMESPACE, - ); -} - -function initialSubmissionRun( - submissionId: string, - requests: Array<{ requestId: string; runId: string }>, - createdAt: Date, -): SubmissionRunState { - const vectorFingerprint = computeSubmissionVectorFingerprint(requests); - return { - _id: submissionRunId(submissionId, 1, vectorFingerprint), - attemptNumber: 1, - vectorFingerprint, - requests, - createdAt, - dependencyProjection: [], - blocking: [], - }; -} - -export async function ensureNativeSubmission(input: { - collections: Pick; - submissionId: string; - projectId: string; - requests: Array<{ requestId: string; runId: string }>; - createdAt?: Date; -}): Promise { - const requestIds = input.requests.map((request) => request.requestId); - const createdAt = input.createdAt ?? new Date(); - const doc: SubmissionDocument = { - _id: input.submissionId, - submissionId: input.submissionId, - projectId: input.projectId, - requestIds, - createdAt, - run: initialSubmissionRun(input.submissionId, input.requests, createdAt), - }; - await input.collections.submissions.updateOne( - { _id: input.submissionId } as Document, - { $setOnInsert: doc } as Document, - { upsert: true }, - ); - const persisted = await input.collections.submissions.findOne({ - _id: input.submissionId, - } as Document); - if (!persisted) { - throw new Error(`Submission ${input.submissionId} was not persisted`); - } - const sameProject = persisted.projectId === input.projectId; - const sameRequests = - persisted.requestIds.length === requestIds.length && - persisted.requestIds.every((requestId, index) => requestId === requestIds[index]); - const sameInitialVector = - persisted.run.attemptNumber > 1 || - (persisted.run.requests.length === input.requests.length && - persisted.run.requests.every((request, index) => { - const expected = input.requests[index]; - return ( - request.requestId === expected?.requestId && - request.runId === expected.runId - ); - })); - if (!sameProject || !sameRequests || !sameInitialVector) { - throw new Error( - `Submission ${input.submissionId} already exists with a different immutable request vector`, - ); - } - return persisted; -} - -async function loadPostProcessHandlers( - services: Collection, -): Promise { - const documents = await services - .find({ type: "post-process-handler" }) - .toArray(); - return documents.filter( - (document): document is HandlerServiceDocument => - document.type === "post-process-handler", - ); -} - -async function loadReadoutService( - services: Collection, -): Promise { - const document = await services.findOne({ - _id: READOUT_HANDLER_ID, - type: "submission-handler", - }); - return document?.type === "submission-handler" ? document : null; -} - -async function archiveAndRoll(input: { - collections: SubmissionCollections; - submission: SubmissionDocument; - requests: Array<{ requestId: string; runId: string }>; - reason: "request-vector-changed" | "manual-retry"; -}): Promise { - let claimed = input.submission; - if (!claimed.run.rollover) { - const claimedAt = new Date(); - const nextAttemptNumber = claimed.run.attemptNumber + 1; - const vectorFingerprint = computeSubmissionVectorFingerprint(input.requests); - const nextSubmissionRunId = submissionRunId( - claimed._id, - nextAttemptNumber, - vectorFingerprint, - ); - const claimedDocument = await input.collections.submissions.findOneAndUpdate( - { - _id: claimed._id, - "run._id": claimed.run._id, - "run.vectorFingerprint": claimed.run.vectorFingerprint, - "run.rollover": { $exists: false }, - } as Document, - { - $set: { - "run.rollover": { - nextSubmissionRunId, - vectorFingerprint, - requests: input.requests, - reason: input.reason, - claimedAt, - }, - "run.updatedAt": claimedAt, - updatedAt: claimedAt, - }, - } as Document, - { returnDocument: "after" }, - ); - if (!claimedDocument) return null; - claimed = claimedDocument; - } - const rollover = claimed.run.rollover; - if (!rollover) return null; - const { rollover: _rollover, reconcileAfter: _reconcileAfter, ...archivedRun } = - claimed.run; - const archived: SubmissionRunHistoryDocument = { - ...archivedRun, - submissionId: claimed._id, - projectId: claimed.projectId, - supersededAt: rollover.claimedAt, - supersededBySubmissionRunId: rollover.nextSubmissionRunId, - supersededReason: rollover.reason, - }; - await input.collections.submissionRuns.updateOne( - { _id: archived._id } as Document, - { $setOnInsert: archived } as Document, - { upsert: true }, - ); - - const nextRun: SubmissionRunState = { - _id: rollover.nextSubmissionRunId, - attemptNumber: claimed.run.attemptNumber + 1, - vectorFingerprint: rollover.vectorFingerprint, - requests: rollover.requests, - createdAt: rollover.claimedAt, - dependencyProjection: [], - blocking: [], - }; - const updated = await input.collections.submissions.findOneAndUpdate( - { - _id: claimed._id, - "run._id": claimed.run._id, - "run.rollover.nextSubmissionRunId": rollover.nextSubmissionRunId, - } as Document, - { - $set: { - run: nextRun, - updatedAt: rollover.claimedAt, - }, - } as Document, - { returnDocument: "after" }, - ); - return updated; -} - -export class SubmissionCoordinator { - private recoveryAfterRequestId: string | null = null; - - constructor( - private readonly collections: SubmissionCollections, - private readonly enqueue?: EnqueueSubmission, - ) {} - - async recoverMissingNativeSubmissions(limit = 30): Promise { - const filter: Document = { - submissionId: { $exists: true }, - submissionExpectedRequestCount: { $exists: true }, - submissionFinalizedAt: { $exists: false }, - deletedAt: { $exists: false }, - ...(this.recoveryAfterRequestId - ? { _id: { $gt: this.recoveryAfterRequestId } } - : {}), - }; - const candidates = await this.collections.requests - .find(filter) - .project({ - _id: 1, - projectId: 1, - submissionId: 1, - submissionExpectedRequestCount: 1, - submissionRequestIndex: 1, - submissionInitialRunId: 1, - "run._id": 1, - createdAt: 1, - }) - .sort({ _id: 1 }) - .limit(limit) - .toArray(); - this.recoveryAfterRequestId = - candidates.length === limit ? candidates.at(-1)?._id ?? null : null; - let recovered = 0; - const visited = new Set(); - for (const candidate of candidates) { - const submissionId = candidate.submissionId; - const expected = candidate.submissionExpectedRequestCount; - if (!submissionId || !expected || visited.has(submissionId)) continue; - visited.add(submissionId); - const requests = await this.collections.requests - .find({ - submissionId, - projectId: candidate.projectId, - submissionExpectedRequestCount: expected, - deletedAt: { $exists: false }, - } as Document) - .sort({ submissionRequestIndex: 1, _id: 1 }) - .toArray(); - if ( - requests.length !== expected || - requests.some( - (request, index) => - request.submissionRequestIndex !== index || - !request.submissionInitialRunId, - ) - ) { - continue; - } - await ensureNativeSubmission({ - collections: this.collections, - submissionId, - projectId: candidate.projectId, - requests: requests.map((request) => ({ - requestId: request._id, - runId: request.submissionInitialRunId!, - })), - createdAt: requests[0]?.createdAt, - }); - await this.collections.requests.updateMany( - { - submissionId, - projectId: candidate.projectId, - submissionExpectedRequestCount: expected, - submissionFinalizedAt: { $exists: false }, - } as Document, - { $set: { submissionFinalizedAt: new Date() } } as Document, - ); - recovered++; - } - return recovered; - } - - async reconcile(submissionId: string): Promise { - let rolled = false; - for (let attempt = 0; attempt < 4; attempt++) { - const submission = await this.collections.submissions.findOne({ - _id: submissionId, - } as Document); - if (!submission) return null; - if ( - submission.run.reconcileAfter && - submission.run.reconcileAfter.getTime() > Date.now() - ) { - return { - submission, - readiness: deriveSubmissionReadiness(submission.run), - rolled, - dispatched: false, - }; - } - if (submission.run.reconcileAfter) { - await this.collections.submissions.updateOne( - { _id: submissionId, "run._id": submission.run._id } as Document, - { - $unset: { "run.reconcileAfter": "" }, - $set: { updatedAt: new Date() }, - } as Document, - ); - delete submission.run.reconcileAfter; - } - if (submission.run.rollover) { - const updated = await archiveAndRoll({ - collections: this.collections, - submission, - requests: submission.run.rollover.requests, - reason: submission.run.rollover.reason, - }); - rolled = true; - if (!updated) continue; - continue; - } - - const requestDocs = await this.collections.requests - .find({ - _id: { $in: submission.requestIds }, - projectId: submission.projectId, - deletedAt: { $exists: false }, - } as Document) - .toArray(); - const byId = new Map(requestDocs.map((request) => [request._id, request])); - const latestVector = submission.requestIds.flatMap((requestId) => { - const runId = byId.get(requestId)?.run?._id; - return runId ? [{ requestId, runId }] : []; - }); - const latestFingerprint = - latestVector.length === submission.requestIds.length - ? computeSubmissionVectorFingerprint(latestVector) - : submission.run.vectorFingerprint; - - if ( - latestVector.length === submission.requestIds.length && - latestFingerprint !== submission.run.vectorFingerprint - ) { - const updated = await archiveAndRoll({ - collections: this.collections, - submission, - requests: latestVector, - reason: "request-vector-changed", - }); - rolled = true; - if (!updated) continue; - continue; - } - - const handlers = await loadPostProcessHandlers(this.collections.services); - const projected = submission.run.requests.map((ref) => - projectSubmissionDependency({ - requestId: ref.requestId, - expectedRunId: ref.runId, - run: byId.get(ref.requestId)?.run, - handlers, - handlerId: OBSERVATIONS_HANDLER_ID, - }), - ); - const dependencyProjection = projected.map((result) => result.projection); - const blocking = projected.flatMap((result) => - result.blocking ? [result.blocking] : [], - ); - const now = new Date(); - const refreshed = await this.collections.submissions.findOneAndUpdate( - { _id: submissionId, "run._id": submission.run._id } as Document, - { - $set: { - "run.dependencyProjection": dependencyProjection, - "run.blocking": blocking, - "run.updatedAt": now, - updatedAt: now, - }, - } as Document, - { returnDocument: "after" }, - ); - if (!refreshed) continue; - - let dispatched = false; - const readiness = deriveSubmissionReadiness(refreshed.run); - if (readiness === "ready" && this.enqueue) { - const service = await loadReadoutService(this.collections.services); - const existing = refreshed.run.handlerStatus?.[READOUT_HANDLER_ID]; - const eligible = - service && - (!existing || - (service.autoBackfill && - existing.status === "done" && - (existing.version ?? 0) < service.version)); - if (service && eligible) { - await this.enqueue(service, { - type: service.selector, - submissionId, - submissionRunId: refreshed.run._id, - }); - const queuedAt = new Date(); - const marked = await this.collections.submissions.updateOne( - { - _id: submissionId, - "run._id": refreshed.run._id, - [`run.handlerStatus.${READOUT_HANDLER_ID}.status`]: { - $nin: ["queued", "processing", "failed"], - }, - } as Document, - { - $set: { - [`run.handlerStatus.${READOUT_HANDLER_ID}`]: { - status: "queued", - version: service.version, - updatedAt: queuedAt, - }, - "run.updatedAt": queuedAt, - updatedAt: queuedAt, - }, - } as Document, - ); - dispatched = marked.modifiedCount === 1; - } - } - const finalSubmission = dispatched - ? await this.collections.submissions.findOne({ _id: submissionId } as Document) - : refreshed; - if (!finalSubmission) return null; - return { - submission: finalSubmission, - readiness: deriveSubmissionReadiness(finalSubmission.run), - rolled, - dispatched, - }; - } - throw new Error(`Submission ${submissionId} could not be reconciled after concurrent updates`); - } - - async retryCurrent( - submissionId: string, - expectedSubmissionRunId: string, - ): Promise { - const reconciled = await this.reconcile(submissionId); - if (!reconciled) return null; - if (reconciled.submission.run._id !== expectedSubmissionRunId) { - return reconciled; - } - if (reconciled.readiness === "blocked" || reconciled.readiness === "waiting") { - return reconciled; - } - const rolled = await archiveAndRoll({ - collections: this.collections, - submission: reconciled.submission, - requests: reconciled.submission.run.requests, - reason: "manual-retry", - }); - if (!rolled) return this.reconcile(submissionId); - return this.reconcile(submissionId); - } -} - -export async function claimSubmissionHandler(input: { - submissions: Collection; - submissionId: string; - submissionRunId: string; - handlerId: string; - version: number; -}): Promise { - const now = new Date(); - return input.submissions.findOneAndUpdate( - { - _id: input.submissionId, - "run._id": input.submissionRunId, - "run.rollover": { $exists: false }, - [`run.handlerStatus.${input.handlerId}.status`]: { $in: ["queued"] }, - } as Document, - { - $set: { - [`run.handlerStatus.${input.handlerId}`]: { - status: "processing", - version: input.version, - updatedAt: now, - }, - "run.startedAt": now, - "run.updatedAt": now, - updatedAt: now, - }, - } as Document, - { returnDocument: "after" }, - ); -} - -export async function isCurrentSubmissionRun(input: { - submissions: Collection; - submissionId: string; - submissionRunId: string; -}): Promise { - return Boolean( - await input.submissions.findOne({ - _id: input.submissionId, - "run._id": input.submissionRunId, - "run.rollover": { $exists: false }, - } as Document), - ); -} - -export async function completeSubmissionHandler(input: { - submissions: Collection; - submissionId: string; - submissionRunId: string; - handlerId: string; - status: "done" | "failed"; - version: number; - error?: string; - report?: SubmissionReportPointer; -}): Promise { - const now = new Date(); - const set: Record = { - [`run.handlerStatus.${input.handlerId}`]: { - status: input.status, - version: input.version, - updatedAt: now, - ...(input.error ? { error: input.error } : {}), - }, - "run.updatedAt": now, - "run.finishedAt": now, - updatedAt: now, - }; - if (input.report) set["run.report"] = input.report; - const result = await input.submissions.updateOne( - { - _id: input.submissionId, - "run._id": input.submissionRunId, - "run.rollover": { $exists: false }, - [`run.handlerStatus.${input.handlerId}.status`]: "processing", - } as Document, - { $set: set } as Document, - ); - return result.modifiedCount === 1; -} diff --git a/packages/shared/src/submissions/submission-state.test.ts b/packages/shared/src/submissions/submission-state.test.ts deleted file mode 100644 index 854558c68..000000000 --- a/packages/shared/src/submissions/submission-state.test.ts +++ /dev/null @@ -1,155 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { describe, expect, it } from "vitest"; -import type { HandlerServiceDocument, RunState, SubmissionRunState } from "../types/types.js"; -import { - OBSERVATIONS_HANDLER_ID, - READOUT_HANDLER_ID, - computeSubmissionVectorFingerprint, - deriveSubmissionReadiness, - evaluateNamedHandlerState, - isHandlerDagDrained, - projectSubmissionDependency, -} from "./submission-state.js"; - -const handlers: HandlerServiceDocument[] = [ - { - _id: "pp-atif", - type: "post-process-handler", - version: 1, - queue: "post-processor", - selector: "atif", - autoBackfill: true, - dependsOn: [], - }, - { - _id: OBSERVATIONS_HANDLER_ID, - type: "post-process-handler", - version: 1, - queue: "post-processor", - selector: "observations", - autoBackfill: true, - dependsOn: ["pp-atif"], - }, -]; - -function run(handlerStatus: RunState["handlerStatus"]): RunState { - return { - _id: "run-1", - attemptNumber: 1, - status: "done", - outcome: "failed", - handlerStatus, - observationResults: [ - { criterionId: "observation-1", passed: false, feedback: "evidence", evaluated: true }, - ], - }; -} - -describe("submission state helpers", () => { - it("fingerprints vectors deterministically independent of request order", () => { - expect( - computeSubmissionVectorFingerprint([ - { requestId: "b", runId: "2" }, - { requestId: "a", runId: "1" }, - ]), - ).toBe( - computeSubmissionVectorFingerprint([ - { requestId: "a", runId: "1" }, - { requestId: "b", runId: "2" }, - ]), - ); - }); - - it("treats completed observations as ready even for failed coding outcomes and passed:false evidence", () => { - const result = projectSubmissionDependency({ - requestId: "request-1", - expectedRunId: "run-1", - run: run({ - [OBSERVATIONS_HANDLER_ID]: { status: "done", version: 1 }, - unrelated: { status: "failed", error: "ignored" }, - }), - handlers, - }); - - expect(result).toEqual({ - projection: { - requestId: "request-1", - runId: "run-1", - handlerId: OBSERVATIONS_HANDLER_ID, - state: "ready", - version: 1, - }, - drifted: false, - }); - }); - - it("blocks when observations fail or are blocked by a failed dependency", () => { - expect( - evaluateNamedHandlerState( - OBSERVATIONS_HANDLER_ID, - handlers, - { [OBSERVATIONS_HANDLER_ID]: { status: "failed" } }, - ), - ).toBe("failed"); - expect( - evaluateNamedHandlerState( - OBSERVATIONS_HANDLER_ID, - handlers, - { "pp-atif": { status: "failed" } }, - ), - ).toBe("blocked"); - }); - - it("reuses named-handler DAG semantics for existing report triggering", () => { - expect( - isHandlerDagDrained(handlers, { - "pp-atif": { status: "failed" }, - }), - ).toBe(true); - expect( - isHandlerDagDrained(handlers, { - "pp-atif": { status: "processing" }, - }), - ).toBe(false); - }); - - it("detects exact run drift", () => { - const result = projectSubmissionDependency({ - requestId: "request-1", - expectedRunId: "old-run", - run: run({ [OBSERVATIONS_HANDLER_ID]: { status: "done" } }), - handlers, - }); - expect(result.drifted).toBe(true); - expect(result.blocking?.reason).toBe("run-changed"); - }); - - it("derives submission readiness from dependencies and readout progress", () => { - const base: SubmissionRunState = { - _id: "submission-run-1", - attemptNumber: 1, - vectorFingerprint: "fingerprint", - requests: [{ requestId: "request-1", runId: "run-1" }], - createdAt: new Date(), - dependencyProjection: [{ - requestId: "request-1", - runId: "run-1", - handlerId: OBSERVATIONS_HANDLER_ID, - state: "ready", - }], - blocking: [], - }; - - expect(deriveSubmissionReadiness(base)).toBe("ready"); - expect(deriveSubmissionReadiness({ - ...base, - handlerStatus: { [READOUT_HANDLER_ID]: { status: "processing" } }, - })).toBe("processing"); - expect(deriveSubmissionReadiness({ - ...base, - handlerStatus: { [READOUT_HANDLER_ID]: { status: "done" } }, - })).toBe("done"); - }); -}); diff --git a/packages/shared/src/submissions/submission-state.ts b/packages/shared/src/submissions/submission-state.ts deleted file mode 100644 index cbaf44452..000000000 --- a/packages/shared/src/submissions/submission-state.ts +++ /dev/null @@ -1,184 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { - HandlerRunStatus, - HandlerServiceDocument, - RunState, - SubmissionBlockingDetail, - SubmissionDependencyProjection, - SubmissionHandlerState, - SubmissionReadiness, - SubmissionRequestRef, - SubmissionRunState, -} from "../types/types.js"; -import { DependencyGraph } from "../graph/dependency-graph.js"; - -export const OBSERVATIONS_HANDLER_ID = "pp-observations"; -export const READOUT_HANDLER_ID = "pp-readout"; - -export function computeSubmissionVectorFingerprint( - requests: readonly SubmissionRequestRef[], -): string { - const canonical = [...requests] - .sort((left, right) => left.requestId.localeCompare(right.requestId)) - .map(({ requestId, runId }) => `${requestId}:${runId}`) - .join("\n"); - let hash = 0xcbf29ce484222325n; - for (let index = 0; index < canonical.length; index++) { - hash ^= BigInt(canonical.charCodeAt(index)); - hash = BigInt.asUintN(64, hash * 0x100000001b3n); - } - return hash.toString(16).padStart(16, "0"); -} - -export function evaluateNamedHandlerState( - handlerId: string, - handlers: readonly HandlerServiceDocument[], - handlerStatus: Record | undefined, -): SubmissionHandlerState { - const status = handlerStatus?.[handlerId]; - if (status?.status === "done") return "ready"; - if (status?.status === "failed") return "failed"; - - const graph = new DependencyGraph( - handlers.map((handler) => ({ - id: handler._id, - dependsOn: handler.dependsOn, - })), - ); - - if (!handlers.some((handler) => handler._id === handlerId)) { - return "waiting"; - } - - for (const ancestorId of graph.getAncestors(handlerId)) { - if (handlerStatus?.[ancestorId]?.status === "failed") return "blocked"; - } - return "waiting"; -} - -function isTerminalHandlerState( - handlerId: string, - graph: DependencyGraph, - handlerStatus: Record | undefined, -): boolean { - const status = handlerStatus?.[handlerId]?.status; - if (status === "done" || status === "failed") return true; - if (status !== undefined) return false; - for (const ancestorId of graph.getAncestors(handlerId)) { - if (handlerStatus?.[ancestorId]?.status === "failed") return true; - } - return false; -} - -export function isHandlerDagDrained( - handlers: readonly HandlerServiceDocument[], - handlerStatus: Record | undefined, -): boolean { - const graph = new DependencyGraph( - handlers.map((handler) => ({ - id: handler._id, - dependsOn: handler.dependsOn, - })), - ); - return handlers.every((handler) => - isTerminalHandlerState(handler._id, graph, handlerStatus), - ); -} - -export function projectSubmissionDependency(input: { - requestId: string; - expectedRunId: string; - run?: RunState; - handlers: readonly HandlerServiceDocument[]; - handlerId?: string; -}): { - projection: SubmissionDependencyProjection; - blocking?: SubmissionBlockingDetail; - drifted: boolean; -} { - const handlerId = input.handlerId ?? OBSERVATIONS_HANDLER_ID; - if (!input.run) { - return { - projection: { - requestId: input.requestId, - runId: input.expectedRunId, - handlerId, - state: "blocked", - }, - blocking: { - requestId: input.requestId, - runId: input.expectedRunId, - handlerId, - reason: "request-missing", - }, - drifted: false, - }; - } - if (input.run._id !== input.expectedRunId) { - return { - projection: { - requestId: input.requestId, - runId: input.expectedRunId, - handlerId, - state: "blocked", - }, - blocking: { - requestId: input.requestId, - runId: input.expectedRunId, - handlerId, - reason: "run-changed", - }, - drifted: true, - }; - } - - const source = input.run.handlerStatus?.[handlerId]; - const state = evaluateNamedHandlerState( - handlerId, - input.handlers, - input.run.handlerStatus, - ); - const projection: SubmissionDependencyProjection = { - requestId: input.requestId, - runId: input.expectedRunId, - handlerId, - state, - ...(source?.version !== undefined ? { version: source.version } : {}), - ...(source?.updatedAt ? { updatedAt: source.updatedAt } : {}), - ...(source?.error ? { error: source.error } : {}), - }; - if (state !== "failed" && state !== "blocked") { - return { projection, drifted: false }; - } - return { - projection, - blocking: { - requestId: input.requestId, - runId: input.expectedRunId, - handlerId, - reason: state === "failed" ? "dependency-failed" : "dependency-blocked", - ...(source?.error ? { error: source.error } : {}), - }, - drifted: false, - }; -} - -export function deriveSubmissionReadiness(run: SubmissionRunState): SubmissionReadiness { - const readout = run.handlerStatus?.[READOUT_HANDLER_ID]; - if (readout?.status === "done") return "done"; - if (readout?.status === "failed") return "failed"; - if (readout?.status === "queued" || readout?.status === "processing") { - return "processing"; - } - if (run.blocking.length > 0) return "blocked"; - if ( - run.requests.length > 0 && - run.dependencyProjection.length === run.requests.length && - run.dependencyProjection.every((dependency) => dependency.state === "ready") - ) { - return "ready"; - } - return "waiting"; -} diff --git a/packages/shared/src/types/types.ts b/packages/shared/src/types/types.ts index 5f8315307..9108cb690 100644 --- a/packages/shared/src/types/types.ts +++ b/packages/shared/src/types/types.ts @@ -384,19 +384,17 @@ export interface RequestDocument { agentVersion?: string; // Agent software version prefix (e.g. "copilot-0.0.415") — FK → AgentVersion.agentVersion profileId?: string; // FK → ProfileDocument._id (the profile lineage) profileVersionId?: string; // FK → ProfileVersionDocument._id (exact version used) - submissionId?: string; // FK → SubmissionDocument._id - /** Expected native request count for interrupted SubmissionDocument finalization. - * Historical/imported requests omit it and remain view-only if their parent - * submission document is missing. */ - submissionExpectedRequestCount?: number; - /** Stable position within the native submission's immutable request vector. */ - submissionRequestIndex?: number; - /** Run id minted for the submission's first attempt. It remains unchanged - * across request retries so recovery can rebuild the exact initial vector. */ - submissionInitialRunId?: string; - /** Set after the parent SubmissionDocument has been idempotently finalized. - * Missing on interrupted native writes so the scheduler can recover them. */ - submissionFinalizedAt?: Date; + experimentId?: string; + experimentRevisionId?: string; + experimentExecutionId?: string; + /** Expected request count for interrupted Experiment finalization. */ + experimentExpectedRequestCount?: number; + /** Stable position within the Experiment's immutable request vector. */ + experimentRequestIndex?: number; + /** Initial run id retained so recovery can rebuild the exact first vector. */ + experimentInitialRunId?: string; + /** Set only after the parent Experiment has been published. */ + experimentFinalizedAt?: Date; /** Scheduling priority. Higher = processed first. Default: 0. */ priority: number; /** @@ -579,9 +577,9 @@ export interface HandlerServiceDocument { dependsOn: string[]; } -export interface SubmissionHandlerServiceDocument { +export interface ExperimentHandlerServiceDocument { _id: string; - type: "submission-handler"; + type: "experiment-handler"; version: number; queue: string; selector: string; @@ -592,104 +590,7 @@ export interface SubmissionHandlerServiceDocument { export type ServiceHandlerDocument = | HandlerServiceDocument - | SubmissionHandlerServiceDocument; - -export interface SubmissionRequestRef { - requestId: string; - runId: string; -} - -export type SubmissionHandlerState = "waiting" | "ready" | "failed" | "blocked"; - -export interface SubmissionDependencyProjection { - requestId: string; - runId: string; - handlerId: string; - state: SubmissionHandlerState; - version?: number; - updatedAt?: Date; - error?: string; -} - -export interface SubmissionBlockingDetail { - requestId: string; - runId: string; - handlerId: string; - reason: - | "request-missing" - | "run-changed" - | "dependency-not-ready" - | "dependency-failed" - | "dependency-blocked"; - error?: string; -} - -export interface SubmissionReportPointer { - reportId?: string; - url?: string; - updatedAt?: Date; -} - -export interface SubmissionRolloverClaim { - nextSubmissionRunId: string; - vectorFingerprint: string; - requests: SubmissionRequestRef[]; - reason: "request-vector-changed" | "manual-retry"; - claimedAt: Date; -} - -export interface SubmissionRunState { - _id: string; - attemptNumber: number; - vectorFingerprint: string; - requests: SubmissionRequestRef[]; - createdAt: Date; - updatedAt?: Date; - startedAt?: Date; - finishedAt?: Date; - dependencyProjection: SubmissionDependencyProjection[]; - handlerStatus?: Record; - blocking: SubmissionBlockingDetail[]; - report?: SubmissionReportPointer; - /** Internal scheduler hold used by bulk request retry so one completed - * replacement batch produces one vector rollover. Expiry self-heals crashes. */ - reconcileAfter?: Date; - /** Internal resumable rollover claim. Its CAS winner exclusively determines - * the immutable archive's successor metadata. */ - rollover?: SubmissionRolloverClaim; - supersededAt?: Date; - supersededBySubmissionRunId?: string; - supersededReason?: "request-vector-changed" | "manual-retry"; -} - -export interface SubmissionDocument { - _id: string; - submissionId: string; - projectId: string; - requestIds: string[]; - createdAt: Date; - updatedAt?: Date; - run: SubmissionRunState; -} - -export interface SubmissionRunHistoryDocument extends SubmissionRunState { - submissionId: string; - projectId: string; -} - -export type SubmissionReadiness = - | "waiting" - | "ready" - | "blocked" - | "processing" - | "done" - | "failed"; - -export interface SubmissionQueueMessagePayload { - type: string; - submissionId: string; - submissionRunId: string; -} + | ExperimentHandlerServiceDocument; /** * Field names whose values move from `RequestDocument` (top-level, legacy @@ -824,7 +725,7 @@ export interface QueueProcessorConfig extends BaseQueueProcessorConfig { // --- Runs grouping types (shared between API and portal) --- -export type GroupByKey = "none" | "task" | "submissionId" | "profile"; +export type GroupByKey = "none" | "task" | "experimentId" | "profile"; export interface AggregateStats { min: number; @@ -842,7 +743,7 @@ export interface GroupUniformValues { skillRevisions?: string[]; extensions?: string[]; status?: "pending" | "processing" | "done"; - submissionId?: string; + experimentId?: string; task?: string; } From ed1ca2c6bdc53ac38834b8bfed865a343f2385a6 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Thu, 15 Oct 2026 22:39:12 -0700 Subject: [PATCH 047/210] feat(experiments): add canonical API runtime Replace legacy Submission API and scheduler surfaces with project-scoped Experiment creation, execution history, retry, exact queue claims, recovery, and OpenAPI contracts. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: b05e74ff-44da-4e78-9f05-0e256009e7ee --- .../openapi-snapshot.test.ts.snap | 1344 ++++++++++++++--- apps/api/src/endpoints.test.ts | 80 +- apps/api/src/experiment-openapi.test.ts | 68 + apps/api/src/grouping.test.ts | 10 +- apps/api/src/grouping.ts | 14 +- apps/api/src/index.ts | 33 +- apps/api/src/openapi/openapi.test.ts | 2 +- apps/api/src/route-context.ts | 12 +- apps/api/src/routes/experiments.test.ts | 247 +++ apps/api/src/routes/experiments.ts | 691 +++++++++ apps/api/src/routes/profiles.ts | 2 +- apps/api/src/routes/requests/archive.test.ts | 2 - apps/api/src/routes/requests/index.ts | 171 +-- apps/api/src/routes/submissions.test.ts | 253 ---- apps/api/src/routes/submissions.ts | 245 --- apps/api/src/test-helpers.ts | 15 +- apps/api/src/utils/agent-helpers.ts | 2 +- apps/api/src/utils/codebase-helpers.ts | 2 +- .../src/experiment-coordinator.test.ts | 365 +++++ apps/scheduler/src/experiment-coordinator.ts | 527 +++++++ apps/scheduler/src/experiment-dispatcher.ts | 169 +++ apps/scheduler/src/handler-dispatcher.ts | 28 +- apps/scheduler/src/index.ts | 39 +- apps/scheduler/src/notify-routes.test.ts | 188 +++ apps/scheduler/src/notify-routes.ts | 122 +- apps/scheduler/src/submission-dispatcher.ts | 112 -- packages/shared/src/cursor.test.ts | 6 +- .../src/experiments/experiment-store.test.ts | 60 +- .../src/experiments/experiment-store.ts | 6 + packages/shared/src/experiments/schemas.ts | 3 + packages/shared/src/experiments/types.ts | 3 + packages/shared/src/schemas/request.ts | 21 +- packages/shared/src/types/types.ts | 22 +- 33 files changed, 3798 insertions(+), 1066 deletions(-) create mode 100644 apps/api/src/experiment-openapi.test.ts create mode 100644 apps/api/src/routes/experiments.test.ts create mode 100644 apps/api/src/routes/experiments.ts delete mode 100644 apps/api/src/routes/submissions.test.ts delete mode 100644 apps/api/src/routes/submissions.ts create mode 100644 apps/scheduler/src/experiment-coordinator.test.ts create mode 100644 apps/scheduler/src/experiment-coordinator.ts create mode 100644 apps/scheduler/src/experiment-dispatcher.ts delete mode 100644 apps/scheduler/src/submission-dispatcher.ts diff --git a/apps/api/src/__snapshots__/openapi-snapshot.test.ts.snap b/apps/api/src/__snapshots__/openapi-snapshot.test.ts.snap index 317154c30..c1d80e316 100644 --- a/apps/api/src/__snapshots__/openapi-snapshot.test.ts.snap +++ b/apps/api/src/__snapshots__/openapi-snapshot.test.ts.snap @@ -721,6 +721,158 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` ], "type": "object", }, + "CreateExperimentInput": { + "properties": { + "metadata": { + "properties": { + "description": { + "maxLength": 4096, + "type": "string", + }, + "name": { + "maxLength": 256, + "minLength": 1, + "type": "string", + }, + "tags": { + "items": { + "maxLength": 64, + "minLength": 1, + "type": "string", + }, + "maxItems": 32, + "type": "array", + }, + }, + "required": [ + "name", + ], + "type": "object", + }, + "mode": { + "enum": [ + "compose", + "empty", + ], + "type": "string", + }, + "requests": { + "default": [], + "items": { + "properties": { + "agentsMd": { + "type": "string", + }, + "agentsMdParentIds": { + "items": { + "type": "string", + }, + "type": "array", + }, + "codebaseRevisionId": { + "type": "string", + }, + "extensions": { + "items": { + "type": "string", + }, + "type": "array", + }, + "gates": { + "items": { + "$ref": "#/components/schemas/GateConfig", + }, + "type": "array", + }, + "maxIterations": { + "maximum": 50, + "minimum": 1, + "type": "integer", + }, + "mcpServers": { + "items": { + "type": "string", + }, + "type": "array", + }, + "model": { + "type": "string", + }, + "observations": { + "items": { + "type": "string", + }, + "type": "array", + }, + "persona": { + "$ref": "#/components/schemas/Persona", + }, + "personaInstructions": { + "type": "string", + }, + "priority": { + "type": "integer", + }, + "profileId": { + "type": "string", + }, + "reasoningEffort": { + "type": "string", + }, + "resources": { + "items": { + "$ref": "#/components/schemas/ResourceBindingSpec", + }, + "type": "array", + }, + "scenario": { + "$ref": "#/components/schemas/Scenario", + }, + "skillRevisions": { + "items": { + "type": "string", + }, + "type": "array", + }, + "workerType": { + "minLength": 1, + "type": "string", + }, + }, + "required": [ + "scenario", + "workerType", + ], + "type": "object", + }, + "maxItems": 250000, + "type": "array", + }, + }, + "required": [ + "mode", + "metadata", + ], + "type": "object", + }, + "CreateExperimentResponse": { + "properties": { + "experiment": { + "$ref": "#/components/schemas/ExperimentResponse", + }, + "requestIds": { + "items": { + "type": "string", + }, + "type": "array", + }, + }, + "required": [ + "experiment", + "requestIds", + ], + "type": "object", + }, "CreateExtensionInput": { "properties": { "_id": { @@ -986,6 +1138,8 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "type": "string", }, "profileVariations": { + "deprecated": true, + "description": "Deprecated for composition. Use POST /api/v1/experiments and its requests array.", "items": { "type": "string", }, @@ -1349,11 +1503,55 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` ], "type": "object", }, - "ExtensionResponse": { + "ExperimentExecutionListResponse": { "properties": { - "_id": { + "data": { + "items": { + "$ref": "#/components/schemas/ExperimentExecutionResponse", + }, + "type": "array", + }, + "nextCursor": { "type": "string", }, + }, + "required": [ + "data", + ], + "type": "object", + }, + "ExperimentExecutionResponse": { + "properties": { + "attemptNumber": { + "type": "integer", + }, + "blockers": { + "items": { + "properties": { + "error": { + "type": "string", + }, + "handlerId": { + "type": "string", + }, + "reason": { + "type": "string", + }, + "requestId": { + "type": "string", + }, + "runId": { + "type": "string", + }, + }, + "required": [ + "handlerId", + "reason", + ], + "type": "object", + }, + "type": "array", + }, "createdAt": { "format": "date-time", "type": [ @@ -1361,33 +1559,91 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "null", ], }, - "deletedAt": { + "discardReason": { + "type": "string", + }, + "discardedAt": { "format": "date-time", "type": [ "string", "null", ], }, - "description": { + "experimentExecutionId": { "type": "string", }, - "name": { - "type": "string", + "finishedAt": { + "format": "date-time", + "type": [ + "string", + "null", + ], }, - "origin": { + "progress": { + "additionalProperties": { + "properties": { + "error": { + "type": "string", + }, + "status": { + "enum": [ + "queued", + "processing", + "done", + "failed", + ], + "type": "string", + }, + "updatedAt": { + "format": "date-time", + "type": [ + "string", + "null", + ], + }, + }, + "required": [ + "status", + "updatedAt", + ], + "type": "object", + }, + "type": "object", + }, + "readiness": { "enum": [ - "marketplace", - "manual", + "empty", + "waiting", + "blocked", + "ready", + "processing", + "done", + "failed", ], "type": "string", }, - "projectId": { - "type": "string", + "startedAt": { + "format": "date-time", + "type": [ + "string", + "null", + ], }, - "publisher": { + "supersededAt": { + "format": "date-time", + "type": [ + "string", + "null", + ], + }, + "supersededByExperimentExecutionId": { "type": "string", }, - "slug": { + "supersededReason": { + "enum": [ + "rollover", + "retry", + ], "type": "string", }, "updatedAt": { @@ -1399,83 +1655,396 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` }, }, "required": [ - "_id", - "slug", - "publisher", - "name", - "origin", + "experimentExecutionId", + "attemptNumber", + "readiness", + "blockers", + "progress", "createdAt", - "projectId", - ], - "type": "object", - }, - "ExtensionSearchResult": { - "properties": { - "description": { - "type": "string", - }, - "id": { - "type": "string", - }, - "internal": { - "type": "boolean", - }, - "name": { - "type": "string", - }, - "publisher": { - "type": "string", - }, - "version": { - "type": "string", - }, - }, - "required": [ - "id", - "name", - "publisher", - "internal", + "updatedAt", ], "type": "object", }, - "ExtensionVersionInfo": { + "ExperimentListResponse": { "properties": { - "lastUpdated": { - "type": "string", - }, - "preRelease": { - "type": "boolean", + "data": { + "items": { + "$ref": "#/components/schemas/ExperimentResponse", + }, + "type": "array", }, - "version": { + "nextCursor": { "type": "string", }, }, "required": [ - "version", - "preRelease", - "lastUpdated", + "data", ], "type": "object", }, - "FeatureFlagResponse": { + "ExperimentResponse": { "properties": { - "enabled": { - "type": "boolean", - }, - "key": { - "type": "string", - }, - "label": { - "type": "string", - }, - "updatedAt": { + "createdAt": { "format": "date-time", "type": [ "string", "null", ], }, - }, + "currentExecution": { + "properties": { + "attemptNumber": { + "type": "integer", + }, + "blockers": { + "items": { + "properties": { + "error": { + "type": "string", + }, + "handlerId": { + "type": "string", + }, + "reason": { + "type": "string", + }, + "requestId": { + "type": "string", + }, + "runId": { + "type": "string", + }, + }, + "required": [ + "handlerId", + "reason", + ], + "type": "object", + }, + "type": "array", + }, + "createdAt": { + "format": "date-time", + "type": [ + "string", + "null", + ], + }, + "discardReason": { + "type": "string", + }, + "discardedAt": { + "format": "date-time", + "type": [ + "string", + "null", + ], + }, + "experimentExecutionId": { + "type": "string", + }, + "finishedAt": { + "format": "date-time", + "type": [ + "string", + "null", + ], + }, + "progress": { + "additionalProperties": { + "properties": { + "error": { + "type": "string", + }, + "status": { + "enum": [ + "queued", + "processing", + "done", + "failed", + ], + "type": "string", + }, + "updatedAt": { + "format": "date-time", + "type": [ + "string", + "null", + ], + }, + }, + "required": [ + "status", + "updatedAt", + ], + "type": "object", + }, + "type": "object", + }, + "readiness": { + "enum": [ + "empty", + "waiting", + "blocked", + "ready", + "processing", + "done", + "failed", + ], + "type": "string", + }, + "report": { + "properties": { + "reportId": { + "type": "string", + }, + "updatedAt": { + "format": "date-time", + "type": [ + "string", + "null", + ], + }, + "url": { + "type": "string", + }, + }, + "type": "object", + }, + "startedAt": { + "format": "date-time", + "type": [ + "string", + "null", + ], + }, + "updatedAt": { + "format": "date-time", + "type": [ + "string", + "null", + ], + }, + }, + "required": [ + "experimentExecutionId", + "attemptNumber", + "readiness", + "blockers", + "progress", + "createdAt", + "updatedAt", + ], + "type": "object", + }, + "experimentId": { + "type": "string", + }, + "metadata": { + "properties": { + "createdBy": { + "type": "string", + }, + "description": { + "maxLength": 4096, + "type": "string", + }, + "name": { + "maxLength": 256, + "minLength": 1, + "type": "string", + }, + "tags": { + "items": { + "maxLength": 64, + "minLength": 1, + "type": "string", + }, + "maxItems": 32, + "type": "array", + }, + }, + "required": [ + "name", + ], + "type": "object", + }, + "projectId": { + "type": "string", + }, + "revision": { + "properties": { + "createdAt": { + "format": "date-time", + "type": [ + "string", + "null", + ], + }, + "experimentRevisionId": { + "type": "string", + }, + "memberCount": { + "type": "integer", + }, + "revisionNumber": { + "type": "integer", + }, + }, + "required": [ + "experimentRevisionId", + "revisionNumber", + "memberCount", + "createdAt", + ], + "type": "object", + }, + "updatedAt": { + "format": "date-time", + "type": [ + "string", + "null", + ], + }, + }, + "required": [ + "experimentId", + "projectId", + "metadata", + "revision", + "currentExecution", + "createdAt", + "updatedAt", + ], + "type": "object", + }, + "ExtensionResponse": { + "properties": { + "_id": { + "type": "string", + }, + "createdAt": { + "format": "date-time", + "type": [ + "string", + "null", + ], + }, + "deletedAt": { + "format": "date-time", + "type": [ + "string", + "null", + ], + }, + "description": { + "type": "string", + }, + "name": { + "type": "string", + }, + "origin": { + "enum": [ + "marketplace", + "manual", + ], + "type": "string", + }, + "projectId": { + "type": "string", + }, + "publisher": { + "type": "string", + }, + "slug": { + "type": "string", + }, + "updatedAt": { + "format": "date-time", + "type": [ + "string", + "null", + ], + }, + }, + "required": [ + "_id", + "slug", + "publisher", + "name", + "origin", + "createdAt", + "projectId", + ], + "type": "object", + }, + "ExtensionSearchResult": { + "properties": { + "description": { + "type": "string", + }, + "id": { + "type": "string", + }, + "internal": { + "type": "boolean", + }, + "name": { + "type": "string", + }, + "publisher": { + "type": "string", + }, + "version": { + "type": "string", + }, + }, + "required": [ + "id", + "name", + "publisher", + "internal", + ], + "type": "object", + }, + "ExtensionVersionInfo": { + "properties": { + "lastUpdated": { + "type": "string", + }, + "preRelease": { + "type": "boolean", + }, + "version": { + "type": "string", + }, + }, + "required": [ + "version", + "preRelease", + "lastUpdated", + ], + "type": "object", + }, + "FeatureFlagResponse": { + "properties": { + "enabled": { + "type": "boolean", + }, + "key": { + "type": "string", + }, + "label": { + "type": "string", + }, + "updatedAt": { + "format": "date-time", + "type": [ + "string", + "null", + ], + }, + }, "required": [ "key", "label", @@ -1601,6 +2170,9 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "codebaseRevisionId": { "type": "string", }, + "experimentId": { + "type": "string", + }, "extensions": { "items": { "type": "string", @@ -1635,9 +2207,6 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` ], "type": "string", }, - "submissionId": { - "type": "string", - }, "task": { "type": "string", }, @@ -2741,6 +3310,27 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "null", ], }, + "experimentExpectedRequestCount": { + "minimum": 0, + "type": "integer", + }, + "experimentFinalizedAt": { + "format": "date-time", + "type": [ + "string", + "null", + ], + }, + "experimentId": { + "type": "string", + }, + "experimentInitialRunId": { + "type": "string", + }, + "experimentRequestIndex": { + "minimum": 0, + "type": "integer", + }, "extensions": { "items": { "type": "string", @@ -2817,9 +3407,6 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` }, "type": "array", }, - "submissionId": { - "type": "string", - }, "taskPromptId": { "type": "string", }, @@ -3109,6 +3696,66 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` }, "type": "object", }, + "RetryExperimentResponse": { + "properties": { + "attemptNumber": { + "type": "integer", + }, + "blockers": { + "items": { + "properties": { + "error": { + "type": "string", + }, + "handlerId": { + "type": "string", + }, + "reason": { + "type": "string", + }, + "requestId": { + "type": "string", + }, + "runId": { + "type": "string", + }, + }, + "required": [ + "handlerId", + "reason", + ], + "type": "object", + }, + "type": "array", + }, + "experimentExecutionId": { + "type": "string", + }, + "experimentId": { + "type": "string", + }, + "readiness": { + "enum": [ + "empty", + "waiting", + "blocked", + "ready", + "processing", + "done", + "failed", + ], + "type": "string", + }, + }, + "required": [ + "experimentId", + "experimentExecutionId", + "attemptNumber", + "readiness", + "blockers", + ], + "type": "object", + }, "RunFacetBucket": { "properties": { "count": { @@ -4690,7 +5337,7 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` }, { "in": "query", - "name": "submissionId", + "name": "experimentId", "required": false, "schema": { "type": "string", @@ -5198,10 +5845,252 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` }, }, "required": [ - "prompt", - "suggestedId", - "suggestedParents", - "suggestedChildren", + "prompt", + "suggestedId", + "suggestedParents", + "suggestedChildren", + ], + "type": "object", + }, + }, + }, + "description": "Success", + }, + "400": { + "description": "Empty behavior string", + }, + "503": { + "description": "LLM not configured", + }, + }, + "summary": "Generate criterion prompt from behavior", + "tags": [ + "Criteria", + ], + }, + }, + "/api/v1/criteria/graph": { + "get": { + "parameters": [ + { + "description": "Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.", + "in": "query", + "name": "projectId", + "required": true, + "schema": { + "description": "Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.", + "example": "00000000-0000-0000-0000-000000000000", + "minLength": 1, + "type": "string", + }, + }, + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CriteriaGraph", + }, + }, + }, + "description": "Success", + }, + }, + "summary": "Get criteria DAG", + "tags": [ + "Criteria", + ], + }, + }, + "/api/v1/criteria/mdp": { + "get": { + "parameters": [ + { + "in": "query", + "name": "criteria", + "required": false, + "schema": { + "type": "string", + }, + }, + { + "in": "query", + "name": "features", + "required": false, + "schema": { + "type": "string", + }, + }, + { + "in": "query", + "name": "since", + "required": false, + "schema": { + "type": "string", + }, + }, + { + "in": "query", + "name": "worker", + "required": false, + "schema": { + "type": "string", + }, + }, + { + "in": "query", + "name": "taskPromptId", + "required": false, + "schema": { + "type": "string", + }, + }, + { + "description": "Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.", + "in": "query", + "name": "projectId", + "required": true, + "schema": { + "description": "Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.", + "example": "00000000-0000-0000-0000-000000000000", + "minLength": 1, + "type": "string", + }, + }, + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "additionalProperties": {}, + "properties": {}, + "type": "object", + }, + }, + }, + "description": "Success", + }, + }, + "summary": "Compute MDP transitions", + "tags": [ + "Criteria", + ], + }, + }, + "/api/v1/criteria/seed": { + "post": { + "parameters": [ + { + "description": "Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.", + "in": "query", + "name": "projectId", + "required": true, + "schema": { + "description": "Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.", + "example": "00000000-0000-0000-0000-000000000000", + "minLength": 1, + "type": "string", + }, + }, + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "properties": { + "criteria": { + "items": { + "$ref": "#/components/schemas/CreateCriteriaInput", + }, + "type": "array", + }, + }, + "required": [ + "criteria", + ], + "type": "object", + }, + }, + }, + }, + "responses": { + "201": { + "content": { + "application/json": { + "schema": { + "properties": { + "errors": { + "items": { + "type": "string", + }, + "type": "array", + }, + "seeded": { + "type": "number", + }, + }, + "required": [ + "seeded", + "errors", + ], + "type": "object", + }, + }, + }, + "description": "Success", + }, + "400": { + "description": "Seed batch would introduce a dependency cycle", + }, + }, + "summary": "Seed criteria in bulk", + "tags": [ + "Criteria", + ], + }, + }, + "/api/v1/criteria/{id}": { + "delete": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "string", + }, + }, + { + "description": "Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.", + "in": "query", + "name": "projectId", + "required": true, + "schema": { + "description": "Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.", + "example": "00000000-0000-0000-0000-000000000000", + "minLength": 1, + "type": "string", + }, + }, + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "properties": { + "deleted": { + "type": "boolean", + }, + "id": { + "type": "string", + }, + }, + "required": [ + "id", + "deleted", ], "type": "object", }, @@ -5209,22 +6098,28 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` }, "description": "Success", }, - "400": { - "description": "Empty behavior string", + "404": { + "description": "Criterion not found", }, - "503": { - "description": "LLM not configured", + "409": { + "description": "Criterion has dependents", }, }, - "summary": "Generate criterion prompt from behavior", + "summary": "Soft-delete criterion", "tags": [ "Criteria", ], }, - }, - "/api/v1/criteria/graph": { "get": { "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "string", + }, + }, { "description": "Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.", "in": "query", @@ -5243,70 +6138,108 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CriteriaGraph", + "$ref": "#/components/schemas/CriteriaResponse", }, }, }, "description": "Success", }, + "404": { + "description": "Criterion not found", + }, }, - "summary": "Get criteria DAG", + "summary": "Get criterion", "tags": [ "Criteria", ], }, - }, - "/api/v1/criteria/mdp": { - "get": { + "put": { "parameters": [ { - "in": "query", - "name": "criteria", - "required": false, + "in": "path", + "name": "id", + "required": true, "schema": { "type": "string", }, }, { + "description": "Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.", "in": "query", - "name": "features", - "required": false, + "name": "projectId", + "required": true, "schema": { + "description": "Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.", + "example": "00000000-0000-0000-0000-000000000000", + "minLength": 1, "type": "string", }, }, - { - "in": "query", - "name": "since", - "required": false, - "schema": { - "type": "string", + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateCriteriaInput", + }, }, }, + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CriteriaResponse", + }, + }, + }, + "description": "Success", + }, + "400": { + "description": "Invalid dependency reference or self-reference", + }, + "404": { + "description": "Criterion not found", + }, + }, + "summary": "Update criterion", + "tags": [ + "Criteria", + ], + }, + }, + "/api/v1/experiments": { + "get": { + "parameters": [ { + "description": "Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.", "in": "query", - "name": "worker", - "required": false, + "name": "projectId", + "required": true, "schema": { + "description": "Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.", + "example": "00000000-0000-0000-0000-000000000000", + "minLength": 1, "type": "string", }, }, { "in": "query", - "name": "taskPromptId", + "name": "limit", "required": false, "schema": { - "type": "string", + "default": 50, + "maximum": 100, + "minimum": 1, + "type": "integer", }, }, { - "description": "Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.", "in": "query", - "name": "projectId", - "required": true, + "name": "after", + "required": false, "schema": { - "description": "Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.", - "example": "00000000-0000-0000-0000-000000000000", "minLength": 1, "type": "string", }, @@ -5317,23 +6250,20 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "content": { "application/json": { "schema": { - "additionalProperties": {}, - "properties": {}, - "type": "object", + "$ref": "#/components/schemas/ExperimentListResponse", }, }, }, "description": "Success", }, }, - "summary": "Compute MDP transitions", + "summary": "List experiments", "tags": [ - "Criteria", + "Experiments", ], }, - }, - "/api/v1/criteria/seed": { "post": { + "description": "Canonical composition endpoint. Request and run IDs are minted before insertion; the exact revision/execution is then finalized idempotently.", "parameters": [ { "description": "Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.", @@ -5352,18 +6282,7 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "content": { "application/json": { "schema": { - "properties": { - "criteria": { - "items": { - "$ref": "#/components/schemas/CreateCriteriaInput", - }, - "type": "array", - }, - }, - "required": [ - "criteria", - ], - "type": "object", + "$ref": "#/components/schemas/CreateExperimentInput", }, }, }, @@ -5373,45 +6292,31 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "content": { "application/json": { "schema": { - "properties": { - "errors": { - "items": { - "type": "string", - }, - "type": "array", - }, - "seeded": { - "type": "number", - }, - }, - "required": [ - "seeded", - "errors", - ], - "type": "object", + "$ref": "#/components/schemas/CreateExperimentResponse", }, }, }, "description": "Success", }, - "400": { - "description": "Seed batch would introduce a dependency cycle", + "409": { + "description": "Experiment identity conflict", }, }, - "summary": "Seed criteria in bulk", + "summary": "Create an experiment and zero or more new requests", "tags": [ - "Criteria", + "Experiments", ], }, }, - "/api/v1/criteria/{id}": { - "delete": { + "/api/v1/experiments/{id}": { + "get": { "parameters": [ { "in": "path", "name": "id", "required": true, "schema": { + "minLength": 1, "type": "string", }, }, @@ -5433,36 +6338,23 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "content": { "application/json": { "schema": { - "properties": { - "deleted": { - "type": "boolean", - }, - "id": { - "type": "string", - }, - }, - "required": [ - "id", - "deleted", - ], - "type": "object", + "$ref": "#/components/schemas/ExperimentResponse", }, }, }, "description": "Success", }, "404": { - "description": "Criterion not found", - }, - "409": { - "description": "Criterion has dependents", + "description": "Experiment not found", }, }, - "summary": "Soft-delete criterion", + "summary": "Get an experiment", "tags": [ - "Criteria", + "Experiments", ], }, + }, + "/api/v1/experiments/{id}/executions": { "get": { "parameters": [ { @@ -5470,17 +6362,69 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "name": "id", "required": true, "schema": { + "minLength": 1, "type": "string", }, }, { - "description": "Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.", "in": "query", - "name": "projectId", + "name": "limit", + "required": false, + "schema": { + "default": 50, + "maximum": 100, + "minimum": 1, + "type": "integer", + }, + }, + { + "in": "query", + "name": "after", + "required": false, + "schema": { + "minLength": 1, + "type": "string", + }, + }, + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ExperimentExecutionListResponse", + }, + }, + }, + "description": "Success", + }, + "404": { + "description": "Experiment not found", + }, + }, + "summary": "List current and historical experiment executions", + "tags": [ + "Experiments", + ], + }, + }, + "/api/v1/experiments/{id}/executions/{experimentExecutionId}": { + "get": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "minLength": 1, + "type": "string", + }, + }, + { + "in": "path", + "name": "experimentExecutionId", "required": true, "schema": { - "description": "Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.", - "example": "00000000-0000-0000-0000-000000000000", "minLength": 1, "type": "string", }, @@ -5491,28 +6435,31 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CriteriaResponse", + "$ref": "#/components/schemas/ExperimentExecutionResponse", }, }, }, "description": "Success", }, "404": { - "description": "Criterion not found", + "description": "Experiment execution not found", }, }, - "summary": "Get criterion", + "summary": "Get one exact experiment execution", "tags": [ - "Criteria", + "Experiments", ], }, - "put": { + }, + "/api/v1/experiments/{id}/retry": { + "post": { "parameters": [ { "in": "path", "name": "id", "required": true, "schema": { + "minLength": 1, "type": "string", }, }, @@ -5533,32 +6480,41 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UpdateCriteriaInput", + "properties": { + "experimentExecutionId": { + "minLength": 1, + "type": "string", + }, + }, + "required": [ + "experimentExecutionId", + ], + "type": "object", }, }, }, }, "responses": { - "200": { + "201": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CriteriaResponse", + "$ref": "#/components/schemas/RetryExperimentResponse", }, }, }, "description": "Success", }, - "400": { - "description": "Invalid dependency reference or self-reference", - }, "404": { - "description": "Criterion not found", + "description": "Experiment not found", + }, + "409": { + "description": "Execution is stale or cannot be retried", }, }, - "summary": "Update criterion", + "summary": "Retry current experiment processing", "tags": [ - "Criteria", + "Experiments", ], }, }, @@ -8828,7 +9784,7 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` }, { "in": "query", - "name": "submissionId", + "name": "experimentId", "required": false, "schema": { "type": "string", @@ -8975,7 +9931,7 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "schema": { "enum": [ "task", - "submissionId", + "experimentId", "profile", ], "type": "string", @@ -9194,6 +10150,8 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` }, "count": { "default": 1, + "deprecated": true, + "description": "Deprecated for composition. Use POST /api/v1/experiments and its requests array.", "maximum": 10, "minimum": 1, "type": "number", diff --git a/apps/api/src/endpoints.test.ts b/apps/api/src/endpoints.test.ts index c105562c7..893288464 100644 --- a/apps/api/src/endpoints.test.ts +++ b/apps/api/src/endpoints.test.ts @@ -766,19 +766,19 @@ describe("API Endpoints", () => { expect(res.body.data[0]).toHaveProperty("uniform"); }); - it("returns grouped results when groupBy=submissionId", async () => { + it("returns grouped results when groupBy=experimentId", async () => { const groupedDocs = [ - { key: "sub-1", label: "sub-1", aggregates: { count: 2, turns: null, duration: null, promptTokens: null, completionTokens: null }, uniform: {} }, + { key: "experiment-1", label: "experiment-1", aggregates: { count: 2, turns: null, duration: null, promptTokens: null, completionTokens: null }, uniform: {} }, ]; (mocks.collection.aggregate as any) - .mockReturnValueOnce({ toArray: vi.fn().mockResolvedValue([{ _id: "sub-1" }]) }) + .mockReturnValueOnce({ toArray: vi.fn().mockResolvedValue([{ _id: "experiment-1" }]) }) .mockReturnValueOnce({ toArray: vi.fn().mockResolvedValue(groupedDocs) }) .mockReturnValueOnce({ toArray: vi.fn().mockResolvedValue([]) }) .mockReturnValueOnce({ toArray: vi.fn().mockResolvedValue([]) }); - const res = await request(testServer()).get(`/api/v1/requests?groupBy=submissionId&projectId=${TEST_PROJECT_ID}`); + const res = await request(testServer()).get(`/api/v1/requests?groupBy=experimentId&projectId=${TEST_PROJECT_ID}`); expect(res.status).toBe(200); - expect(res.body.data[0]).toHaveProperty("key", "sub-1"); + expect(res.body.data[0]).toHaveProperty("key", "experiment-1"); }); it("calls aggregate pipeline when groupBy is provided", async () => { @@ -1955,15 +1955,14 @@ describe("API Endpoints", () => { expect(res.status).toBe(201); const doc = (mocks.collection.insertOne as any).mock.calls[0][0]; expect(doc).toHaveProperty("reasoningEffort", "high"); - expect(doc).toHaveProperty("submissionExpectedRequestCount", 1); - const submissionInsert = (mocks.submissionCollection.updateOne as any).mock.calls[0][1].$setOnInsert; - expect(submissionInsert.requestIds).toEqual([doc._id]); - expect(submissionInsert.run.requests).toEqual([ - { requestId: doc._id, runId: doc.run._id }, - ]); + expect(doc).not.toHaveProperty("experimentId"); + expect(mocks.experimentCollection.updateOne).not.toHaveBeenCalled(); + expect(res.headers).not.toHaveProperty("deprecation"); + expect(res.headers).not.toHaveProperty("link"); + expect(res.headers).not.toHaveProperty("sunset"); }); - it("creates one complete submission vector for count fan-out", async () => { + it("keeps count fan-out independent from experiments", async () => { const res = await request(testServer()) .post(`/api/v1/requests?worker=coder-acp-copilot&projectId=${TEST_PROJECT_ID}`) .send({ @@ -1974,25 +1973,13 @@ describe("API Endpoints", () => { expect(res.status).toBe(201); const docs = (mocks.collection.insertMany as any).mock.calls[0][0]; expect(docs).toHaveLength(3); - expect(docs.every((doc: { submissionExpectedRequestCount: number }) => - doc.submissionExpectedRequestCount === 3)).toBe(true); - expect( - docs.map((doc: { submissionRequestIndex: number }) => doc.submissionRequestIndex), - ).toEqual([0, 1, 2]); - expect( - docs.every( - (doc: { submissionInitialRunId: string; run: { _id: string } }) => - doc.submissionInitialRunId === doc.run._id, - ), - ).toBe(true); - const submissionInsert = (mocks.submissionCollection.updateOne as any).mock.calls[0][1].$setOnInsert; - expect(submissionInsert.requestIds).toEqual(docs.map((doc: { _id: string }) => doc._id)); - expect(submissionInsert.run.requests).toEqual( - docs.map((doc: { _id: string; run: { _id: string } }) => ({ - requestId: doc._id, - runId: doc.run._id, - })), + expect(docs.every((doc: object) => !("experimentId" in doc))).toBe(true); + expect(mocks.experimentCollection.updateOne).not.toHaveBeenCalled(); + expect(res.headers.deprecation).toBe("true"); + expect(res.headers.link).toBe( + '; rel="successor-version"; title="POST /api/v1/experiments"', ); + expect(res.headers).not.toHaveProperty("sunset"); }); it("profile reasoningEffort takes precedence over client-provided effort", async () => { @@ -2297,7 +2284,7 @@ describe("API Endpoints", () => { new Set(["base-profile", "var-profile"]), ); for (const doc of docs) { - expect(doc.submissionExpectedRequestCount).toBe(2); + expect(doc.experimentId).toBeUndefined(); expect(Array.isArray(doc.gates)).toBe(true); const selectGate = doc.gates.find((g: { gate: string }) => g.gate === "select"); const buildGate = doc.gates.find((g: { gate: string }) => g.gate === "build"); @@ -2308,10 +2295,7 @@ describe("API Endpoints", () => { expect(buildGate.promptId).toBe("tp-build"); expect(buildGate.promptText).toBeUndefined(); } - const submissionInsert = (mocks.submissionCollection.updateOne as any).mock.calls[0][1].$setOnInsert; - expect(submissionInsert.requestIds).toEqual( - docs.map((doc: { _id: string }) => doc._id), - ); + expect(mocks.experimentCollection.updateOne).not.toHaveBeenCalled(); // Response surfaces the configured gate count. expect(res.body.gates).toBe(2); }); @@ -2469,9 +2453,8 @@ describe("API Endpoints", () => { expect(insertCall[0]).toHaveProperty("taskPromptId", "tp-123"); expect(insertCall[0]).toHaveProperty("model", "gpt-4o"); expect(insertCall[0]).toHaveProperty("maxIterations", 5); - expect(insertCall[0]).toHaveProperty("submissionExpectedRequestCount", 1); - const submissionInsert = (mocks.submissionCollection.updateOne as any).mock.calls[0][1].$setOnInsert; - expect(submissionInsert.requestIds).toEqual([insertCall[0]._id]); + expect(insertCall[0]).not.toHaveProperty("experimentId"); + expect(mocks.experimentCollection.updateOne).not.toHaveBeenCalled(); }); it("applies profile override: uses profile fields for worker, model, mcpServers, skillRevisions, extensions", async () => { @@ -2848,13 +2831,13 @@ describe("API Endpoints", () => { it("retries eligible requests and skips non-terminal ones", async () => { const doc1 = { _id: "req-1", - submissionId: "submission-1", + experimentId: "experiment-1", workerType: "coder-acp-copilot", run: { _id: "run-1", attemptNumber: 1, status: "done", outcome: "failed" }, }; const doc2 = { _id: "req-2", - submissionId: "submission-1", + experimentId: "experiment-1", workerType: "coder-acp-copilot", run: { _id: "run-2", attemptNumber: 1, status: "processing" }, }; @@ -2880,22 +2863,7 @@ describe("API Endpoints", () => { $set: expect.objectContaining({ agentVersion: "1.0.0" }), }), ); - expect(mocks.submissionCollection.updateMany).toHaveBeenNthCalledWith( - 1, - { _id: { $in: ["submission-1"] } }, - expect.objectContaining({ - $set: expect.objectContaining({ - "run.reconcileAfter": expect.any(Date), - }), - }), - ); - expect(mocks.submissionCollection.updateMany).toHaveBeenNthCalledWith( - 2, - { _id: { $in: ["submission-1"] } }, - expect.objectContaining({ - $unset: { "run.reconcileAfter": "" }, - }), - ); + expect(mocks.experimentCollection.updateMany).not.toHaveBeenCalled(); }); it("returns 400 when ids array is empty", async () => { diff --git a/apps/api/src/experiment-openapi.test.ts b/apps/api/src/experiment-openapi.test.ts new file mode 100644 index 000000000..fd5288a78 --- /dev/null +++ b/apps/api/src/experiment-openapi.test.ts @@ -0,0 +1,68 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { beforeAll, describe, expect, it, vi } from "vitest"; +import type { OpenAPIObject } from "openapi3-ts/oas31"; + +vi.mock("db-migrations/check-migrations", () => ({ + checkMigrations: vi.fn().mockResolvedValue({ + ready: true, + applied: [], + pending: [], + }), +})); +vi.mock("./llm.js", () => ({ + isLlmAvailable: vi.fn().mockReturnValue(false), + generateCriteriaPrompt: vi.fn(), +})); +vi.mock("./prompt-feature-llm.js", () => ({ + isLlmAvailable: vi.fn().mockReturnValue(false), + generatePromptFeaturePrompt: vi.fn(), + extractPromptFeatures: vi.fn(), +})); +vi.mock("./task-prompt-llm.js", () => ({ + isTaskPromptLlmAvailable: vi.fn().mockReturnValue(false), + generateTaskPrompt: vi.fn(), +})); + +let document: OpenAPIObject; + +beforeAll(async () => { + await import("./index.js"); + const { generateOpenAPIDocument } = await import("./openapi/index.js"); + document = generateOpenAPIDocument(); +}); + +describe("Experiment OpenAPI contract", () => { + it("publishes canonical experiment operations", () => { + expect(document.paths).toHaveProperty("/api/v1/experiments"); + expect(document.paths).toHaveProperty("/api/v1/experiments/{id}"); + expect(document.paths).toHaveProperty( + "/api/v1/experiments/{id}/executions", + ); + expect(document.paths).toHaveProperty( + "/api/v1/experiments/{id}/executions/{experimentExecutionId}", + ); + expect(document.paths).toHaveProperty("/api/v1/experiments/{id}/retry"); + expect( + Object.keys(document.paths ?? {}).filter((path) => + path.includes("submission"), + ), + ).toEqual([]); + }); + + it("keeps POST /requests active while deprecating only composition properties", () => { + const operation = document.paths?.["/api/v1/requests"]?.post; + expect(operation?.deprecated).not.toBe(true); + const requestSchema = document.components?.schemas?.CreateRequestInput; + const operationJson = JSON.stringify(operation); + const requestSchemaJson = JSON.stringify(requestSchema); + + expect(operationJson).toContain('"count"'); + expect(operationJson).toContain('"deprecated":true'); + expect(requestSchemaJson).toContain('"profileVariations"'); + expect(requestSchemaJson).toContain('"deprecated":true'); + expect(operationJson).toContain("POST /api/v1/experiments"); + expect(requestSchemaJson).toContain("POST /api/v1/experiments"); + }); +}); diff --git a/apps/api/src/grouping.test.ts b/apps/api/src/grouping.test.ts index 56a834ce3..746498c58 100644 --- a/apps/api/src/grouping.test.ts +++ b/apps/api/src/grouping.test.ts @@ -14,8 +14,8 @@ describe("buildGroupingPipeline", () => { expect(pipeline[3]).toHaveProperty("$sort"); }); - it("returns 4 pipeline stages for submissionId grouping", () => { - const pipeline = buildGroupingPipeline("submissionId"); + it("returns 4 pipeline stages for experimentId grouping", () => { + const pipeline = buildGroupingPipeline("experimentId"); expect(pipeline).toHaveLength(4); }); @@ -32,8 +32,8 @@ describe("buildGroupingPipeline", () => { expect(addFields._groupKey).toBe("$taskPromptId"); }); - it("groups by submissionId for submissionId grouping", () => { - const pipeline = buildGroupingPipeline("submissionId"); + it("groups by experimentId for experimentId grouping", () => { + const pipeline = buildGroupingPipeline("experimentId"); const addFields = pipeline[0].$addFields as Record; expect(addFields._groupKey).toBeDefined(); }); @@ -74,7 +74,7 @@ describe("buildGroupingPipeline", () => { expect(group._agentVersions).toBeDefined(); expect(group._platforms).toBeDefined(); expect(group._statuses).toBeDefined(); - expect(group._submissionIds).toBeDefined(); + expect(group._experimentIds).toBeDefined(); expect(group._tasks).toBeDefined(); expect(group._mcpKeys).toBeDefined(); expect(group._skillKeys).toBeDefined(); diff --git a/apps/api/src/grouping.ts b/apps/api/src/grouping.ts index 3cc34cb18..d3ae0f60b 100644 --- a/apps/api/src/grouping.ts +++ b/apps/api/src/grouping.ts @@ -12,17 +12,17 @@ import type { GroupByKey, RunGroup, AggregateStats, GroupUniformValues } from "s * The pipeline is appended after a $match stage with the caller's filter. */ export function buildGroupingPipeline( - groupBy: "task" | "submissionId" | "profile", + groupBy: "task" | "experimentId" | "profile", ): Document[] { const groupField = - groupBy === "task" ? "$taskPromptId" : groupBy === "profile" ? "$profileId" : "$submissionId"; + groupBy === "task" ? "$taskPromptId" : groupBy === "profile" ? "$profileId" : "$experimentId"; const fallbackGroupField = - groupBy === "profile" ? { $literal: "no-profile" } : { $literal: "no-submission" }; + groupBy === "profile" ? { $literal: "no-profile" } : { $literal: "no-experiment" }; // `task` groups purely by the always-present `taskPromptId` — it is // materialized on every run-creation path (findOrCreate → taskPrompt._id) and // backfilled onto legacy docs by migration 001, so the group key is always a // real id the member-fetch filter (`{ taskPromptId: key }`) can match. Only - // `profile`/`submission` fall back to a fixed literal sentinel for runs that + // `profile`/`experiment` fall back to a fixed literal sentinel for runs that // genuinely lack the field. const groupKeyExpr = groupBy === "task" ? groupField : { $ifNull: [groupField, fallbackGroupField] }; @@ -131,7 +131,7 @@ export function buildGroupingPipeline( _agentVersions: { $addToSet: { $ifNull: ["$agentVersion", ""] } }, _platforms: { $addToSet: { $ifNull: ["$run.os.platform", ""] } }, _statuses: { $addToSet: "$run.status" }, - _submissionIds: { $addToSet: { $ifNull: ["$submissionId", ""] } }, + _experimentIds: { $addToSet: { $ifNull: ["$experimentId", ""] } }, _tasks: { $addToSet: { $ifNull: ["$scenario.task", ""] } }, _mcpKeys: { $addToSet: "$_mcpKey" }, _skillKeys: { $addToSet: "$_skillKey" }, @@ -160,7 +160,7 @@ export function buildGroupingPipeline( label: { $switch: { branches: [ - { case: { $eq: ["$_id", "no-submission"] }, then: "No submission ID" }, + { case: { $eq: ["$_id", "no-experiment"] }, then: "No experiment ID" }, { case: { $eq: ["$_id", "no-profile"] }, then: "No profile" }, ], default: { $ifNull: ["$_firstTask", "$_id"] }, @@ -183,7 +183,7 @@ export function buildGroupingPipeline( agentVersion: { $cond: { if: { $and: [{ $eq: [{ $size: "$_agentVersions" }, 1] }, { $ne: [{ $arrayElemAt: ["$_agentVersions", 0] }, ""] }] }, then: { $arrayElemAt: ["$_agentVersions", 0] }, else: "$$REMOVE" } }, platform: { $cond: { if: { $and: [{ $eq: [{ $size: "$_platforms" }, 1] }, { $ne: [{ $arrayElemAt: ["$_platforms", 0] }, ""] }] }, then: { $arrayElemAt: ["$_platforms", 0] }, else: "$$REMOVE" } }, status: { $cond: { if: { $eq: [{ $size: "$_statuses" }, 1] }, then: { $arrayElemAt: ["$_statuses", 0] }, else: "$$REMOVE" } }, - submissionId: { $cond: { if: { $and: [{ $eq: [{ $size: "$_submissionIds" }, 1] }, { $ne: [{ $arrayElemAt: ["$_submissionIds", 0] }, ""] }] }, then: { $arrayElemAt: ["$_submissionIds", 0] }, else: "$$REMOVE" } }, + experimentId: { $cond: { if: { $and: [{ $eq: [{ $size: "$_experimentIds" }, 1] }, { $ne: [{ $arrayElemAt: ["$_experimentIds", 0] }, ""] }] }, then: { $arrayElemAt: ["$_experimentIds", 0] }, else: "$$REMOVE" } }, task: { $cond: { if: { $and: [{ $eq: [{ $size: "$_tasks" }, 1] }, { $ne: [{ $arrayElemAt: ["$_tasks", 0] }, ""] }] }, then: { $arrayElemAt: ["$_tasks", 0] }, else: "$$REMOVE" } }, mcpServers: { $cond: { if: { $and: [{ $eq: [{ $size: "$_mcpKeys" }, 1] }, { $ne: [{ $arrayElemAt: ["$_mcpKeys", 0] }, ""] }] }, then: "$_firstMcpServers", else: "$$REMOVE" } }, skillRevisions: { $cond: { if: { $and: [{ $eq: [{ $size: "$_skillKeys" }, 1] }, { $ne: [{ $arrayElemAt: ["$_skillKeys", 0] }, ""] }] }, then: "$_firstSkillRevisions", else: "$$REMOVE" } }, diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index 7f95ab2f5..d9229ca51 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -10,6 +10,7 @@ import { resolve } from "node:path"; import { fileURLToPath } from "node:url"; import dotenv from "dotenv"; import { TaskPromptStore, SkillRevisionStore, SkillResolver, CodebaseStore, CodebaseRevisionStore, CodebaseResolver, ResourceStore, ResourceRevisionStore, ResourceResolver, McpSecretClient, McpSecretUnavailableError, BlobStorage, RedisHeartbeatStore, ProjectStore, loadAuthConfigFromEnv } from "shared"; +import type { ExperimentDocument, ExperimentExecutionHistoryDocument } from "shared"; import { initTelemetry } from "telemetry"; import type { TaskPromptDocument, SkillDocument, SkillRevisionDocument, CodebaseDocument, CodebaseRevisionDocument, ResourceDocument, ResourceRevisionDocument, ProfileDocument, ProfileVersionDocument, ProjectDocument, HeartbeatStore, AuthProvider, ProfileEnricher, UserDocument } from "shared"; import { UserStore } from "./auth/user-store.js"; @@ -47,7 +48,7 @@ import { registerInsightsRoutes } from "./routes/insights.js"; import { registerSecretsRoutes } from "./routes/secrets.js"; import { registerProfilesRoutes } from "./routes/profiles.js"; import { registerProjectsRoutes } from "./routes/projects.js"; -import { registerSubmissionsRoutes } from "./routes/submissions.js"; +import { registerExperimentsRoutes } from "./routes/experiments.js"; import { ProjectScopeError } from "./utils/project-scope.js"; import { registerUsersRoutes } from "./routes/users.js"; import { shutdownPortalCopilotClientPool } from "./copilot-client-pool.js"; @@ -60,8 +61,6 @@ import type { InsightDocument, RequestDocument, RunHistoryDocument, - SubmissionDocument, - SubmissionRunHistoryDocument, CodingAgentDocument, ModelDocument, McpServerDocument, @@ -100,8 +99,9 @@ let mongoClient: MongoClient; let db: Db; let collection: Collection; let runsCol: Collection; -let submissionCollection: Collection; -let submissionRunsCollection: Collection; +let experimentCollection: Collection; +let experimentExecutionsCollection: Collection; +let experimentChunksCollection: Collection; let projectCollection: Collection; let projectStore: ProjectStore; let criteriaCollection: Collection; @@ -149,8 +149,10 @@ async function initializeClients(): Promise { db = mongoClient.db(mongoDatabase); collection = db.collection(mongoCollection); runsCol = db.collection("runs"); - submissionCollection = db.collection("submissions"); - submissionRunsCollection = db.collection("submission-runs"); + experimentCollection = db.collection("experiments"); + experimentExecutionsCollection = + db.collection("experiment-executions"); + experimentChunksCollection = db.collection("experiment-chunks"); projectCollection = db.collection("projects"); projectStore = new ProjectStore(projectCollection); criteriaCollection = db.collection("criteria"); @@ -284,8 +286,9 @@ const routeCtx: RouteContext = { get db() { return db; }, get requestCollection() { return collection; }, get runsCollection() { return runsCol; }, - get submissionCollection() { return submissionCollection; }, - get submissionRunsCollection() { return submissionRunsCollection; }, + get experimentCollection() { return experimentCollection; }, + get experimentExecutionsCollection() { return experimentExecutionsCollection; }, + get experimentChunksCollection() { return experimentChunksCollection; }, get projectCollection() { return projectCollection; }, get criteriaCollection() { return criteriaCollection; }, get promptFeatureCollection() { return promptFeatureCollection; }, @@ -347,7 +350,7 @@ app.use(createUserAccessMiddleware(() => userAccessResolver)); registerSecretsRoutes(routeCtx); registerSystemRoutes(routeCtx); registerProjectsRoutes(routeCtx); -registerSubmissionsRoutes(routeCtx); +registerExperimentsRoutes(routeCtx); registerRequestsRoutes(routeCtx); registerRequestsCancelRoutes(routeCtx); registerRequestsLogsRoutes(routeCtx); @@ -434,8 +437,9 @@ export interface TestDependencies { db?: Db; collection?: Collection; runsCollection?: Collection; - submissionCollection?: Collection; - submissionRunsCollection?: Collection; + experimentCollection?: Collection; + experimentExecutionsCollection?: Collection; + experimentChunksCollection?: Collection; criteriaCollection?: Collection; promptFeatureCollection?: Collection; reportCollection?: Collection; @@ -477,8 +481,9 @@ export function _injectTestDependencies(deps: TestDependencies): void { if (deps.db) db = deps.db; if (deps.collection) collection = deps.collection; if (deps.runsCollection) runsCol = deps.runsCollection; - if (deps.submissionCollection) submissionCollection = deps.submissionCollection; - if (deps.submissionRunsCollection) submissionRunsCollection = deps.submissionRunsCollection; + if (deps.experimentCollection) experimentCollection = deps.experimentCollection; + if (deps.experimentExecutionsCollection) experimentExecutionsCollection = deps.experimentExecutionsCollection; + if (deps.experimentChunksCollection) experimentChunksCollection = deps.experimentChunksCollection; if (deps.criteriaCollection) criteriaCollection = deps.criteriaCollection; if (deps.promptFeatureCollection) promptFeatureCollection = deps.promptFeatureCollection; if (deps.reportCollection) reportCollection = deps.reportCollection; diff --git a/apps/api/src/openapi/openapi.test.ts b/apps/api/src/openapi/openapi.test.ts index 87426de43..6dbfa9152 100644 --- a/apps/api/src/openapi/openapi.test.ts +++ b/apps/api/src/openapi/openapi.test.ts @@ -466,7 +466,7 @@ apiRoute(testApp, registry, { apiRoute(testApp, registry, { method: "get", path: "/api/v1/analysis", tags: ["Requests"], summary: "Compute pass@k / success@T metrics", - query: z.object({ worker: z.string().optional(), taskPromptId: z.string().optional(), criteria: z.string().optional(), submissionId: z.string().optional(), k: z.string().optional() }), + query: z.object({ worker: z.string().optional(), taskPromptId: z.string().optional(), criteria: z.string().optional(), experimentId: z.string().optional(), k: z.string().optional() }), response: z.object({}).passthrough().describe("Analysis metrics"), handler: noop, }); apiRoute(testApp, registry, { diff --git a/apps/api/src/route-context.ts b/apps/api/src/route-context.ts index b675e8b9f..2037c04f0 100644 --- a/apps/api/src/route-context.ts +++ b/apps/api/src/route-context.ts @@ -52,8 +52,8 @@ import type { ReportTemplateResponseSchema, RequestResponseSchema, RunHistoryDocumentSchema, - SubmissionDocumentSchema, - SubmissionRunHistoryDocumentSchema, + ExperimentDocument, + ExperimentExecutionHistoryDocument, } from "shared"; // ─── Document types (inferred from Zod schemas) ───────────────────────────── @@ -76,9 +76,6 @@ export type ReportTrigger = z.infer; export type ReportTemplateDocument = Omit, "_id">; export type RequestDocument = z.infer; export type RunHistoryDocument = z.infer; -export type SubmissionDocument = z.infer; -export type SubmissionRunHistoryDocument = z.infer; - export type WorkerType = string; // ─── RouteContext ──────────────────────────────────────────────────────────── @@ -96,8 +93,9 @@ export interface RouteContext { db: Db; requestCollection: Collection; runsCollection: Collection; - submissionCollection: Collection; - submissionRunsCollection: Collection; + experimentCollection: Collection; + experimentExecutionsCollection: Collection; + experimentChunksCollection: Collection; projectCollection: Collection; criteriaCollection: Collection; promptFeatureCollection: Collection; diff --git a/apps/api/src/routes/experiments.test.ts b/apps/api/src/routes/experiments.test.ts new file mode 100644 index 000000000..677e1633f --- /dev/null +++ b/apps/api/src/routes/experiments.test.ts @@ -0,0 +1,247 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import express from "express"; +import request from "supertest"; +import { + OpenAPIRegistry, + OpenApiGeneratorV31, + extendZodWithOpenApi, +} from "@asteasolutions/zod-to-openapi"; +import { describe, expect, it, vi } from "vitest"; +import { z } from "zod"; +import type { RouteContext } from "../route-context.js"; +import type { ExperimentDocument } from "shared"; +import { registerExperimentsRoutes } from "./experiments.js"; + +extendZodWithOpenApi(z); + +function harness(overrides: Partial = {}) { + const app = express(); + app.use(express.json()); + const registry = new OpenAPIRegistry(); + registerExperimentsRoutes({ + app, + registry, + ...overrides, + } as unknown as RouteContext); + return { app, registry }; +} + +function emptyExperimentCollection() { + let document: ExperimentDocument | undefined; + return { + updateOne: vi.fn( + async ( + _filter: object, + update: { $setOnInsert?: ExperimentDocument }, + ) => { + document ??= structuredClone(update.$setOnInsert); + return { acknowledged: true, matchedCount: document ? 1 : 0 }; + }, + ), + findOne: vi.fn(async () => + document ? structuredClone(document) : null, + ), + findOneAndUpdate: vi.fn( + async ( + _filter: object, + update: { + $set?: Partial; + $inc?: { stateVersion?: number }; + }, + ) => { + if (!document) return null; + document = { + ...document, + ...update.$set, + stateVersion: + document.stateVersion + (update.$inc?.stateVersion ?? 0), + }; + return structuredClone(document); + }, + ), + }; +} + +function generateDocument(registry: OpenAPIRegistry) { + return new OpenApiGeneratorV31(registry.definitions).generateDocument({ + openapi: "3.1.0", + info: { title: "Experiment contract", version: "1.0.0" }, + }); +} + +describe("Experiment API contract", () => { + it("requires project scope on root routes", async () => { + const { app } = harness(); + + const create = await request(app) + .post("/api/v1/experiments") + .send({ + mode: "empty", + metadata: { name: "Empty experiment" }, + requests: [], + }); + const list = await request(app).get("/api/v1/experiments"); + const get = await request(app).get("/api/v1/experiments/experiment-1"); + const retry = await request(app) + .post("/api/v1/experiments/experiment-1/retry") + .send({ experimentExecutionId: "execution-1" }); + + expect(create.status).toBe(400); + expect(list.status).toBe(400); + expect(get.status).toBe(400); + expect(retry.status).toBe(400); + }); + + it("enforces explicit empty and compose modes", async () => { + const { app } = harness(); + + const emptyWithMembers = await request(app) + .post("/api/v1/experiments?projectId=project-1") + .send({ + mode: "empty", + metadata: { name: "Invalid empty experiment" }, + requests: [{ scenario: { task: "task" }, workerType: "worker" }], + }); + const composeWithoutMembers = await request(app) + .post("/api/v1/experiments?projectId=project-1") + .send({ + mode: "compose", + metadata: { name: "Invalid composed experiment" }, + requests: [], + }); + + expect(emptyWithMembers.status).toBe(400); + expect(composeWithoutMembers.status).toBe(400); + }); + + it("creates an empty, visible, non-dispatchable experiment", async () => { + const experimentCollection = emptyExperimentCollection(); + const { app } = harness({ + experimentCollection, + experimentExecutionsCollection: {}, + experimentChunksCollection: {}, + requestCollection: { + insertMany: vi.fn(), + updateMany: vi.fn(), + }, + } as unknown as Partial); + + const response = await request(app) + .post("/api/v1/experiments?projectId=project-1") + .send({ + mode: "empty", + metadata: { name: "Empty experiment" }, + requests: [], + }); + + expect(response.status).toBe(201); + expect(response.body.requestIds).toEqual([]); + expect(response.body.experiment).toMatchObject({ + projectId: "project-1", + metadata: { name: "Empty experiment" }, + revision: { memberCount: 0 }, + currentExecution: { + readiness: "empty", + blockers: [], + progress: {}, + }, + }); + expect(JSON.stringify(response.body)).not.toMatch( + /stateVersion|claimToken|vectorFingerprint|storageProfile|rollover/, + ); + }); + + it("inserts composed requests before publishing their exact revision", async () => { + const experimentCollection = emptyExperimentCollection(); + const insertMany = vi.fn().mockResolvedValue({ + acknowledged: true, + insertedCount: 1, + }); + const updateMany = vi.fn().mockResolvedValue({ + acknowledged: true, + matchedCount: 1, + modifiedCount: 1, + }); + const { app } = harness({ + experimentCollection, + experimentExecutionsCollection: {}, + experimentChunksCollection: {}, + requestCollection: { insertMany, updateMany }, + taskPromptStore: { + findOrCreate: vi.fn().mockResolvedValue({ _id: "prompt-1" }), + }, + blobStorage: { + getLogsBlobUrl: vi.fn( + (path: string) => `https://storage.invalid/${path}`, + ), + }, + } as unknown as Partial); + + const response = await request(app) + .post("/api/v1/experiments?projectId=project-1") + .send({ + mode: "compose", + metadata: { name: "One request" }, + requests: [ + { + scenario: { task: "Build it", criteria: ["works"] }, + workerType: "coder", + }, + ], + }); + + expect(response.status).toBe(201); + expect(response.body.requestIds).toHaveLength(1); + const inserted = insertMany.mock.calls[0]?.[0]?.[0]; + expect(inserted).toMatchObject({ + projectId: "project-1", + experimentId: response.body.experiment.experimentId, + experimentExpectedRequestCount: 1, + experimentRequestIndex: 0, + experimentInitialRunId: expect.any(String), + run: { + _id: expect.any(String), + status: "pending", + }, + }); + expect(updateMany).toHaveBeenCalledWith( + expect.objectContaining({ + projectId: "project-1", + experimentId: response.body.experiment.experimentId, + }), + { $set: { experimentFinalizedAt: expect.any(Date) } }, + ); + }); + + it("publishes only the canonical routes and public execution fields", () => { + const { registry } = harness(); + const document = generateDocument(registry); + + expect(Object.keys(document.paths ?? {}).sort()).toEqual([ + "/api/v1/experiments", + "/api/v1/experiments/{id}", + "/api/v1/experiments/{id}/executions", + "/api/v1/experiments/{id}/executions/{experimentExecutionId}", + "/api/v1/experiments/{id}/retry", + ]); + expect(document.paths).not.toHaveProperty("/api/v1/submissions"); + + const executionSchema = document.components?.schemas + ?.ExperimentExecutionResponse; + expect(executionSchema).toMatchObject({ + type: "object", + properties: { + experimentExecutionId: { type: "string" }, + readiness: expect.any(Object), + blockers: expect.any(Object), + progress: expect.any(Object), + supersededByExperimentExecutionId: { type: "string" }, + }, + }); + expect(JSON.stringify(executionSchema)).not.toMatch( + /claimToken|stateVersion|vectorFingerprint|storageProfile/, + ); + }); +}); diff --git a/apps/api/src/routes/experiments.ts b/apps/api/src/routes/experiments.ts new file mode 100644 index 000000000..824b1442b --- /dev/null +++ b/apps/api/src/routes/experiments.ts @@ -0,0 +1,691 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { v4 as uuidv4 } from "uuid"; +import { z } from "zod"; +import type { Document } from "mongodb"; +import { + CreateRequestInputSchema, + ExperimentStore, + fingerprintExperimentPayload, + type ExperimentDocument, + type ExperimentExecution, + type ExperimentExecutionHistoryDocument, + type ExperimentMetadata, + type ExperimentRequestState, +} from "shared"; +import type { RequestDocument, RouteContext } from "../route-context.js"; +import { apiRoute } from "../openapi/api-route.js"; +import { + ProjectIdQuerySchema, + getQueryProjectId, +} from "../utils/project-scope.js"; + +const CursorSchema = z.string().min(1).optional(); +const PageQuerySchema = ProjectIdQuerySchema.extend({ + limit: z.coerce.number().int().min(1).max(100).default(50), + after: CursorSchema, +}); + +const ExperimentMetadataInputSchema = z.object({ + name: z.string().trim().min(1).max(256), + description: z.string().max(4_096).optional(), + tags: z.array(z.string().trim().min(1).max(64)).max(32).optional(), +}); + +const ExperimentRequestInputSchema = CreateRequestInputSchema.omit({ + profileVariations: true, +}).extend({ + workerType: z.string().trim().min(1), +}); + +const CreateExperimentInputSchema = z + .object({ + mode: z.enum(["compose", "empty"]), + metadata: ExperimentMetadataInputSchema, + requests: z.array(ExperimentRequestInputSchema).max(250_000).default([]), + }) + .superRefine((value, ctx) => { + if (value.mode === "empty" && value.requests.length !== 0) { + ctx.addIssue({ + code: "custom", + path: ["requests"], + message: "empty mode requires an empty requests array", + }); + } + if (value.mode === "compose" && value.requests.length === 0) { + ctx.addIssue({ + code: "custom", + path: ["requests"], + message: "compose mode requires at least one request", + }); + } + }) + .openapi("CreateExperimentInput"); + +const HandlerProgressSchema = z.record( + z.string(), + z.object({ + status: z.enum(["queued", "processing", "done", "failed"]), + updatedAt: z.coerce.date(), + error: z.string().optional(), + }), +); + +const ReadinessSchema = z.enum([ + "empty", + "waiting", + "blocked", + "ready", + "processing", + "done", + "failed", +]); + +const ExperimentResponseSchema = z + .object({ + experimentId: z.string(), + projectId: z.string(), + metadata: ExperimentMetadataInputSchema.extend({ + createdBy: z.string().optional(), + }), + revision: z.object({ + experimentRevisionId: z.string(), + revisionNumber: z.number().int(), + memberCount: z.number().int(), + createdAt: z.coerce.date(), + }), + currentExecution: z.object({ + experimentExecutionId: z.string(), + attemptNumber: z.number().int(), + readiness: ReadinessSchema, + blockers: z.array( + z.object({ + requestId: z.string().optional(), + runId: z.string().optional(), + handlerId: z.string(), + reason: z.string(), + error: z.string().optional(), + }), + ), + progress: HandlerProgressSchema, + createdAt: z.coerce.date(), + updatedAt: z.coerce.date(), + startedAt: z.coerce.date().optional(), + finishedAt: z.coerce.date().optional(), + discardedAt: z.coerce.date().optional(), + discardReason: z.string().optional(), + report: z + .object({ + reportId: z.string().optional(), + url: z.string().optional(), + updatedAt: z.coerce.date().optional(), + }) + .optional(), + }), + createdAt: z.coerce.date(), + updatedAt: z.coerce.date(), + }) + .openapi("ExperimentResponse"); + +const ExperimentListResponseSchema = z + .object({ + data: z.array(ExperimentResponseSchema), + nextCursor: z.string().optional(), + }) + .openapi("ExperimentListResponse"); + +const ExecutionResponseSchema = z + .object({ + experimentExecutionId: z.string(), + attemptNumber: z.number().int(), + readiness: ReadinessSchema, + blockers: z.array(z.object({ + requestId: z.string().optional(), + runId: z.string().optional(), + handlerId: z.string(), + reason: z.string(), + error: z.string().optional(), + })), + progress: HandlerProgressSchema, + createdAt: z.coerce.date(), + updatedAt: z.coerce.date(), + startedAt: z.coerce.date().optional(), + finishedAt: z.coerce.date().optional(), + discardedAt: z.coerce.date().optional(), + discardReason: z.string().optional(), + supersededAt: z.coerce.date().optional(), + supersededByExperimentExecutionId: z.string().optional(), + supersededReason: z.enum(["rollover", "retry"]).optional(), + }) + .openapi("ExperimentExecutionResponse"); + +const ExecutionListResponseSchema = z + .object({ + data: z.array(ExecutionResponseSchema), + nextCursor: z.string().optional(), + }) + .openapi("ExperimentExecutionListResponse"); + +const CreateExperimentResponseSchema = z + .object({ + experiment: ExperimentResponseSchema, + requestIds: z.array(z.string()), + }) + .openapi("CreateExperimentResponse"); + +const RetryExperimentResponseSchema = z + .object({ + experimentId: z.string(), + experimentExecutionId: z.string(), + attemptNumber: z.number().int(), + readiness: ReadinessSchema, + blockers: z.array(z.object({ + requestId: z.string().optional(), + runId: z.string().optional(), + handlerId: z.string(), + reason: z.string(), + error: z.string().optional(), + })), + }) + .openapi("RetryExperimentResponse"); + +type Readiness = z.infer; + +function store(ctx: RouteContext): ExperimentStore { + return new ExperimentStore({ + experiments: ctx.experimentCollection, + executions: ctx.experimentExecutionsCollection, + chunks: ctx.experimentChunksCollection, + }); +} + +function readiness(execution: ExperimentExecution): Readiness { + if (execution.requests.entryCount === 0) return "empty"; + if (execution.discardedAt) return "failed"; + if (execution.blocking.some((blocker) => blocker.reason === "dependency-failed")) { + return "failed"; + } + if ( + execution.blocking.length > 0 && + execution.blocking.every( + (blocker) => blocker.reason === "dependency-not-ready", + ) + ) { + return "waiting"; + } + if (execution.blocking.length > 0) return "blocked"; + const statuses = Object.values(execution.handlerSummary); + if (statuses.some((status) => status.status === "failed")) return "failed"; + if (statuses.some((status) => status.status === "processing" || status.status === "queued")) { + return "processing"; + } + if (statuses.length > 0 && statuses.every((status) => status.status === "done")) { + return "done"; + } + return "ready"; +} + +function executionResponse(execution: ExperimentExecution) { + return { + experimentExecutionId: execution.experimentExecutionId, + attemptNumber: execution.attemptNumber, + readiness: readiness(execution), + blockers: execution.blocking, + progress: Object.fromEntries( + Object.entries(execution.handlerSummary).map(([handlerId, status]) => [ + handlerId, + { + status: status.status, + updatedAt: status.updatedAt, + ...(status.error ? { error: status.error } : {}), + }, + ]), + ), + createdAt: execution.createdAt, + updatedAt: execution.updatedAt, + ...(execution.startedAt ? { startedAt: execution.startedAt } : {}), + ...(execution.finishedAt ? { finishedAt: execution.finishedAt } : {}), + ...(execution.discardedAt ? { discardedAt: execution.discardedAt } : {}), + ...(execution.discardReason ? { discardReason: execution.discardReason } : {}), + ...(execution.supersededAt ? { supersededAt: execution.supersededAt } : {}), + ...(execution.supersededByExperimentExecutionId + ? { + supersededByExperimentExecutionId: + execution.supersededByExperimentExecutionId, + } + : {}), + ...(execution.supersededReason + ? { supersededReason: execution.supersededReason } + : {}), + }; +} + +function experimentResponse(experiment: ExperimentDocument) { + return { + experimentId: experiment.experimentId, + projectId: experiment.projectId, + metadata: experiment.metadata, + revision: { + experimentRevisionId: experiment.revision.experimentRevisionId, + revisionNumber: experiment.revision.revisionNumber, + memberCount: experiment.revision.memberCount, + createdAt: experiment.revision.createdAt, + }, + currentExecution: executionResponse(experiment.execution), + createdAt: experiment.createdAt, + updatedAt: experiment.updatedAt, + }; +} + +interface ExecutionCursor { + attemptNumber: number; + experimentExecutionId: string; +} + +function encodeExecutionCursor(cursor: ExecutionCursor): string { + return Buffer.from(JSON.stringify({ v: 1, ...cursor }), "utf8").toString( + "base64url", + ); +} + +function decodeExecutionCursor( + cursor: string | undefined, +): ExecutionCursor | undefined { + if (!cursor) return undefined; + try { + const parsed: unknown = JSON.parse( + Buffer.from(cursor, "base64url").toString("utf8"), + ); + const result = z + .object({ + v: z.literal(1), + attemptNumber: z.number().int().positive(), + experimentExecutionId: z.string().min(1), + }) + .strict() + .safeParse(parsed); + if (result.success) { + return { + attemptNumber: result.data.attemptNumber, + experimentExecutionId: result.data.experimentExecutionId, + }; + } + } catch { + // Converted to the route's standard 400 below. + } + throw new Error("Invalid experiment cursor"); +} + +function createRequestDocument(input: { + requestId: string; + runId: string; + experimentId: string; + expectedCount: number; + index: number; + projectId: string; + body: z.infer; + taskPromptId: string; + logsUrl: string; + now: Date; +}): RequestDocument { + const { body } = input; + return { + _id: input.requestId, + projectId: input.projectId, + scenario: body.scenario, + workerType: body.workerType, + createdAt: input.now, + taskPromptId: input.taskPromptId, + priority: body.priority ?? 0, + ...(body.model ? { model: body.model } : {}), + ...(body.reasoningEffort ? { reasoningEffort: body.reasoningEffort } : {}), + ...(body.maxIterations ? { maxIterations: body.maxIterations } : {}), + ...(body.personaInstructions + ? { personaInstructions: body.personaInstructions } + : {}), + ...(body.persona ? { persona: body.persona } : {}), + ...(body.mcpServers ? { mcpServers: body.mcpServers } : {}), + ...(body.skillRevisions ? { skillRevisions: body.skillRevisions } : {}), + ...(body.codebaseRevisionId + ? { codebaseRevisionId: body.codebaseRevisionId } + : {}), + ...(body.extensions ? { extensions: body.extensions } : {}), + ...(body.profileId ? { profileId: body.profileId } : {}), + ...(body.gates ? { gates: body.gates } : {}), + ...(body.observations ? { observations: body.observations } : {}), + experimentId: input.experimentId, + experimentExpectedRequestCount: input.expectedCount, + experimentRequestIndex: input.index, + experimentInitialRunId: input.runId, + run: { + _id: input.runId, + attemptNumber: 1, + status: "pending", + logsUrl: input.logsUrl, + }, + }; +} + +export function registerExperimentsRoutes(ctx: RouteContext): void { + apiRoute(ctx.app, ctx.registry, { + method: "post", + path: "/api/v1/experiments", + tags: ["Experiments"], + summary: "Create an experiment and zero or more new requests", + description: + "Canonical composition endpoint. Request and run IDs are minted before insertion; " + + "the exact revision/execution is then finalized idempotently.", + query: ProjectIdQuerySchema, + body: CreateExperimentInputSchema, + response: CreateExperimentResponseSchema, + errorResponses: { + 409: { description: "Experiment identity conflict" }, + }, + handler: async (req, res) => { + const projectId = getQueryProjectId(req); + const experimentId = uuidv4(); + const experimentExecutionId = uuidv4(); + const experimentRevisionId = uuidv4(); + const now = new Date(); + const identities = req.body.requests.map(() => ({ + requestId: uuidv4(), + runId: uuidv4(), + })); + const requestDocs = await Promise.all( + req.body.requests.map(async (body, index) => { + const identity = identities[index]!; + const taskPrompt = await ctx.taskPromptStore.findOrCreate( + projectId, + body.scenario.task, + ); + return createRequestDocument({ + ...identity, + experimentId, + expectedCount: req.body.requests.length, + index, + projectId, + body, + taskPromptId: taskPrompt._id, + logsUrl: ctx.blobStorage.getLogsBlobUrl( + `${identity.requestId}/runs/${identity.runId}/run.jsonl`, + ), + now, + }); + }), + ); + if (requestDocs.length > 0) { + await ctx.requestCollection.insertMany(requestDocs); + } + const requestStates: ExperimentRequestState[] = requestDocs.map((doc) => ({ + requestId: doc._id, + runId: doc.run!._id, + dependencies: [], + blockers: [], + })); + const metadata: ExperimentMetadata = req.body.metadata; + const experimentStore = store(ctx); + const pending = await experimentStore.createPending({ + experimentId, + projectId, + metadata, + revision: { + experimentRevisionId, + revisionNumber: 1, + memberCount: requestStates.length, + membershipFingerprint: fingerprintExperimentPayload( + requestStates.map(({ requestId, runId }) => ({ requestId, runId })), + ), + definitionFingerprint: fingerprintExperimentPayload({ + metadata, + requests: req.body.requests, + }), + createdAt: now, + }, + experimentExecutionId, + requests: requestStates, + now, + }); + const finalized = await experimentStore.finalizeCreation({ + projectId, + experimentId, + expectedExperimentExecutionId: experimentExecutionId, + expectedStateVersion: pending.stateVersion, + now, + }); + if (!finalized) { + res.status(409).json({ error: "Experiment finalization contention" }); + return; + } + if (requestDocs.length > 0) { + await ctx.requestCollection.updateMany( + { + _id: { $in: requestDocs.map((doc) => doc._id) }, + projectId, + experimentId, + experimentInitialRunId: { + $in: requestDocs.map((doc) => doc.run!._id), + }, + }, + { $set: { experimentFinalizedAt: now } }, + ); + } + res.status(201).json({ + experiment: experimentResponse(finalized), + requestIds: requestDocs.map((doc) => doc._id), + }); + }, + }); + + apiRoute(ctx.app, ctx.registry, { + method: "get", + path: "/api/v1/experiments", + tags: ["Experiments"], + summary: "List experiments", + query: PageQuerySchema, + response: ExperimentListResponseSchema, + handler: async (req, res) => { + const page = await store(ctx).listPage({ + projectId: getQueryProjectId(req), + limit: req.query.limit, + afterExperimentId: req.query.after, + }); + res.json({ + data: page.experiments.map(experimentResponse), + ...(page.nextCursor ? { nextCursor: page.nextCursor } : {}), + }); + }, + }); + + apiRoute(ctx.app, ctx.registry, { + method: "get", + path: "/api/v1/experiments/:id", + tags: ["Experiments"], + summary: "Get an experiment", + params: z.object({ id: z.string().min(1) }), + query: ProjectIdQuerySchema, + response: ExperimentResponseSchema, + errorResponses: { 404: { description: "Experiment not found" } }, + handler: async (req, res) => { + const experiment = await store(ctx).get( + getQueryProjectId(req), + req.params.id, + ); + if (!experiment) { + res.status(404).json({ error: "Experiment not found" }); + return; + } + res.json(experimentResponse(experiment)); + }, + }); + + apiRoute(ctx.app, ctx.registry, { + method: "get", + path: "/api/v1/experiments/:id/executions", + tags: ["Experiments"], + summary: "List current and historical experiment executions", + params: z.object({ id: z.string().min(1) }), + query: z.object({ + limit: z.coerce.number().int().min(1).max(100).default(50), + after: CursorSchema, + }), + response: ExecutionListResponseSchema, + errorResponses: { 404: { description: "Experiment not found" } }, + handler: async (req, res) => { + const experiment = await ctx.experimentCollection.findOne({ + _id: req.params.id, + finalizedAt: { $exists: true }, + }); + if (!experiment) { + res.status(404).json({ error: "Experiment not found" }); + return; + } + const after = decodeExecutionCursor(req.query.after); + const historyFilter: Document = { + projectId: experiment.projectId, + experimentId: req.params.id, + }; + if (after) { + historyFilter.$or = [ + { attemptNumber: { $lt: after.attemptNumber } }, + { + attemptNumber: after.attemptNumber, + experimentExecutionId: { + $gt: after.experimentExecutionId, + }, + }, + ]; + } + const raw = await ctx.experimentExecutionsCollection + .find(historyFilter) + .sort({ attemptNumber: -1, experimentExecutionId: 1 }) + .limit(req.query.limit + 1) + .toArray(); + const executions: ExperimentExecution[] = + after ? raw : [experiment.execution, ...raw]; + const data = executions.slice(0, req.query.limit).map(executionResponse); + const hasMore = executions.length > req.query.limit; + const last = executions[Math.min(data.length, executions.length) - 1]; + res.json({ + data, + ...(hasMore && last + ? { + nextCursor: encodeExecutionCursor({ + attemptNumber: last.attemptNumber, + experimentExecutionId: last.experimentExecutionId, + }), + } + : {}), + }); + }, + }); + + apiRoute(ctx.app, ctx.registry, { + method: "get", + path: "/api/v1/experiments/:id/executions/:experimentExecutionId", + tags: ["Experiments"], + summary: "Get one exact experiment execution", + params: z.object({ + id: z.string().min(1), + experimentExecutionId: z.string().min(1), + }), + response: ExecutionResponseSchema, + errorResponses: { 404: { description: "Experiment execution not found" } }, + handler: async (req, res) => { + const experiment = await ctx.experimentCollection.findOne({ + _id: req.params.id, + finalizedAt: { $exists: true }, + }); + if (!experiment) { + res.status(404).json({ error: "Experiment execution not found" }); + return; + } + const execution = await store(ctx).getExecution({ + projectId: experiment.projectId, + experimentId: req.params.id, + experimentExecutionId: req.params.experimentExecutionId, + }); + if (!execution) { + res.status(404).json({ error: "Experiment execution not found" }); + return; + } + res.json(executionResponse(execution)); + }, + }); + + apiRoute(ctx.app, ctx.registry, { + method: "post", + path: "/api/v1/experiments/:id/retry", + tags: ["Experiments"], + summary: "Retry current experiment processing", + params: z.object({ id: z.string().min(1) }), + query: ProjectIdQuerySchema, + body: z.object({ experimentExecutionId: z.string().min(1) }), + response: RetryExperimentResponseSchema, + errorResponses: { + 404: { description: "Experiment not found" }, + 409: { description: "Execution is stale or cannot be retried" }, + }, + handler: async (req, res) => { + const projectId = getQueryProjectId(req); + const experimentStore = store(ctx); + const current = await experimentStore.get(projectId, req.params.id); + if (!current) { + res.status(404).json({ error: "Experiment not found" }); + return; + } + if ( + current.execution.experimentExecutionId !== + req.body.experimentExecutionId + ) { + res.status(409).json({ + error: "Experiment execution is stale", + experimentExecutionId: + current.execution.experimentExecutionId, + blockers: current.execution.blocking, + }); + return; + } + const frozen = await experimentStore.freezeCurrent({ + projectId, + experimentId: req.params.id, + experimentExecutionId: req.body.experimentExecutionId, + expectedExecutionVersion: current.execution.version, + }); + if (!frozen) { + res.status(409).json({ + error: "Experiment retry contention", + experimentExecutionId: + current.execution.experimentExecutionId, + blockers: current.execution.blocking, + }); + return; + } + const retried = await experimentStore.retryCurrent({ + projectId, + experimentId: req.params.id, + expectedExperimentExecutionId: + req.body.experimentExecutionId, + expectedExecutionVersion: frozen.execution.version, + nextExperimentExecutionId: uuidv4(), + }); + if (!retried) { + res.status(409).json({ + error: "Experiment retry could not be published", + experimentExecutionId: + current.execution.experimentExecutionId, + blockers: current.execution.blocking, + }); + return; + } + res.status(201).json({ + experimentId: retried.experimentId, + experimentExecutionId: + retried.execution.experimentExecutionId, + attemptNumber: retried.execution.attemptNumber, + readiness: readiness(retried.execution), + blockers: retried.execution.blocking, + }); + }, + }); +} diff --git a/apps/api/src/routes/profiles.ts b/apps/api/src/routes/profiles.ts index b61c0b808..c8da480c6 100644 --- a/apps/api/src/routes/profiles.ts +++ b/apps/api/src/routes/profiles.ts @@ -107,7 +107,7 @@ apiRoute(ctx.app, ctx.registry, { const profileId = uuidv4(); const versionRef = `${profileId}@1`; - // Resolve extension versions (same pattern as run submission) + // Resolve extension versions (same pattern as request creation) let resolvedExtensions: string[] | undefined; if (extensions && extensions.length > 0) { const extensionClient = new ExtensionClient(""); diff --git a/apps/api/src/routes/requests/archive.test.ts b/apps/api/src/routes/requests/archive.test.ts index e6bc8a176..e9ad843d5 100644 --- a/apps/api/src/routes/requests/archive.test.ts +++ b/apps/api/src/routes/requests/archive.test.ts @@ -304,7 +304,6 @@ function makeFixtureRun(id = "run-fixture-1") { workerType: "coder-acp-copilot", createdAt: new Date("2026-01-01T00:00:00Z"), priority: 0, - submissionId: "submission-abc", run: { _id: id, attemptNumber: 1, @@ -765,7 +764,6 @@ describe("run import/export — round-trip (export → import)", () => { updatedAt: new Date("2026-05-11T23:04:47.446Z"), maxIterations: 1, priority: 0, - submissionId: "sub-rich-1", run: { _id: runId, attemptNumber: 2, // ← not 1; previous code hard-coded 1 diff --git a/apps/api/src/routes/requests/index.ts b/apps/api/src/routes/requests/index.ts index 070a583f3..07987a124 100644 --- a/apps/api/src/routes/requests/index.ts +++ b/apps/api/src/routes/requests/index.ts @@ -37,8 +37,8 @@ import { isCriterionCompatibleWithGate, orderGates, computeTaskPromptId, - ensureNativeSubmission, } from "shared"; +import { trackMetric } from "telemetry"; import type { ProfileDocument, ProfileVersionDocument, @@ -236,6 +236,28 @@ const validatePersistedRequestTarget = (request: RequestDocument) => /** Maximum number of profile variations (including the base profile) allowed in one submit. */ const MAX_PROFILE_VARIATIONS = 25; +const LEGACY_EXPERIMENT_COMPOSITION_ID = + "scope.api.requests.legacy-experiment-composition.v1"; + +function emitLegacyCompositionHeaders( + res: { setHeader(name: string, value: string): void }, + properties: readonly string[], +): void { + if (properties.length === 0) return; + res.setHeader("Deprecation", "true"); + res.setHeader( + "Link", + '; rel="successor-version"; title="POST /api/v1/experiments"', + ); + trackMetric({ + name: "api.deprecated_input_used", + value: 1, + properties: { + identifier: LEGACY_EXPERIMENT_COMPOSITION_ID, + properties: [...properties].sort().join(","), + }, + }); +} /** * Server-side validation of a request's gate configuration (docs/design/gates.md @@ -479,7 +501,16 @@ apiRoute(ctx.app, ctx.registry, { tags: ["Requests"], summary: "Submit request(s)", body: CreateRequestInputSchema.extend({ - count: z.number().min(1).max(10).default(1), + count: z + .number() + .min(1) + .max(10) + .default(1) + .openapi({ + deprecated: true, + description: + "Deprecated for composition. Use POST /api/v1/experiments and its requests array.", + }), skills: z.array(z.string()).optional(), agentVersion: z.string().optional(), codebase: z.string().optional(), @@ -554,6 +585,10 @@ apiRoute(ctx.app, ctx.registry, { ? profileVariations.filter((v: unknown): v is string => typeof v === "string") : []; const isVariationSubmit = typedProfileVariations.length > 0; + emitLegacyCompositionHeaders(res, [ + ...(count > 1 ? ["count"] : []), + ...(isVariationSubmit ? ["profileVariations"] : []), + ]); if (isVariationSubmit) { if (!requestedProfileSpec) { @@ -639,7 +674,7 @@ apiRoute(ctx.app, ctx.registry, { const taskPromptId = taskPrompt._id; // Gates are the shared evaluation harness for the whole comparative - // submission, not a per-variation controlled field: every variation + // request batch, not a per-variation controlled field: every variation // (including the base) runs the same gate configuration. Resolve, validate // and canonicalize them up front so an invalid config fails the whole // submit before any inserts (docs/design/gates.md §4.3), mirroring the @@ -836,10 +871,8 @@ apiRoute(ctx.app, ctx.registry, { }); } - // Pass 2: build documents and insert them under a single shared submissionId. - // All variations belong to the same comparative submission so consumers can - // group them via `submissionId` (matches docs/architecture/app-design.md). - const submissionId = uuidv4(); + // Pass 2: build independent request documents. Comparative composition is + // represented only by POST /experiments. const allNewIds: string[] = []; const newDocs: RequestDocument[] = []; const variationResults: Array<{ profileId: string; label?: string; ids: string[] }> = []; @@ -879,10 +912,6 @@ apiRoute(ctx.app, ctx.registry, { profileId: r.profile._id, profileVersionId: r.profileVersion.ref ?? r.profileVersion._id, ...(persistedVariationGates ? { gates: persistedVariationGates } : {}), - submissionId, - submissionExpectedRequestCount: expectedRequestCount, - submissionRequestIndex: newDocs.length, - submissionInitialRunId: runId, ...agentsMdFields, run: { _id: runId, attemptNumber: 1, status: "pending", logsUrl: ctx.blobStorage.getLogsBlobUrl(`${requestId}/runs/${runId}/run.jsonl`) }, }; @@ -896,25 +925,10 @@ apiRoute(ctx.app, ctx.registry, { } await ctx.requestCollection.insertMany(newDocs); - await ensureNativeSubmission({ - collections: { submissions: ctx.submissionCollection }, - submissionId, - projectId, - requests: newDocs.map((doc) => ({ - requestId: doc._id, - runId: doc.run!._id, - })), - createdAt: newDocs[0]?.createdAt, - }); - await ctx.requestCollection.updateMany( - { _id: { $in: allNewIds }, submissionId }, - { $set: { submissionFinalizedAt: new Date() } }, - ); res.status(201).json({ ids: allNewIds, count: allNewIds.length, - submissionId, variations: variationResults, variationCount: variationEntries.length, status: "pending", @@ -1280,7 +1294,7 @@ apiRoute(ctx.app, ctx.registry, { const taskPrompt = await ctx.taskPromptStore.findOrCreate(projectId, scenario.task); const taskPromptId = taskPrompt._id; - // Resolve AGENTS.md lineage once for this submission (shared across count>1). + // Resolve AGENTS.md lineage once for this request batch (shared across count>1). const agentsMdPromptId = await resolveAgentsMdPromptId(); const agentsMdFields = buildAgentsMdFields(agentsMdPromptId); @@ -1298,9 +1312,6 @@ apiRoute(ctx.app, ctx.registry, { ? [...new Set(resolvedObservations)] : undefined; - // Generate a submission ID to group all runs from this request - const submissionId = uuidv4(); - // Handle multiple runs (count > 1) if (count > 1) { const newIds: string[] = []; @@ -1334,10 +1345,6 @@ apiRoute(ctx.app, ctx.registry, { ...(profileVersionId ? { profileVersionId } : {}), ...(persistedGates ? { gates: persistedGates } : {}), ...(persistedObservations ? { observations: persistedObservations } : {}), - submissionId, - submissionExpectedRequestCount: count, - submissionRequestIndex: i, - submissionInitialRunId: runId, ...agentsMdFields, // Mint a distinct run id for the first attempt. Blob artifacts // are scoped under `{requestId}/runs/{runId}/...` so retries @@ -1349,27 +1356,12 @@ apiRoute(ctx.app, ctx.registry, { // Bulk insert all documents — scheduler will dispatch to queues await ctx.requestCollection.insertMany(newDocs); - await ensureNativeSubmission({ - collections: { submissions: ctx.submissionCollection }, - submissionId, - projectId, - requests: newDocs.map((doc) => ({ - requestId: doc._id, - runId: doc.run!._id, - })), - createdAt: newDocs[0]?.createdAt, - }); - await ctx.requestCollection.updateMany( - { _id: { $in: newIds }, submissionId }, - { $set: { submissionFinalizedAt: new Date() } }, - ); console.log(`Created ${count} ${mode} requests for ${workerType} (priority: ${requestedPriority ?? 0})`); res.status(201).json({ ids: newIds, count, - submissionId, workerType, taskPromptId, ...(model ? { model } : {}), @@ -1414,10 +1406,6 @@ apiRoute(ctx.app, ctx.registry, { ...(profileVersionId ? { profileVersionId } : {}), ...(persistedGates ? { gates: persistedGates } : {}), ...(persistedObservations ? { observations: persistedObservations } : {}), - submissionId, - submissionExpectedRequestCount: 1, - submissionRequestIndex: 0, - submissionInitialRunId: runId, ...agentsMdFields, // Mint a distinct run id for the first attempt. Blob artifacts // are scoped under `{requestId}/runs/{runId}/...` so retries @@ -1427,23 +1415,11 @@ apiRoute(ctx.app, ctx.registry, { // Store in MongoDB — scheduler will dispatch to queue await ctx.requestCollection.insertOne(requestDoc); - await ensureNativeSubmission({ - collections: { submissions: ctx.submissionCollection }, - submissionId, - projectId, - requests: [{ requestId, runId }], - createdAt: requestDoc.createdAt, - }); - await ctx.requestCollection.updateOne( - { _id: requestId, submissionId }, - { $set: { submissionFinalizedAt: new Date() } }, - ); console.log(`Created ${mode} request ${requestId} for ${workerType} (priority: ${requestedPriority ?? 0})`); res.status(201).json({ id: requestId, - submissionId, workerType, ...(model ? { model } : {}), ...(effectiveReasoningEffort ? { reasoningEffort: effectiveReasoningEffort } : {}), @@ -1526,14 +1502,14 @@ apiRoute(ctx.app, ctx.registry, { const projectId = getQueryProjectId(req); const taskPromptIdFilter = req.query.taskPromptId as string; const criteriaFilter = req.query.criteria as string; - const submissionIdFilter = req.query.submissionId as string; + const experimentIdFilter = req.query.experimentId as string; const searchFilter = req.query.search as string | undefined; const turnsFilterRaw = req.query.turns as string | undefined; const turnsOpFilter = (req.query.turnsOp as string | undefined) ?? "eq"; const maxIterationsFilterRaw = req.query.maxIterations as string | undefined; const maxIterationsOpFilter = (req.query.maxIterationsOp as string | undefined) ?? "eq"; const includeDeleted = req.query.includeDeleted === "true"; - const groupByParam = req.query.groupBy as "task" | "submissionId" | "profile" | undefined; + const groupByParam = req.query.groupBy as "task" | "experimentId" | "profile" | undefined; const limit = Math.min(Math.max(Number(req.query.limit) || 10, 1), 100); const afterParam = req.query.after as string | undefined; const beforeParam = req.query.before as string | undefined; @@ -1600,9 +1576,9 @@ apiRoute(ctx.app, ctx.registry, { pushClause(buildMultiClause("priority", priorityValues, { coerceNumber: true })); pushClause(buildMultiClause("agentVersion", agentVersionValues)); - if (submissionIdFilter) { - // Prefix-based matching: allow filtering by partial submission ID. - flat.submissionId = { $regex: `^${submissionIdFilter.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}` }; + if (experimentIdFilter) { + // Prefix-based matching: allow filtering by partial experiment ID. + flat.experimentId = { $regex: `^${experimentIdFilter.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}` }; } if (!includeDeleted) { flat.deletedAt = { $exists: false }; @@ -1699,7 +1675,7 @@ apiRoute(ctx.app, ctx.registry, { // Grouped mode: paginated RunGroup[] via two-phase aggregation if (groupByParam) { - const groupByField = groupByParam === "task" ? "taskPromptId" : groupByParam === "profile" ? "profileId" : "submissionId"; + const groupByField = groupByParam === "task" ? "taskPromptId" : groupByParam === "profile" ? "profileId" : "experimentId"; const groupByAggField = `$${groupByField}`; // Decode group cursor @@ -1932,7 +1908,7 @@ apiRoute(ctx.app, ctx.registry, { taskPromptId: z.string().optional(), criteria: z.string().optional(), features: z.string().optional(), - submissionId: z.string().optional(), + experimentId: z.string().optional(), k: z.string().optional(), }).merge(ProjectIdQuerySchema), response: z.object({}).passthrough().describe("Analysis metrics"), @@ -2116,7 +2092,6 @@ apiRoute(ctx.app, ctx.registry, { const foundIds = new Set(originalRuns.map(r => r._id)); const notFound = ids.filter((id: string) => !foundIds.has(id)); - const submissionId = uuidv4(); const newIds: string[] = []; const newDocs: RequestDocument[] = []; @@ -2255,10 +2230,6 @@ apiRoute(ctx.app, ctx.registry, { // Preserve AGENTS.md lineage across re-submits. ...(original.agentsMdPromptId ? { agentsMdPromptId: original.agentsMdPromptId } : {}), ...(original.agentsMdParentIds && original.agentsMdParentIds.length > 0 ? { agentsMdParentIds: original.agentsMdParentIds } : {}), - submissionId, - submissionExpectedRequestCount: originalRuns.length * count, - submissionRequestIndex: newDocs.length, - submissionInitialRunId: runId, // Bulk re-submit creates a brand-new request — mint a distinct // run id for the first attempt so blob artifacts live under // `{requestId}/runs/{runId}/...` (independent of the original run). @@ -2272,20 +2243,6 @@ apiRoute(ctx.app, ctx.registry, { // Insert all new documents — scheduler will dispatch to queues if (newDocs.length > 0) { await ctx.requestCollection.insertMany(newDocs); - await ensureNativeSubmission({ - collections: { submissions: ctx.submissionCollection }, - submissionId, - projectId: newDocs[0].projectId, - requests: newDocs.map((doc) => ({ - requestId: doc._id, - runId: doc.run!._id, - })), - createdAt: newDocs[0].createdAt, - }); - await ctx.requestCollection.updateMany( - { _id: { $in: newIds }, submissionId }, - { $set: { submissionFinalizedAt: new Date() } }, - ); } console.log(`Bulk re-submitted ${newIds.length} runs from ${originalRuns.length} originals (count=${count})`); @@ -2294,7 +2251,6 @@ apiRoute(ctx.app, ctx.registry, { submitted: newIds.length, failed: notFound, newIds, - submissionId, }); }, }); @@ -2685,7 +2641,7 @@ async function finalizePendingRun( const topChat = run.artifacts.get("run.chat-export.json"); if (topChat) runState.rawChatUrl = topChat; - // Materialize the task-prompt entity for this run. The submission flow + // Materialize the task-prompt entity for this run. The request creation flow // (POST /api/v1/requests) goes through `taskPromptStore.findOrCreate` so // every run has a row in the `task-prompts` collection that backs // features, report triggers, group-by-task, the runs-list task filter and @@ -2717,7 +2673,6 @@ async function finalizePendingRun( createdAt: runDoc.createdAt ?? new Date(), priority: runDoc.priority ?? 0, taskPromptId: resolvedTaskPromptId, - ...(runDoc.submissionId ? {} : { submissionId: uuidv4() }), run: { ...(runState as unknown as RunState), // Per-attempt `run._id` is preserved from the yaml (NOT clobbered @@ -3196,24 +3151,6 @@ apiRoute(ctx.app, ctx.registry, { { _id: { $in: ids }, deletedAt: { $exists: false } }, ).toArray(); const requestMap = new Map(requests.map((r) => [r._id, r])); - const affectedSubmissionIds = [ - ...new Set( - requests.flatMap((request) => - request.submissionId ? [request.submissionId] : [], - ), - ), - ]; - if (affectedSubmissionIds.length > 0) { - await ctx.submissionCollection.updateMany( - { _id: { $in: affectedSubmissionIds } }, - { - $set: { - "run.reconcileAfter": new Date(Date.now() + 60_000), - updatedAt: new Date(), - }, - }, - ); - } const results: Array<{ requestId: string; runId?: string; attemptNumber?: number; error?: string }> = []; let retried = 0; @@ -3295,16 +3232,6 @@ apiRoute(ctx.app, ctx.registry, { retried++; } - if (affectedSubmissionIds.length > 0) { - await ctx.submissionCollection.updateMany( - { _id: { $in: affectedSubmissionIds } }, - { - $unset: { "run.reconcileAfter": "" }, - $set: { updatedAt: new Date() }, - }, - ); - } - res.status(201).json({ retried, skipped, results }); }, }); diff --git a/apps/api/src/routes/submissions.test.ts b/apps/api/src/routes/submissions.test.ts deleted file mode 100644 index 984bdd358..000000000 --- a/apps/api/src/routes/submissions.test.ts +++ /dev/null @@ -1,253 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { OpenAPIRegistry } from "@asteasolutions/zod-to-openapi"; -import express from "express"; -import request from "supertest"; -import { describe, expect, it, vi } from "vitest"; -import type { Collection, Db } from "mongodb"; -import type { - RequestDocument, - ServiceHandlerDocument, - SubmissionDocument, - SubmissionRunHistoryDocument, -} from "shared"; -import { computeSubmissionVectorFingerprint } from "shared"; -import type { RouteContext } from "../route-context.js"; -import { registerSubmissionsRoutes } from "./submissions.js"; - -function queryResult(items: T[]) { - return { - sort: () => queryResult(items), - limit: () => queryResult(items), - toArray: async () => items, - }; -} - -function buildApp(input: { - requests: RequestDocument[]; - submission: SubmissionDocument; - history?: SubmissionRunHistoryDocument[]; -}) { - let submission = structuredClone(input.submission); - const services: ServiceHandlerDocument[] = [ - { - _id: "pp-atif", - type: "post-process-handler", - version: 1, - queue: "post-processor", - selector: "atif", - autoBackfill: true, - dependsOn: [], - }, - { - _id: "pp-observations", - type: "post-process-handler", - version: 1, - queue: "post-processor", - selector: "observations", - autoBackfill: true, - dependsOn: ["pp-atif"], - }, - ]; - const submissionCollection = { - findOne: vi.fn(async () => structuredClone(submission)), - find: vi.fn(() => queryResult([structuredClone(submission)])), - findOneAndUpdate: vi.fn(async ( - filter: Record, - update: { $set: Record }, - ) => { - if (filter["run._id"] !== submission.run._id) return null; - submission = { - ...submission, - updatedAt: update.$set.updatedAt as Date, - run: { - ...submission.run, - dependencyProjection: update.$set[ - "run.dependencyProjection" - ] as SubmissionDocument["run"]["dependencyProjection"], - blocking: update.$set[ - "run.blocking" - ] as SubmissionDocument["run"]["blocking"], - updatedAt: update.$set["run.updatedAt"] as Date, - }, - }; - return structuredClone(submission); - }), - } as unknown as Collection; - const db = { - collection: vi.fn(() => ({ - find: vi.fn(() => - queryResult(services.filter((service) => service.type === "post-process-handler")), - ), - findOne: vi.fn(async () => null), - })), - } as unknown as Db; - const ctx = { - app: express(), - registry: new OpenAPIRegistry(), - db, - requestCollection: { - find: vi.fn(() => queryResult(input.requests)), - } as unknown as Collection, - submissionCollection, - submissionRunsCollection: { - find: vi.fn(() => queryResult(input.history ?? [])), - findOne: vi.fn(async (filter: { _id: string }) => - (input.history ?? []).find((run) => run._id === filter._id) ?? null, - ), - } as unknown as Collection, - } as unknown as RouteContext; - ctx.app.use(express.json()); - registerSubmissionsRoutes(ctx); - ctx.app.use( - ( - error: Error, - _req: express.Request, - res: express.Response, - _next: express.NextFunction, - ) => res.status(500).json({ error: error.message }), - ); - return ctx.app; -} - -describe("submission routes", () => { - const requestDocument: RequestDocument = { - _id: "request-1", - projectId: "project-1", - scenario: { task: "Implement feature", criteria: ["criterion"] }, - workerType: "worker", - createdAt: new Date(), - priority: 0, - run: { - _id: "run-1", - attemptNumber: 1, - status: "done", - outcome: "failed", - handlerStatus: { - "pp-observations": { status: "done", version: 1 }, - }, - }, - }; - const submissionDocument: SubmissionDocument = { - _id: "submission-1", - submissionId: "submission-1", - projectId: "project-1", - requestIds: ["request-1"], - createdAt: new Date(), - run: { - _id: "submission-run-1", - attemptNumber: 1, - vectorFingerprint: computeSubmissionVectorFingerprint([ - { requestId: "request-1", runId: "run-1" }, - ]), - requests: [{ requestId: "request-1", runId: "run-1" }], - createdAt: new Date(), - dependencyProjection: [], - blocking: [], - }, - }; - - it("returns readiness and the exact request/run vector", async () => { - const response = await request( - buildApp({ - requests: [requestDocument], - submission: submissionDocument, - }), - ).get("/api/v1/submissions/submission-1"); - - expect(response.status, JSON.stringify(response.body)).toBe(200); - expect(response.body).toMatchObject({ - submissionId: "submission-1", - submissionRunId: "submission-run-1", - readiness: "ready", - requests: [{ requestId: "request-1", runId: "run-1", outcome: "failed" }], - dependencyProjection: [{ - requestId: "request-1", - runId: "run-1", - handlerId: "pp-observations", - state: "ready", - }], - }); - }); - - it("lists current and immutable archived attempts", async () => { - const historical: SubmissionRunHistoryDocument = { - ...submissionDocument.run, - _id: "submission-run-0", - attemptNumber: 1, - reconcileAfter: new Date(), - rollover: { - nextSubmissionRunId: "internal-next", - vectorFingerprint: "internal-fingerprint", - requests: [{ requestId: "request-1", runId: "run-1" }], - reason: "request-vector-changed", - claimedAt: new Date(), - }, - submissionId: "submission-1", - projectId: "project-1", - }; - const response = await request( - buildApp({ - requests: [requestDocument], - submission: submissionDocument, - history: [historical], - }), - ).get("/api/v1/submissions/submission-1/runs"); - - expect(response.status).toBe(200); - expect(response.body.runs.map((run: { _id: string }) => run._id)).toEqual([ - "submission-run-1", - "submission-run-0", - ]); - expect(response.body.runs[1]).not.toHaveProperty("reconcileAfter"); - expect(response.body.runs[1]).not.toHaveProperty("rollover"); - }); - - it("rejects a manual retry targeting a stale submission run", async () => { - const response = await request( - buildApp({ - requests: [requestDocument], - submission: submissionDocument, - }), - ) - .post("/api/v1/submissions/submission-1/retry") - .send({ submissionRunId: "stale-submission-run" }); - - expect(response.status).toBe(409); - expect(response.body).toMatchObject({ - error: "Submission attempt is stale", - submissionRunId: "submission-run-1", - }); - }); - - it("returns exact waiting request/run pairs when retry dependencies are not ready", async () => { - const waitingRequest: RequestDocument = { - ...requestDocument, - run: { - _id: "run-1", - attemptNumber: 1, - status: "done", - handlerStatus: {}, - }, - }; - const response = await request( - buildApp({ - requests: [waitingRequest], - submission: submissionDocument, - }), - ) - .post("/api/v1/submissions/submission-1/retry") - .send({ submissionRunId: "submission-run-1" }); - - expect(response.status).toBe(409); - expect(response.body.blocking).toEqual([ - { - requestId: "request-1", - runId: "run-1", - handlerId: "pp-observations", - reason: "dependency-not-ready", - }, - ]); - }); -}); diff --git a/apps/api/src/routes/submissions.ts b/apps/api/src/routes/submissions.ts deleted file mode 100644 index 201aae5bd..000000000 --- a/apps/api/src/routes/submissions.ts +++ /dev/null @@ -1,245 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { z } from "zod"; -import { - SubmissionCoordinator, - SubmissionListResponseSchema, - SubmissionResponseSchema, - SubmissionRetryResponseSchema, - SubmissionRunResponseSchema, - type ServiceHandlerDocument, - deriveSubmissionReadiness, -} from "shared"; -import type { SubmissionDocument } from "../route-context.js"; -import type { RouteContext } from "../route-context.js"; -import { apiRoute } from "../openapi/api-route.js"; -import { ProjectIdQuerySchema, getQueryProjectId } from "../utils/project-scope.js"; - -function coordinator(ctx: RouteContext): SubmissionCoordinator { - return new SubmissionCoordinator({ - requests: ctx.requestCollection, - submissions: ctx.submissionCollection, - submissionRuns: ctx.submissionRunsCollection, - services: ctx.db.collection("services"), - }); -} - -function toRunResponse( - run: T, -): Omit { - const { - reconcileAfter: _reconcileAfter, - rollover: _rollover, - ...response - } = run; - return response; -} - -function retryBlocking(submission: SubmissionDocument) { - if (submission.run.blocking.length > 0) return submission.run.blocking; - return submission.run.dependencyProjection - .filter((dependency) => dependency.state !== "ready") - .map((dependency) => ({ - requestId: dependency.requestId, - runId: dependency.runId, - handlerId: dependency.handlerId, - reason: "dependency-not-ready" as const, - ...(dependency.error ? { error: dependency.error } : {}), - })); -} - -async function toResponse(ctx: RouteContext, submission: SubmissionDocument) { - const requestDocs = await ctx.requestCollection - .find({ - _id: { $in: submission.requestIds }, - projectId: submission.projectId, - deletedAt: { $exists: false }, - }) - .toArray(); - const byId = new Map(requestDocs.map((request) => [request._id, request])); - const requests = submission.run.requests.flatMap((ref) => { - const request = byId.get(ref.requestId); - if (!request) return []; - return [{ - requestId: request._id, - runId: ref.runId, - task: request.scenario.task, - status: request.run?.status ?? "unknown", - ...(request.run?.outcome ? { outcome: request.run.outcome } : {}), - workerType: request.workerType, - ...(request.model ? { model: request.model } : {}), - ...(request.profileId ? { profileId: request.profileId } : {}), - }]; - }); - return { - submissionId: submission._id, - projectId: submission.projectId, - requestIds: submission.requestIds, - createdAt: submission.createdAt, - ...(submission.updatedAt ? { updatedAt: submission.updatedAt } : {}), - submissionRunId: submission.run._id, - attemptNumber: submission.run.attemptNumber, - readiness: deriveSubmissionReadiness(submission.run), - requests, - dependencyProjection: submission.run.dependencyProjection, - blocking: submission.run.blocking, - ...(submission.run.handlerStatus - ? { handlerProgress: submission.run.handlerStatus } - : {}), - ...(submission.run.report ? { report: submission.run.report } : {}), - ...(submission.run.supersededAt - ? { supersededAt: submission.run.supersededAt } - : {}), - ...(submission.run.supersededBySubmissionRunId - ? { supersededBySubmissionRunId: submission.run.supersededBySubmissionRunId } - : {}), - ...(submission.run.supersededReason - ? { supersededReason: submission.run.supersededReason } - : {}), - }; -} - -export function registerSubmissionsRoutes(ctx: RouteContext): void { - apiRoute(ctx.app, ctx.registry, { - method: "get", - path: "/api/v1/submissions", - tags: ["Submissions"], - summary: "List submissions", - query: ProjectIdQuerySchema.extend({ - limit: z.coerce.number().int().min(1).max(100).default(50), - }), - response: SubmissionListResponseSchema, - handler: async (req, res) => { - const projectId = getQueryProjectId(req); - const docs = await ctx.submissionCollection - .find({ projectId }) - .sort({ createdAt: -1, _id: -1 }) - .limit(req.query.limit) - .toArray(); - res.json({ - submissions: await Promise.all(docs.map((doc) => toResponse(ctx, doc))), - }); - }, - }); - - apiRoute(ctx.app, ctx.registry, { - method: "get", - path: "/api/v1/submissions/:id", - tags: ["Submissions"], - summary: "Get a submission", - params: z.object({ id: z.string() }), - response: SubmissionResponseSchema, - errorResponses: { 404: { description: "Submission not found" } }, - handler: async (req, res) => { - const reconciled = await coordinator(ctx).reconcile(req.params.id); - if (!reconciled) { - res.status(404).json({ error: "Submission not found" }); - return; - } - res.json(await toResponse(ctx, reconciled.submission)); - }, - }); - - apiRoute(ctx.app, ctx.registry, { - method: "get", - path: "/api/v1/submissions/:id/runs", - tags: ["Submissions"], - summary: "List current and historical submission attempts", - params: z.object({ id: z.string() }), - response: z.object({ runs: z.array(SubmissionRunResponseSchema) }), - errorResponses: { 404: { description: "Submission not found" } }, - handler: async (req, res) => { - const submission = await ctx.submissionCollection.findOne({ _id: req.params.id }); - if (!submission) { - res.status(404).json({ error: "Submission not found" }); - return; - } - const historical = await ctx.submissionRunsCollection - .find({ submissionId: req.params.id }) - .sort({ attemptNumber: -1 }) - .toArray(); - res.json({ - runs: [toRunResponse(submission.run), ...historical.map(toRunResponse)], - }); - }, - }); - - apiRoute(ctx.app, ctx.registry, { - method: "get", - path: "/api/v1/submissions/:id/runs/:submissionRunId", - tags: ["Submissions"], - summary: "Get one submission attempt", - params: z.object({ id: z.string(), submissionRunId: z.string() }), - response: SubmissionRunResponseSchema, - errorResponses: { 404: { description: "Submission attempt not found" } }, - handler: async (req, res) => { - const submission = await ctx.submissionCollection.findOne({ _id: req.params.id }); - if (submission?.run._id === req.params.submissionRunId) { - res.json(toRunResponse(submission.run)); - return; - } - const historical = await ctx.submissionRunsCollection.findOne({ - _id: req.params.submissionRunId, - submissionId: req.params.id, - }); - if (!historical) { - res.status(404).json({ error: "Submission attempt not found" }); - return; - } - res.json(toRunResponse(historical)); - }, - }); - - apiRoute(ctx.app, ctx.registry, { - method: "post", - path: "/api/v1/submissions/:id/retry", - tags: ["Submissions"], - summary: "Retry current submission processing", - params: z.object({ id: z.string() }), - body: z.object({ submissionRunId: z.string() }), - response: SubmissionRetryResponseSchema, - errorResponses: { - 404: { description: "Submission not found" }, - 409: { description: "Submission attempt is stale or dependencies are blocked" }, - }, - handler: async (req, res) => { - const current = await ctx.submissionCollection.findOne({ _id: req.params.id }); - if (!current) { - res.status(404).json({ error: "Submission not found" }); - return; - } - if (current.run._id !== req.body.submissionRunId) { - res.status(409).json({ - error: "Submission attempt is stale", - submissionRunId: current.run._id, - blocking: retryBlocking(current), - }); - return; - } - const result = await coordinator(ctx).retryCurrent( - req.params.id, - req.body.submissionRunId, - ); - if (!result) { - res.status(404).json({ error: "Submission not found" }); - return; - } - if (result.readiness === "blocked" || result.readiness === "waiting") { - res.status(409).json({ - error: "Submission dependencies are not ready", - submissionRunId: result.submission.run._id, - blocking: retryBlocking(result.submission), - }); - return; - } - res.status(201).json({ - submissionId: result.submission._id, - submissionRunId: result.submission.run._id, - attemptNumber: result.submission.run.attemptNumber, - readiness: result.readiness, - blocking: result.submission.run.blocking, - }); - }, - }); -} diff --git a/apps/api/src/test-helpers.ts b/apps/api/src/test-helpers.ts index 74447d6e7..64229a113 100644 --- a/apps/api/src/test-helpers.ts +++ b/apps/api/src/test-helpers.ts @@ -222,8 +222,9 @@ export function createAllMockDependencies() { const db = createMockDb(); const collection = createMockCollection(); const runsCollection = createMockCollection(); - const submissionCollection = createMockCollection(); - const submissionRunsCollection = createMockCollection(); + const experimentCollection = createMockCollection(); + const experimentExecutionsCollection = createMockCollection(); + const experimentChunksCollection = createMockCollection(); const criteriaCollection = createMockCollection(); const promptFeatureCollection = createMockCollection(); const reportCollection = createMockCollection(); @@ -252,8 +253,9 @@ export function createAllMockDependencies() { db, collection, runsCollection, - submissionCollection, - submissionRunsCollection, + experimentCollection, + experimentExecutionsCollection, + experimentChunksCollection, criteriaCollection, promptFeatureCollection, reportCollection, @@ -284,8 +286,9 @@ export function createAllMockDependencies() { db: ReturnType; collection: Collection; runsCollection: Collection; - submissionCollection: Collection; - submissionRunsCollection: Collection; + experimentCollection: Collection; + experimentExecutionsCollection: Collection; + experimentChunksCollection: Collection; criteriaCollection: Collection; promptFeatureCollection: Collection; reportCollection: Collection; diff --git a/apps/api/src/utils/agent-helpers.ts b/apps/api/src/utils/agent-helpers.ts index 768a635cf..95f130278 100644 --- a/apps/api/src/utils/agent-helpers.ts +++ b/apps/api/src/utils/agent-helpers.ts @@ -41,7 +41,7 @@ export interface ValidateAgentTargetOptions { } /** - * Resolve a submission target entirely from the agent registry. + * Resolve a request target entirely from the agent registry. * * Existence, deletion, explicit availability, active version, and advertised * queue are always enforced. Capability flags are enforced only while the diff --git a/apps/api/src/utils/codebase-helpers.ts b/apps/api/src/utils/codebase-helpers.ts index 1cb5d504d..fd9d69f0f 100644 --- a/apps/api/src/utils/codebase-helpers.ts +++ b/apps/api/src/utils/codebase-helpers.ts @@ -84,7 +84,7 @@ export interface CodebaseSpecResolveContext { } /** - * Resolve a codebase spec given at run-submission time into a concrete revision id. + * Resolve a codebase spec given at request creation time into a concrete revision id. * * Accepted forms: * - a raw revision UUID (`_id`) → validated as-is. diff --git a/apps/scheduler/src/experiment-coordinator.test.ts b/apps/scheduler/src/experiment-coordinator.test.ts new file mode 100644 index 000000000..570839e67 --- /dev/null +++ b/apps/scheduler/src/experiment-coordinator.test.ts @@ -0,0 +1,365 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import type { Collection, Document } from "mongodb"; +import { + EXPERIMENT_STORAGE_PROFILE_VERSION, + ExperimentStore, + FixedPayloadStore, + fingerprintExperimentPayload, + type ExperimentDocument, + type ExperimentExecutionHistoryDocument, + type ExperimentRequestState, + type RequestDocument, + type ServiceHandlerDocument, +} from "shared"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + ExperimentCoordinator, + type ExperimentCoordinatorCollections, +} from "./experiment-coordinator.js"; + +const now = new Date("2026-01-01T00:00:00.000Z"); + +function experiment( + requests: ExperimentRequestState[], + overrides: Partial = {}, +): ExperimentDocument { + const fingerprint = fingerprintExperimentPayload(requests); + return { + _id: "experiment-1", + experimentId: "experiment-1", + projectId: "project-1", + metadata: { name: "Experiment" }, + storageProfileVersion: EXPERIMENT_STORAGE_PROFILE_VERSION, + stateVersion: 1, + revision: { + experimentRevisionId: "revision-1", + revisionNumber: 1, + memberCount: requests.length, + membershipFingerprint: fingerprint, + definitionFingerprint: "definition-1", + createdAt: now, + }, + execution: { + experimentExecutionId: "execution-1", + attemptNumber: 1, + version: 1, + requests: { + storage: "inline", + entryCount: requests.length, + payloadFingerprint: fingerprint, + entries: requests, + }, + vectorFingerprint: fingerprint, + handlerSummary: {}, + blocking: [], + createdAt: now, + updatedAt: now, + ...overrides, + }, + createdAt: now, + updatedAt: now, + finalizedAt: now, + }; +} + +function cursor(documents: T[]) { + return { + sort: vi.fn().mockReturnThis(), + limit: vi.fn().mockReturnThis(), + toArray: vi.fn().mockResolvedValue(documents), + }; +} + +function collections(input: { + requests: RequestDocument[]; + services: ServiceHandlerDocument[]; + updatedExperiments?: ExperimentDocument[]; + currentExperiment?: ExperimentDocument; +}): ExperimentCoordinatorCollections { + const updates = [...(input.updatedExperiments ?? [])]; + return { + requests: { + find: vi.fn().mockReturnValue(cursor(input.requests)), + updateMany: vi.fn(), + } as unknown as Collection, + experiments: { + findOne: vi.fn().mockResolvedValue(input.currentExperiment ?? null), + findOneAndUpdate: vi.fn().mockImplementation(async () => updates.shift() ?? null), + } as unknown as Collection, + executions: {} as Collection, + chunks: {} as Collection, + services: { + find: vi.fn().mockImplementation((filter: Document) => { + const type = filter.type; + return cursor(input.services.filter((service) => service.type === type)); + }), + } as unknown as Collection, + }; +} + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe("ExperimentCoordinator", () => { + it("projects authoritative run status and dispatches an exact execution message", async () => { + const initialRequest: ExperimentRequestState = { + requestId: "request-1", + runId: "run-1", + dependencies: [], + blockers: [], + }; + const projectedRequest: ExperimentRequestState = { + ...initialRequest, + dependencies: [ + { + handlerId: "pp-observations", + state: "ready", + version: 3, + updatedAt: now, + }, + ], + }; + const initial = experiment([initialRequest]); + const projected = experiment([projectedRequest], { version: 2 }); + const queued = experiment([projectedRequest], { + version: 3, + handlerSummary: { + "experiment-processing": { + status: "queued", + version: 2, + claimToken: "claim-1", + updatedAt: now, + }, + }, + }); + vi.spyOn(ExperimentStore.prototype, "get").mockResolvedValue(initial); + vi.spyOn(FixedPayloadStore.prototype, "readRequests").mockResolvedValue([ + initialRequest, + ]); + const enqueue = vi.fn().mockResolvedValue(undefined); + const coordinator = new ExperimentCoordinator( + collections({ + requests: [ + { + _id: "request-1", + projectId: "project-1", + scenario: { task: "task", criteria: [] }, + workerType: "worker", + createdAt: now, + taskPromptId: "prompt-1", + priority: 0, + run: { + _id: "run-1", + attemptNumber: 1, + status: "done", + logsUrl: "https://logs", + handlerStatus: { + "pp-observations": { + status: "done", + version: 3, + updatedAt: now, + }, + }, + }, + }, + ], + services: [ + { + _id: "pp-observations", + type: "post-process-handler", + version: 3, + queue: "queue-pp-observations", + selector: "observations", + autoBackfill: false, + dependsOn: [], + }, + { + _id: "experiment-processing", + type: "experiment-handler", + version: 2, + queue: "queue-experiment-processing", + selector: "experiment-processing", + autoBackfill: false, + dependsOn: ["pp-observations"], + dependencyMode: "all-runs", + }, + ], + updatedExperiments: [projected, queued], + }), + enqueue, + ); + + const result = await coordinator.reconcile("project-1", "experiment-1"); + + expect(result?.dispatched).toBe(true); + expect(enqueue).toHaveBeenCalledWith( + expect.objectContaining({ _id: "experiment-processing" }), + { + type: "experiment-processing", + projectId: "project-1", + experimentId: "experiment-1", + experimentExecutionId: "execution-1", + handlerId: "experiment-processing", + handlerVersion: 2, + claimToken: expect.any(String), + executionVersion: 3, + }, + ); + }); + + it("re-enqueues a dropped notice without changing its exact identity", async () => { + const requestState: ExperimentRequestState = { + requestId: "request-1", + runId: "run-1", + dependencies: [ + { + handlerId: "pp-observations", + state: "ready", + updatedAt: now, + }, + ], + blockers: [], + }; + const queuedAt = new Date(Date.now() - 60_000); + const current = experiment([requestState], { + version: 7, + handlerSummary: { + "experiment-processing": { + status: "queued", + version: 2, + claimToken: "claim-original", + updatedAt: queuedAt, + }, + }, + }); + vi.spyOn(ExperimentStore.prototype, "get").mockResolvedValue(current); + vi.spyOn(FixedPayloadStore.prototype, "readRequests").mockResolvedValue([ + requestState, + ]); + const enqueue = vi.fn().mockResolvedValue(undefined); + const coordinator = new ExperimentCoordinator( + collections({ + requests: [ + { + _id: "request-1", + projectId: "project-1", + scenario: { task: "task", criteria: [] }, + workerType: "worker", + createdAt: now, + taskPromptId: "prompt-1", + priority: 0, + run: { + _id: "run-1", + attemptNumber: 1, + status: "done", + logsUrl: "https://logs", + handlerStatus: { + "pp-observations": { + status: "done", + updatedAt: now, + }, + }, + }, + }, + ], + services: [ + { + _id: "pp-observations", + type: "post-process-handler", + version: 1, + queue: "queue-pp-observations", + selector: "observations", + autoBackfill: false, + dependsOn: [], + }, + { + _id: "experiment-processing", + type: "experiment-handler", + version: 2, + queue: "queue-experiment-processing", + selector: "experiment-processing", + autoBackfill: false, + dependsOn: ["pp-observations"], + dependencyMode: "all-runs", + }, + ], + }), + enqueue, + ); + + const result = await coordinator.reconcile("project-1", "experiment-1"); + + expect(result?.dispatched).toBe(true); + expect(enqueue).toHaveBeenCalledWith( + expect.any(Object), + expect.objectContaining({ + experimentExecutionId: "execution-1", + executionVersion: 7, + claimToken: "claim-original", + }), + ); + }); + + it("finalizes an interrupted pending creation before marking its requests", async () => { + const requestState: ExperimentRequestState = { + requestId: "request-1", + runId: "run-1", + dependencies: [], + blockers: [], + }; + const pending = experiment([requestState]); + delete pending.finalizedAt; + const finalized = { ...pending, finalizedAt: now }; + const experimentCollections = collections({ + requests: [ + { + _id: "request-1", + projectId: "project-1", + scenario: { task: "task", criteria: [] }, + workerType: "worker", + createdAt: now, + taskPromptId: "prompt-1", + priority: 0, + experimentId: "experiment-1", + experimentExpectedRequestCount: 1, + experimentRequestIndex: 0, + experimentInitialRunId: "run-1", + run: { + _id: "run-1", + attemptNumber: 1, + status: "pending", + logsUrl: "https://logs", + }, + }, + ], + services: [], + currentExperiment: pending, + }); + const finalize = vi + .spyOn(ExperimentStore.prototype, "finalizeCreation") + .mockResolvedValue(finalized); + const coordinator = new ExperimentCoordinator(experimentCollections); + + const recovered = await coordinator.recoverInterruptedCreations(); + + expect(recovered).toBe(1); + expect(finalize).toHaveBeenCalledWith( + expect.objectContaining({ + projectId: "project-1", + experimentId: "experiment-1", + expectedExperimentExecutionId: "execution-1", + expectedStateVersion: 1, + }), + ); + expect(experimentCollections.requests.updateMany).toHaveBeenCalledWith( + expect.objectContaining({ + projectId: "project-1", + experimentId: "experiment-1", + }), + { $set: { experimentFinalizedAt: expect.any(Date) } }, + ); + }); +}); diff --git a/apps/scheduler/src/experiment-coordinator.ts b/apps/scheduler/src/experiment-coordinator.ts new file mode 100644 index 000000000..f88cf469f --- /dev/null +++ b/apps/scheduler/src/experiment-coordinator.ts @@ -0,0 +1,527 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { randomUUID } from "node:crypto"; +import type { Collection, Document } from "mongodb"; +import { + DependencyGraph, + ExperimentStore, + FixedPayloadStore, + fingerprintExperimentPayload, + type ExperimentBlocker, + type ExperimentDocument, + type ExperimentExecutionHistoryDocument, + type ExperimentHandlerServiceDocument, + type ExperimentQueueMessagePayload, + type ExperimentRequestState, + type HandlerRunStatus, + type HandlerServiceDocument, + type RequestDocument, + type ServiceHandlerDocument, +} from "shared"; + +export interface ExperimentCoordinatorCollections { + requests: Collection; + experiments: Collection; + executions: Collection; + chunks: Collection; + services: Collection; +} + +export interface ExperimentDispatchMessage + extends ExperimentQueueMessagePayload { + projectId: string; + handlerId: string; + handlerVersion: number; + claimToken: string; + executionVersion: number; +} + +export type EnqueueExperiment = ( + service: ExperimentHandlerServiceDocument, + message: ExperimentDispatchMessage, +) => Promise; + +export type ExperimentReadiness = + | "empty" + | "waiting" + | "blocked" + | "ready" + | "processing" + | "done" + | "failed"; + +export interface ReconcileExperimentResult { + experiment: ExperimentDocument; + readiness: ExperimentReadiness; + rolled: boolean; + dispatched: boolean; +} + +function namedHandlerState( + handlerId: string, + handlers: readonly HandlerServiceDocument[], + status: Record | undefined, +): "waiting" | "ready" | "failed" | "blocked" { + const direct = status?.[handlerId]?.status; + if (direct === "done") return "ready"; + if (direct === "failed") return "failed"; + if (!handlers.some((handler) => handler._id === handlerId)) return "waiting"; + const graph = new DependencyGraph( + handlers.map((handler) => ({ + id: handler._id, + dependsOn: handler.dependsOn, + })), + ); + for (const ancestorId of graph.getAncestors(handlerId)) { + if (status?.[ancestorId]?.status === "failed") return "blocked"; + } + return "waiting"; +} + +function currentReadiness( + experiment: ExperimentDocument, +): ExperimentReadiness { + if (experiment.execution.requests.entryCount === 0) return "empty"; + if (experiment.execution.discardedAt) return "failed"; + if ( + experiment.execution.blocking.some( + (blocker) => blocker.reason === "dependency-failed", + ) + ) { + return "failed"; + } + if ( + experiment.execution.blocking.length > 0 && + experiment.execution.blocking.every( + (blocker) => blocker.reason === "dependency-not-ready", + ) + ) { + return "waiting"; + } + if (experiment.execution.blocking.length > 0) return "blocked"; + const statuses = Object.values(experiment.execution.handlerSummary); + if (statuses.some((status) => status.status === "failed")) return "failed"; + if ( + statuses.some( + (status) => + status.status === "queued" || status.status === "processing", + ) + ) { + return "processing"; + } + if ( + statuses.length > 0 && + statuses.every((status) => status.status === "done") + ) { + return "done"; + } + return statuses.length === 0 ? "ready" : "waiting"; +} + +function sameProjection( + left: readonly ExperimentRequestState[], + right: readonly ExperimentRequestState[], +): boolean { + return fingerprintExperimentPayload(left) === fingerprintExperimentPayload(right); +} + +export class ExperimentCoordinator { + private readonly store: ExperimentStore; + private readonly payloads: FixedPayloadStore; + + constructor( + private readonly collections: ExperimentCoordinatorCollections, + private readonly enqueue?: EnqueueExperiment, + ) { + this.store = new ExperimentStore({ + experiments: collections.experiments, + executions: collections.executions, + chunks: collections.chunks, + }); + this.payloads = new FixedPayloadStore(collections.chunks); + } + + async reconcile( + projectId: string, + experimentId: string, + ): Promise { + let rolled = false; + for (let attempt = 0; attempt < 4; attempt += 1) { + let experiment = await this.store.get(projectId, experimentId); + if (!experiment) return null; + if (experiment.execution.rollover) { + const repaired = await this.store.repairRollover(projectId, experimentId); + if (!repaired) return null; + experiment = repaired; + rolled = true; + } + + const requests = await this.readRequests(experiment); + const requestDocs = await this.collections.requests + .find({ + _id: { $in: requests.map((request) => request.requestId) }, + projectId, + deletedAt: { $exists: false }, + } as Document) + .toArray(); + const byId = new Map(requestDocs.map((request) => [request._id, request])); + const runVectorChanged = requests.some((request) => { + const current = byId.get(request.requestId); + return current?.run?._id !== request.runId; + }); + const handlers = await this.loadRunHandlers(); + + if (runVectorChanged) { + const nextRequests = requests.map((request) => { + const current = byId.get(request.requestId); + if (!current?.run || current.run._id === request.runId) return request; + return this.projectRequest( + request.requestId, + current.run._id, + current, + handlers, + ); + }); + const frozen = await this.store.freezeCurrent({ + projectId, + experimentId, + experimentExecutionId: + experiment.execution.experimentExecutionId, + expectedExecutionVersion: experiment.execution.version, + }); + if (!frozen) { + const latest = await this.store.get(projectId, experimentId); + if ( + !latest || + latest.execution.experimentExecutionId !== + experiment.execution.experimentExecutionId + ) { + return latest + ? { + experiment: latest, + readiness: currentReadiness(latest), + rolled: true, + dispatched: false, + } + : null; + } + continue; + } + const next = await this.store.rollover({ + projectId, + experimentId, + expectedExperimentExecutionId: + experiment.execution.experimentExecutionId, + expectedExecutionVersion: frozen.execution.version, + nextExperimentExecutionId: randomUUID(), + requests: nextRequests, + reason: "rollover", + }); + if (!next) continue; + rolled = true; + continue; + } + + const projected = requests.map((request) => + this.projectRequest( + request.requestId, + request.runId, + byId.get(request.requestId), + handlers, + ), + ); + const blockers = projected.flatMap((request) => request.blockers); + if (!sameProjection(requests, projected)) { + if (experiment.execution.requests.storage !== "inline") { + throw new Error( + `Chunked experiment ${experimentId} requires a rollover before dependency projection changes`, + ); + } + const now = new Date(); + const payloadFingerprint = fingerprintExperimentPayload(projected); + const updated = await this.collections.experiments.findOneAndUpdate( + { + _id: experimentId, + projectId, + "execution.experimentExecutionId": + experiment.execution.experimentExecutionId, + "execution.version": experiment.execution.version, + "execution.frozenAt": { $exists: false }, + "execution.rollover": { $exists: false }, + } as Document, + { + $set: { + "execution.requests.entries": projected, + "execution.requests.payloadFingerprint": payloadFingerprint, + "execution.vectorFingerprint": payloadFingerprint, + "execution.blocking": blockers, + "execution.updatedAt": now, + updatedAt: now, + }, + $inc: { "execution.version": 1, stateVersion: 1 }, + } as Document, + { returnDocument: "after" }, + ); + if (!updated) continue; + experiment = updated; + } else if ( + fingerprintExperimentPayload(experiment.execution.blocking) !== + fingerprintExperimentPayload(blockers) + ) { + const updated = await this.collections.experiments.findOneAndUpdate( + { + _id: experimentId, + projectId, + "execution.experimentExecutionId": + experiment.execution.experimentExecutionId, + "execution.version": experiment.execution.version, + } as Document, + { + $set: { + "execution.blocking": blockers, + "execution.updatedAt": new Date(), + updatedAt: new Date(), + }, + $inc: { "execution.version": 1, stateVersion: 1 }, + } as Document, + { returnDocument: "after" }, + ); + if (!updated) continue; + experiment = updated; + } + + const dispatch = await this.dispatchReadyHandlers(experiment, projected); + const latest = + (await this.store.get(projectId, experimentId)) ?? experiment; + return { + experiment: latest, + readiness: currentReadiness(latest), + rolled, + dispatched: dispatch, + }; + } + throw new Error( + `Experiment ${experimentId} invariant failure after bounded same-identity contention`, + ); + } + + async recoverInterruptedCreations(limit = 30): Promise { + const candidates = await this.collections.requests + .find({ + experimentId: { $exists: true }, + experimentExpectedRequestCount: { $exists: true }, + experimentFinalizedAt: { $exists: false }, + deletedAt: { $exists: false }, + } as Document) + .sort({ _id: 1 }) + .limit(limit) + .toArray(); + let recovered = 0; + for (const experimentId of new Set( + candidates.flatMap((request) => + request.experimentId ? [request.experimentId] : [], + ), + )) { + const member = candidates.find( + (request) => request.experimentId === experimentId, + ); + if (!member) continue; + const raw = await this.collections.experiments.findOne({ + _id: experimentId, + projectId: member.projectId, + } as Document); + if (!raw) continue; + const existing = + raw.finalizedAt + ? raw + : await this.store.finalizeCreation({ + projectId: member.projectId, + experimentId, + expectedExperimentExecutionId: + raw.execution.experimentExecutionId, + expectedStateVersion: raw.stateVersion, + }); + if (!existing) continue; + await this.collections.requests.updateMany( + { + projectId: member.projectId, + experimentId, + experimentFinalizedAt: { $exists: false }, + } as Document, + { $set: { experimentFinalizedAt: new Date() } } as Document, + ); + recovered += 1; + } + return recovered; + } + + private async readRequests( + experiment: ExperimentDocument, + ): Promise { + return this.payloads.readRequests( + { + projectId: experiment.projectId, + experimentId: experiment.experimentId, + ownerId: experiment.execution.experimentExecutionId, + generation: experiment.execution.attemptNumber, + }, + experiment.execution.requests, + ); + } + + private async loadRunHandlers(): Promise { + const docs = await this.collections.services + .find({ type: "post-process-handler" } as Document) + .toArray(); + return docs.filter( + (doc): doc is HandlerServiceDocument => + doc.type === "post-process-handler", + ); + } + + private async loadExperimentHandlers(): Promise< + ExperimentHandlerServiceDocument[] + > { + const docs = await this.collections.services + .find({ type: "experiment-handler" } as Document) + .toArray(); + return docs.filter( + (doc): doc is ExperimentHandlerServiceDocument => + doc.type === "experiment-handler", + ); + } + + private projectRequest( + requestId: string, + runId: string, + request: RequestDocument | undefined, + handlers: readonly HandlerServiceDocument[], + ): ExperimentRequestState { + if (!request?.run) { + return { + requestId, + runId, + dependencies: [], + blockers: [ + { + requestId, + runId, + handlerId: "request", + reason: "request-missing", + }, + ], + }; + } + const experimentHandlers = request.run.handlerStatus ?? {}; + const dependencyIds = handlers + .filter((handler) => handler.selector === "observations") + .map((handler) => handler._id); + const effectiveDependencyIds = + dependencyIds.length > 0 ? dependencyIds : ["pp-observations"]; + const dependencies = effectiveDependencyIds.map((handlerId) => { + const source = experimentHandlers[handlerId]; + const state = namedHandlerState( + handlerId, + handlers, + request.run?.handlerStatus, + ); + return { + handlerId, + state, + ...(source?.version !== undefined ? { version: source.version } : {}), + ...(source?.updatedAt ? { updatedAt: source.updatedAt } : {}), + ...(source?.error ? { error: source.error } : {}), + }; + }); + const blockers: ExperimentBlocker[] = dependencies.flatMap((dependency) => { + if (dependency.state === "ready") return []; + const reason = + dependency.state === "failed" + ? ("dependency-failed" as const) + : dependency.state === "blocked" + ? ("dependency-blocked" as const) + : ("dependency-not-ready" as const); + return [ + { + requestId, + runId, + handlerId: dependency.handlerId, + reason, + ...(dependency.error ? { error: dependency.error } : {}), + }, + ]; + }); + return { requestId, runId, dependencies, blockers }; + } + + private async dispatchReadyHandlers( + experiment: ExperimentDocument, + requests: readonly ExperimentRequestState[], + ): Promise { + if (!this.enqueue || requests.length === 0) return false; + const services = await this.loadExperimentHandlers(); + let dispatched = false; + for (const service of services) { + const existing = experiment.execution.handlerSummary[service._id]; + const allReady = requests.every((request) => + service.dependsOn.every( + (handlerId) => + request.dependencies.find( + (dependency) => dependency.handlerId === handlerId, + )?.state === "ready", + ), + ); + const retryDroppedNotice = + existing?.status === "queued" && + Date.now() - existing.updatedAt.getTime() >= 30_000; + if ((!existing && !allReady) || (existing && !retryDroppedNotice)) continue; + + const claimToken = existing?.claimToken ?? randomUUID(); + const now = new Date(); + let current = experiment; + if (!existing) { + const path = `execution.handlerSummary.${service._id}`; + const queued = await this.collections.experiments.findOneAndUpdate( + { + _id: experiment.experimentId, + projectId: experiment.projectId, + "execution.experimentExecutionId": + experiment.execution.experimentExecutionId, + "execution.version": experiment.execution.version, + [`${path}.status`]: { $exists: false }, + } as Document, + { + $set: { + [path]: { + status: "queued", + version: service.version, + claimToken, + updatedAt: now, + }, + "execution.updatedAt": now, + updatedAt: now, + }, + $inc: { "execution.version": 1, stateVersion: 1 }, + } as Document, + { returnDocument: "after" }, + ); + if (!queued) continue; + current = queued; + } + await this.enqueue(service, { + type: service.selector, + projectId: current.projectId, + experimentId: current.experimentId, + experimentExecutionId: + current.execution.experimentExecutionId, + handlerId: service._id, + handlerVersion: service.version, + claimToken, + executionVersion: current.execution.version, + }); + dispatched = true; + } + return dispatched; + } +} diff --git a/apps/scheduler/src/experiment-dispatcher.ts b/apps/scheduler/src/experiment-dispatcher.ts new file mode 100644 index 000000000..4e0df8091 --- /dev/null +++ b/apps/scheduler/src/experiment-dispatcher.ts @@ -0,0 +1,169 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import type { QueueClient } from "@azure/storage-queue"; +import type { Collection, Db } from "mongodb"; +import type { + ExperimentDocument, + ExperimentExecutionHistoryDocument, + ExperimentHandlerServiceDocument, + RequestDocument, + ServiceHandlerDocument, +} from "shared"; +import { ExperimentStore } from "shared"; +import { + ExperimentCoordinator, + type ExperimentDispatchMessage, +} from "./experiment-coordinator.js"; + +export class ExperimentDispatcher { + private interval: ReturnType | null = null; + private dispatching = false; + private scanAfterExperimentId: string | null = null; + private readonly queueClients = new Map(); + private readonly coordinator: ExperimentCoordinator; + + constructor( + private readonly requests: Collection, + private readonly experiments: Collection, + private readonly executions: Collection, + private readonly chunks: Collection, + db: Db, + private readonly createQueueClient: (queueName: string) => QueueClient, + private readonly pollIntervalMs = 30_000, + private readonly batchSize = 30, + ) { + this.coordinator = new ExperimentCoordinator( + { + requests, + experiments, + executions, + chunks, + services: db.collection("services"), + }, + (service, message) => this.enqueue(service, message), + ); + } + + start(): void { + if (this.interval) return; + this.interval = setInterval(() => void this.poll(), this.pollIntervalMs); + void this.poll(); + } + + async stop(): Promise { + if (this.interval) { + clearInterval(this.interval); + this.interval = null; + } + const deadline = Date.now() + 5_000; + while (this.dispatching && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 100)); + } + } + + async onRequestChanged(requestId: string): Promise { + const request = await this.requests.findOne( + { _id: requestId }, + { projection: { projectId: 1, experimentId: 1 } }, + ); + if (request?.experimentId) { + await this.coordinator.reconcile( + request.projectId, + request.experimentId, + ); + } + } + + async onHandlerComplete(input: { + projectId: string; + experimentId: string; + experimentExecutionId: string; + executionVersion: number; + handlerId: string; + handlerVersion: number; + claimToken: string; + status: "done" | "failed"; + error?: string; + }): Promise { + const updated = await new ExperimentStore({ + experiments: this.experiments, + executions: this.executions, + chunks: this.chunks, + }).completeHandler({ + ...input, + expectedExecutionVersion: input.executionVersion, + }); + return updated !== null; + } + + async onHandlerClaim(input: { + projectId: string; + experimentId: string; + experimentExecutionId: string; + executionVersion: number; + handlerId: string; + handlerVersion: number; + claimToken: string; + }): Promise { + const updated = await new ExperimentStore({ + experiments: this.experiments, + executions: this.executions, + chunks: this.chunks, + }).claimHandler({ + ...input, + expectedExecutionVersion: input.executionVersion, + }); + return updated?.execution.version ?? null; + } + + private async poll(): Promise { + if (this.dispatching) return; + this.dispatching = true; + try { + await this.coordinator.recoverInterruptedCreations(this.batchSize); + const candidates = await this.experiments + .find( + this.scanAfterExperimentId + ? { + _id: { $gt: this.scanAfterExperimentId }, + finalizedAt: { $exists: true }, + } + : { finalizedAt: { $exists: true } }, + ) + .sort({ _id: 1 }) + .limit(this.batchSize) + .project({ _id: 1, projectId: 1 }) + .toArray(); + this.scanAfterExperimentId = + candidates.length === this.batchSize + ? candidates.at(-1)?._id ?? null + : null; + for (const candidate of candidates) { + await this.coordinator.reconcile( + candidate.projectId, + candidate._id, + ); + } + } catch (error) { + console.error("[ExperimentDispatcher] Poll failed:", error); + } finally { + this.dispatching = false; + } + } + + private async enqueue( + service: ExperimentHandlerServiceDocument, + message: ExperimentDispatchMessage, + ): Promise { + let client = this.queueClients.get(service.queue); + if (!client) { + client = this.createQueueClient(service.queue); + await client.createIfNotExists(); + this.queueClients.set(service.queue, client); + } + await client.sendMessage( + Buffer.from(JSON.stringify(message)).toString("base64"), + ); + } +} diff --git a/apps/scheduler/src/handler-dispatcher.ts b/apps/scheduler/src/handler-dispatcher.ts index d744092c3..c6415dada 100644 --- a/apps/scheduler/src/handler-dispatcher.ts +++ b/apps/scheduler/src/handler-dispatcher.ts @@ -9,10 +9,30 @@ import type { HandlerRunStatus, ServiceHandlerDocument, } from "shared"; -import { DependencyGraph, isHandlerDagDrained, withRetry } from "shared"; +import { DependencyGraph, withRetry } from "shared"; import type { RetryOptions } from "shared"; import type { NotifyHandler } from "./notify-routes.js"; +function isHandlerDagDrained( + handlers: readonly HandlerServiceDocument[], + handlerStatus: Record | undefined, +): boolean { + const graph = new DependencyGraph( + handlers.map((handler) => ({ + id: handler._id, + dependsOn: handler.dependsOn, + })), + ); + return handlers.every((handler) => { + const status = handlerStatus?.[handler._id]?.status; + if (status === "done" || status === "failed") return true; + if (status !== undefined) return false; + return [...graph.getAncestors(handler._id)].some( + (ancestorId) => handlerStatus?.[ancestorId]?.status === "failed", + ); + }); +} + /** * HandlerDispatcher — DAG-aware post-processing orchestrator. * @@ -157,12 +177,12 @@ export class HandlerDispatcher implements NotifyHandler { } async registerHandler(doc: ServiceHandlerDocument): Promise { - if (doc.type === "submission-handler") { + if (doc.type === "experiment-handler") { const postProcessHandlers = await this.loadHandlers(true); for (const dependency of doc.dependsOn) { if (!postProcessHandlers.some((handler) => handler._id === dependency)) { throw new Error( - `Submission handler '${doc._id}' depends on unknown run handler '${dependency}'`, + `Experiment handler '${doc._id}' depends on unknown run handler '${dependency}'`, ); } } @@ -173,7 +193,7 @@ export class HandlerDispatcher implements NotifyHandler { { upsert: true }, ); console.log( - `[HandlerDispatcher] Registered submission handler ${_id} (version=${doc.version}, queue=${doc.queue}, dependsOn=[${doc.dependsOn.join(", ")}])`, + `[HandlerDispatcher] Registered experiment handler ${_id} (version=${doc.version}, queue=${doc.queue}, dependsOn=[${doc.dependsOn.join(", ")}])`, ); return; } diff --git a/apps/scheduler/src/index.ts b/apps/scheduler/src/index.ts index 9fe0fbf79..ff1068a86 100644 --- a/apps/scheduler/src/index.ts +++ b/apps/scheduler/src/index.ts @@ -8,15 +8,15 @@ import { DefaultAzureCredential } from "@azure/identity"; import { RequestScheduler } from "./request-scheduler.js"; import { PostProcessorDispatcher } from "./post-processor-dispatcher.js"; import { HandlerDispatcher } from "./handler-dispatcher.js"; -import { SubmissionDispatcher } from "./submission-dispatcher.js"; +import { ExperimentDispatcher } from "./experiment-dispatcher.js"; import { createHttpServer, type NotifyHandler } from "./notify-routes.js"; import { StuckRunReaper } from "./stuck-run-reaper.js"; import { RedisHeartbeatStore, type HeartbeatStore } from "shared"; import type { CodingAgentDocument, RequestDocument, - SubmissionDocument, - SubmissionRunHistoryDocument, + ExperimentDocument, + ExperimentExecutionHistoryDocument, } from "shared"; import { initTelemetry, trackMetric, trackEvent, shutdownTelemetry } from "telemetry"; @@ -134,9 +134,13 @@ async function main(): Promise { const db = mongoClient.db(MONGO_DATABASE); const collection = db.collection(MONGO_COLLECTION); const agentCollection = db.collection("agents"); - const submissionCollection = db.collection("submissions"); - const submissionRunsCollection = - db.collection("submission-runs"); + const experimentCollection = + db.collection("experiments"); + const experimentExecutionsCollection = + db.collection( + "experiment-executions", + ); + const experimentChunksCollection = db.collection("experiment-chunks"); // Start the scheduler const scheduler = new RequestScheduler( @@ -200,16 +204,17 @@ async function main(): Promise { `[Scheduler] Handler dispatcher (DAG) started (poll=${ppPollIntervalMs}ms, topologyCacheTtl=${handlerCacheTtlMs}ms)`, ); - const submissionDispatcher = new SubmissionDispatcher( + const experimentDispatcher = new ExperimentDispatcher( collection, - submissionCollection, - submissionRunsCollection, + experimentCollection, + experimentExecutionsCollection, + experimentChunksCollection, db, createQueueClient, ppPollIntervalMs, ); - submissionDispatcher.start(); - console.log(`[Scheduler] Submission dispatcher started (poll=${ppPollIntervalMs}ms)`); + experimentDispatcher.start(); + console.log(`[Scheduler] Experiment dispatcher started (poll=${ppPollIntervalMs}ms)`); // Start the stuck-run reaper (authoritative backstop). Redis is non-fatal: // on misconfig or connection failure the reaper self-disables (its sweeps @@ -248,11 +253,11 @@ async function main(): Promise { } // Run notifications update the run DAG and immediately reconcile the parent - // submission. The polling loop remains the durable safety net. + // experiment. The polling loop remains the durable safety net. const notifyHandler: NotifyHandler = { onRunTerminal: async (requestId, runId) => { await handlerDispatcher.onRunTerminal(requestId, runId); - await submissionDispatcher.onRequestChanged(requestId); + await experimentDispatcher.onRequestChanged(requestId); }, onHandlerComplete: async (requestId, runId, handlerId, status) => { await handlerDispatcher.onHandlerComplete( @@ -261,8 +266,12 @@ async function main(): Promise { handlerId, status, ); - await submissionDispatcher.onRequestChanged(requestId); + await experimentDispatcher.onRequestChanged(requestId); }, + onExperimentHandlerClaim: (input) => + experimentDispatcher.onHandlerClaim(input), + onExperimentHandlerComplete: (input) => + experimentDispatcher.onHandlerComplete(input), registerHandler: (doc) => handlerDispatcher.registerHandler(doc), }; const httpServer = createHttpServer(notifyHandler); @@ -276,7 +285,7 @@ async function main(): Promise { await scheduler.stop(); await postProcessorDispatcher.stop(); await handlerDispatcher.stop(); - await submissionDispatcher.stop(); + await experimentDispatcher.stop(); if (stuckRunReaper) await stuckRunReaper.stop(); if (heartbeatStore) await heartbeatStore.close(); httpServer.close(); diff --git a/apps/scheduler/src/notify-routes.test.ts b/apps/scheduler/src/notify-routes.test.ts index 2d7ef741b..284bf081a 100644 --- a/apps/scheduler/src/notify-routes.test.ts +++ b/apps/scheduler/src/notify-routes.test.ts @@ -121,6 +121,161 @@ describe("createHttpServer", () => { expect(handler.onRunTerminal).not.toHaveBeenCalled(); }); + it("accepts exact experiment handler completions", async () => { + const onExperimentHandlerComplete = vi.fn().mockResolvedValue(true); + const handler: NotifyHandler = { + onRunTerminal: vi.fn().mockResolvedValue(undefined), + onHandlerComplete: vi.fn().mockResolvedValue(undefined), + onExperimentHandlerComplete, + registerHandler: vi.fn().mockResolvedValue(undefined), + }; + const { server, baseUrl } = await startServer(handler); + servers.push(server); + const body = { + projectId: "project-1", + experimentId: "experiment-1", + experimentExecutionId: "execution-1", + executionVersion: 4, + handlerId: "experiment-report", + handlerVersion: 2, + claimToken: "claim-1", + status: "done", + }; + + const response = await fetch( + `${baseUrl}/notify/experiment-handler-complete`, + { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + }, + ); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ ok: true }); + expect(onExperimentHandlerComplete).toHaveBeenCalledWith(body); + }); + + it("claims an exact experiment handler execution and returns its new version", async () => { + const onExperimentHandlerClaim = vi.fn().mockResolvedValue(5); + const handler: NotifyHandler = { + onRunTerminal: vi.fn().mockResolvedValue(undefined), + onHandlerComplete: vi.fn().mockResolvedValue(undefined), + onExperimentHandlerClaim, + registerHandler: vi.fn().mockResolvedValue(undefined), + }; + const { server, baseUrl } = await startServer(handler); + servers.push(server); + const body = { + projectId: "project-1", + experimentId: "experiment-1", + experimentExecutionId: "execution-1", + executionVersion: 4, + handlerId: "experiment-report", + handlerVersion: 2, + claimToken: "claim-1", + }; + + const response = await fetch( + `${baseUrl}/notify/experiment-handler-claim`, + { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + }, + ); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ + ok: true, + executionVersion: 5, + }); + expect(onExperimentHandlerClaim).toHaveBeenCalledWith(body); + }); + + it("rejects stale experiment handler claims", async () => { + const handler: NotifyHandler = { + onRunTerminal: vi.fn().mockResolvedValue(undefined), + onHandlerComplete: vi.fn().mockResolvedValue(undefined), + onExperimentHandlerClaim: vi.fn().mockResolvedValue(null), + registerHandler: vi.fn().mockResolvedValue(undefined), + }; + const { server, baseUrl } = await startServer(handler); + servers.push(server); + + const response = await fetch( + `${baseUrl}/notify/experiment-handler-claim`, + { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + projectId: "project-1", + experimentId: "experiment-1", + experimentExecutionId: "execution-1", + executionVersion: 4, + handlerId: "experiment-report", + handlerVersion: 2, + claimToken: "claim-1", + }), + }, + ); + + expect(response.status).toBe(409); + expect(await response.json()).toEqual({ + error: "Stale experiment handler claim discarded", + }); + }); + + it("rejects stale and malformed experiment handler completions", async () => { + const onExperimentHandlerComplete = vi.fn().mockResolvedValue(false); + const handler: NotifyHandler = { + onRunTerminal: vi.fn().mockResolvedValue(undefined), + onHandlerComplete: vi.fn().mockResolvedValue(undefined), + onExperimentHandlerComplete, + registerHandler: vi.fn().mockResolvedValue(undefined), + }; + const { server, baseUrl } = await startServer(handler); + servers.push(server); + + const stale = await fetch( + `${baseUrl}/notify/experiment-handler-complete`, + { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + projectId: "project-1", + experimentId: "experiment-1", + experimentExecutionId: "execution-1", + executionVersion: 4, + handlerId: "experiment-report", + handlerVersion: 2, + claimToken: "claim-1", + status: "failed", + error: "worker failed", + }), + }, + ); + const malformed = await fetch( + `${baseUrl}/notify/experiment-handler-complete`, + { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + projectId: "project-1", + experimentId: "experiment-1", + status: "done", + }), + }, + ); + + expect(stale.status).toBe(409); + expect(await stale.json()).toEqual({ + error: "Stale experiment handler completion discarded", + }); + expect(malformed.status).toBe(400); + expect(onExperimentHandlerComplete).toHaveBeenCalledTimes(1); + }); + it("returns 400 when required fields are missing", async () => { const handler: NotifyHandler = { onRunTerminal: vi.fn().mockResolvedValue(undefined), @@ -193,6 +348,39 @@ describe("createHttpServer", () => { expect(handler.registerHandler).toHaveBeenCalledWith(doc); }); + it("registers experiment-processing handlers", async () => { + const handler: NotifyHandler = { + onRunTerminal: vi.fn().mockResolvedValue(undefined), + onHandlerComplete: vi.fn().mockResolvedValue(undefined), + registerHandler: vi.fn().mockResolvedValue(undefined), + }; + const { server, baseUrl } = await startServer(handler); + servers.push(server); + const doc = { + _id: "experiment-processing", + type: "experiment-handler", + version: 1, + queue: "experiment-processing-queue", + selector: "experiment-processing", + autoBackfill: false, + dependsOn: ["pp-observations"], + dependencyMode: "all-runs", + }; + + const response = await fetch(`${baseUrl}/handlers/register`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(doc), + }); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ + ok: true, + handlerId: "experiment-processing", + }); + expect(handler.registerHandler).toHaveBeenCalledWith(doc); + }); + it("returns 400 for invalid handler registrations", async () => { const handler: NotifyHandler = { onRunTerminal: vi.fn().mockResolvedValue(undefined), diff --git a/apps/scheduler/src/notify-routes.ts b/apps/scheduler/src/notify-routes.ts index 6810a90c0..35c01eb1d 100644 --- a/apps/scheduler/src/notify-routes.ts +++ b/apps/scheduler/src/notify-routes.ts @@ -29,6 +29,10 @@ export interface NotifyHandler { status: "done" | "failed", ): Promise; registerHandler(doc: ServiceHandlerDocument): Promise; + onExperimentHandlerClaim?( + input: ExperimentHandlerClaimRequest, + ): Promise; + onExperimentHandlerComplete?(input: ExperimentHandlerCompleteRequest): Promise; } interface RunTerminalRequest { @@ -43,6 +47,22 @@ interface HandlerCompleteRequest { status: "done" | "failed"; } +export interface ExperimentHandlerClaimRequest { + projectId: string; + experimentId: string; + experimentExecutionId: string; + executionVersion: number; + handlerId: string; + handlerVersion: number; + claimToken: string; +} + +export interface ExperimentHandlerCompleteRequest + extends ExperimentHandlerClaimRequest { + status: "done" | "failed"; + error?: string; +} + function sendJson( res: http.ServerResponse, statusCode: number, @@ -98,6 +118,50 @@ function parseHandlerCompleteRequest(body: unknown): HandlerCompleteRequest | nu }; } +function parseExperimentHandlerCompleteRequest( + body: unknown, +): ExperimentHandlerCompleteRequest | null { + const claim = parseExperimentHandlerClaimRequest(body); + if (!claim || !isRecord(body)) return null; + if ( + (body.status !== "done" && body.status !== "failed") || + (body.error !== undefined && typeof body.error !== "string") + ) { + return null; + } + return { + ...claim, + status: body.status, + ...(typeof body.error === "string" ? { error: body.error } : {}), + }; +} + +function parseExperimentHandlerClaimRequest( + body: unknown, +): ExperimentHandlerClaimRequest | null { + if (!isRecord(body)) return null; + if ( + !isNonEmptyString(body.projectId) || + !isNonEmptyString(body.experimentId) || + !isNonEmptyString(body.experimentExecutionId) || + !Number.isInteger(body.executionVersion) || + !isNonEmptyString(body.handlerId) || + !Number.isInteger(body.handlerVersion) || + !isNonEmptyString(body.claimToken) + ) { + return null; + } + return { + projectId: body.projectId, + experimentId: body.experimentId, + experimentExecutionId: body.experimentExecutionId, + executionVersion: body.executionVersion as number, + handlerId: body.handlerId, + handlerVersion: body.handlerVersion as number, + claimToken: body.claimToken, + }; +} + function parseHandlerRegisterRequest(body: unknown): ServiceHandlerDocument | null { if (!isRecord(body)) { return null; @@ -115,7 +179,7 @@ function parseHandlerRegisterRequest(body: unknown): ServiceHandlerDocument | nu if ( !isNonEmptyString(_id) || - (type !== "post-process-handler" && type !== "submission-handler") || + (type !== "post-process-handler" && type !== "experiment-handler") || typeof version !== "number" || !Number.isFinite(version) || !isNonEmptyString(queue) || @@ -135,7 +199,7 @@ function parseHandlerRegisterRequest(body: unknown): ServiceHandlerDocument | nu autoBackfill, dependsOn: dependsOn as string[], }; - if (type === "submission-handler") { + if (type === "experiment-handler") { if (body.dependencyMode !== "all-runs") return null; return { ...common, @@ -265,12 +329,64 @@ export function createHttpServer( return; } + if ( + method === "POST" && + url.pathname === "/notify/experiment-handler-claim" + ) { + const parsedBody = parseExperimentHandlerClaimRequest( + await readJsonBody(req, maxBodyBytes), + ); + if (!parsedBody || !handler.onExperimentHandlerClaim) { + sendJson(res, 400, { + error: + "Exact experiment execution, handler version, and claim token are required", + }); + return; + } + const executionVersion = + await handler.onExperimentHandlerClaim(parsedBody); + if (executionVersion === null) { + sendJson(res, 409, { + error: "Stale experiment handler claim discarded", + }); + return; + } + sendJson(res, 200, { ok: true, executionVersion }); + return; + } + + if ( + method === "POST" && + url.pathname === "/notify/experiment-handler-complete" + ) { + const parsedBody = parseExperimentHandlerCompleteRequest( + await readJsonBody(req, maxBodyBytes), + ); + if (!parsedBody || !handler.onExperimentHandlerComplete) { + sendJson(res, 400, { + error: + "Exact experiment execution, handler version, claim token, and terminal status are required", + }); + return; + } + const completed = + await handler.onExperimentHandlerComplete(parsedBody); + if (!completed) { + sendJson(res, 409, { + error: "Stale experiment handler completion discarded", + }); + return; + } + sendJson(res, 200, { ok: true }); + return; + } + if (method === "POST" && url.pathname === "/handlers/register") { const parsedBody = parseHandlerRegisterRequest(await readJsonBody(req, maxBodyBytes)); if (!parsedBody) { sendJson(res, 400, { error: - "Invalid handler registration: _id, supported type, version, queue, selector, autoBackfill, dependsOn, and submission dependencyMode when applicable are required", + "Invalid handler registration: _id, supported type, version, queue, selector, autoBackfill, dependsOn, and experiment dependencyMode when applicable are required", }); return; } diff --git a/apps/scheduler/src/submission-dispatcher.ts b/apps/scheduler/src/submission-dispatcher.ts deleted file mode 100644 index cd2914853..000000000 --- a/apps/scheduler/src/submission-dispatcher.ts +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { QueueClient } from "@azure/storage-queue"; -import type { Collection, Db } from "mongodb"; -import { - SubmissionCoordinator, - type RequestDocument, - type SubmissionDocument, - type SubmissionHandlerServiceDocument, - type SubmissionQueueMessagePayload, - type SubmissionRunHistoryDocument, - type ServiceHandlerDocument, -} from "shared"; - -export class SubmissionDispatcher { - private interval: ReturnType | null = null; - private dispatching = false; - private scanAfterSubmissionId: string | null = null; - private readonly queueClients = new Map(); - private readonly coordinator: SubmissionCoordinator; - - constructor( - private readonly requests: Collection, - private readonly submissions: Collection, - submissionRuns: Collection, - db: Db, - private readonly createQueueClient: (queueName: string) => QueueClient, - private readonly pollIntervalMs = 30_000, - private readonly batchSize = 30, - ) { - this.coordinator = new SubmissionCoordinator( - { - requests, - submissions, - submissionRuns, - services: db.collection("services"), - }, - (service, message) => this.enqueue(service, message), - ); - } - - start(): void { - if (this.interval) return; - this.interval = setInterval(() => this.poll(), this.pollIntervalMs); - void this.poll(); - } - - async stop(): Promise { - if (this.interval) { - clearInterval(this.interval); - this.interval = null; - } - const deadline = Date.now() + 5_000; - while (this.dispatching && Date.now() < deadline) { - await new Promise((resolve) => setTimeout(resolve, 100)); - } - } - - async onRequestChanged(requestId: string): Promise { - const request = await this.requests.findOne( - { _id: requestId }, - { projection: { submissionId: 1 } }, - ); - if (request?.submissionId) { - await this.coordinator.reconcile(request.submissionId); - } - } - - private async poll(): Promise { - if (this.dispatching) return; - this.dispatching = true; - try { - await this.coordinator.recoverMissingNativeSubmissions(this.batchSize); - const candidates = await this.submissions - .find( - this.scanAfterSubmissionId - ? { _id: { $gt: this.scanAfterSubmissionId } } - : {}, - ) - .sort({ _id: 1 }) - .limit(this.batchSize) - .project({ _id: 1 }) - .toArray(); - this.scanAfterSubmissionId = - candidates.length === this.batchSize - ? candidates.at(-1)?._id ?? null - : null; - for (const candidate of candidates) { - await this.coordinator.reconcile(candidate._id); - } - } catch (error) { - console.error("[SubmissionDispatcher] Poll failed:", error); - } finally { - this.dispatching = false; - } - } - - private async enqueue( - service: SubmissionHandlerServiceDocument, - message: SubmissionQueueMessagePayload, - ): Promise { - let client = this.queueClients.get(service.queue); - if (!client) { - client = this.createQueueClient(service.queue); - await client.createIfNotExists(); - this.queueClients.set(service.queue, client); - } - const encoded = Buffer.from(JSON.stringify(message)).toString("base64"); - await client.sendMessage(encoded); - } -} diff --git a/packages/shared/src/cursor.test.ts b/packages/shared/src/cursor.test.ts index b06f0bfaf..b097915e9 100644 --- a/packages/shared/src/cursor.test.ts +++ b/packages/shared/src/cursor.test.ts @@ -18,8 +18,10 @@ describe("encodeCursor / decodeCursor", () => { }); it("preserves colons in values", () => { - const encoded = encodeCursor({ submissionId: "sub:with:colons" }); - expect(decodeCursor(encoded)).toEqual({ submissionId: "sub:with:colons" }); + const encoded = encodeCursor({ experimentId: "experiment:with:colons" }); + expect(decodeCursor(encoded)).toEqual({ + experimentId: "experiment:with:colons", + }); }); it("throws on missing tilde", () => { diff --git a/packages/shared/src/experiments/experiment-store.test.ts b/packages/shared/src/experiments/experiment-store.test.ts index ef925baa0..f9e0e0e1c 100644 --- a/packages/shared/src/experiments/experiment-store.test.ts +++ b/packages/shared/src/experiments/experiment-store.test.ts @@ -115,7 +115,12 @@ function experiment(): ExperimentDocument { }, vectorFingerprint: "vector", handlerSummary: { - report: { status: "queued", version: 1, updatedAt: now }, + report: { + status: "queued", + version: 1, + claimToken: "claim-1", + updatedAt: now, + }, }, blocking: [], createdAt: now, @@ -146,6 +151,7 @@ describe("ExperimentStore CAS contracts", () => { expectedExecutionVersion: 1, handlerId: "report", handlerVersion: 1, + claimToken: "claim-1", }), store.freezeCurrent({ projectId: "project-1", @@ -177,6 +183,7 @@ describe("ExperimentStore CAS contracts", () => { expectedExecutionVersion: 1, handlerId: "report", handlerVersion: 1, + claimToken: "claim-1", }), ).resolves.toBeNull(); await expect( @@ -187,7 +194,58 @@ describe("ExperimentStore CAS contracts", () => { expectedExecutionVersion: 1, handlerId: "report", handlerVersion: 1, + claimToken: "claim-1", }), ).resolves.toBeNull(); }); + + it("rejects stale completion tokens and accepts the exact claimed version", async () => { + const experiments = atomicCollection(experiment()); + const store = new ExperimentStore({ + experiments: + experiments as unknown as Collection, + executions: + {} as Collection, + chunks: {} as Collection, + }); + const claimed = await store.claimHandler({ + projectId: "project-1", + experimentId: "experiment-1", + experimentExecutionId: "execution-1", + expectedExecutionVersion: 1, + handlerId: "report", + handlerVersion: 1, + claimToken: "claim-1", + }); + expect(claimed?.execution.version).toBe(2); + + await expect( + store.completeHandler({ + projectId: "project-1", + experimentId: "experiment-1", + experimentExecutionId: "execution-1", + expectedExecutionVersion: 2, + handlerId: "report", + handlerVersion: 1, + claimToken: "stale-token", + status: "done", + }), + ).resolves.toBeNull(); + + const completed = await store.completeHandler({ + projectId: "project-1", + experimentId: "experiment-1", + experimentExecutionId: "execution-1", + expectedExecutionVersion: 2, + handlerId: "report", + handlerVersion: 1, + claimToken: "claim-1", + status: "done", + }); + expect(completed?.execution.handlerSummary.report).toMatchObject({ + status: "done", + version: 1, + claimToken: "claim-1", + }); + }); }); diff --git a/packages/shared/src/experiments/experiment-store.ts b/packages/shared/src/experiments/experiment-store.ts index 43b13ca7f..ce9ab4f1e 100644 --- a/packages/shared/src/experiments/experiment-store.ts +++ b/packages/shared/src/experiments/experiment-store.ts @@ -305,6 +305,7 @@ export class ExperimentStore { expectedExecutionVersion: number; handlerId: string; handlerVersion: number; + claimToken: string; now?: Date; }): Promise { assertHandlerId(input.handlerId); @@ -322,12 +323,14 @@ export class ExperimentStore { "execution.rollover": { $exists: false }, [`${path}.status`]: "queued", [`${path}.version`]: input.handlerVersion, + [`${path}.claimToken`]: input.claimToken, } as Document, { $set: { [path]: { status: "processing", version: input.handlerVersion, + claimToken: input.claimToken, updatedAt: now, }, "execution.startedAt": now, @@ -348,6 +351,7 @@ export class ExperimentStore { expectedExecutionVersion: number; handlerId: string; handlerVersion: number; + claimToken: string; status: Extract; error?: string; now?: Date; @@ -366,12 +370,14 @@ export class ExperimentStore { "execution.frozenAt": { $exists: false }, [`${path}.status`]: "processing", [`${path}.version`]: input.handlerVersion, + [`${path}.claimToken`]: input.claimToken, } as Document, { $set: { [path]: { status: input.status, version: input.handlerVersion, + claimToken: input.claimToken, updatedAt: now, ...(input.error ? { error: input.error } : {}), }, diff --git a/packages/shared/src/experiments/schemas.ts b/packages/shared/src/experiments/schemas.ts index 8491cf493..0022421f3 100644 --- a/packages/shared/src/experiments/schemas.ts +++ b/packages/shared/src/experiments/schemas.ts @@ -22,6 +22,8 @@ export const ExperimentDependencyProjectionSchema = z export const ExperimentBlockerSchema = z .object({ + requestId: IdSchema.optional(), + runId: IdSchema.optional(), handlerId: IdSchema, reason: z.enum([ "request-missing", @@ -67,6 +69,7 @@ export const ExperimentHandlerSummarySchema = z .object({ status: z.enum(["queued", "processing", "done", "failed"]), version: z.number().int().nonnegative(), + claimToken: IdSchema.optional(), updatedAt: z.coerce.date(), error: ErrorSchema.optional(), }) diff --git a/packages/shared/src/experiments/types.ts b/packages/shared/src/experiments/types.ts index e31b2f328..8d8595259 100644 --- a/packages/shared/src/experiments/types.ts +++ b/packages/shared/src/experiments/types.ts @@ -50,6 +50,8 @@ export type ExperimentBlockerReason = | "dependency-blocked"; export interface ExperimentBlocker { + requestId?: string; + runId?: string; handlerId: string; reason: ExperimentBlockerReason; error?: string; @@ -88,6 +90,7 @@ export type ExperimentHandlerStatus = export interface ExperimentHandlerSummary { status: ExperimentHandlerStatus; version: number; + claimToken?: string; updatedAt: Date; error?: string; } diff --git a/packages/shared/src/schemas/request.ts b/packages/shared/src/schemas/request.ts index ac7766f2d..029c03e09 100644 --- a/packages/shared/src/schemas/request.ts +++ b/packages/shared/src/schemas/request.ts @@ -137,11 +137,18 @@ export const CreateRequestInputSchema = z /** Resources to provision for this run, in setup order. Each entry is a * bare spec (slug, `slug@rN`, or revision id) or an object carrying * parameter values. Resolved at submit time and shared by every variation - * in a grouped submission, so each profile gets an identical environment. */ + * in an experiment, so each profile gets an identical environment. */ resources: z.array(ResourceBindingSpecSchema).optional(), extensions: z.array(z.string()).optional(), profileId: z.string().optional(), - profileVariations: z.array(z.string()).optional(), + profileVariations: z + .array(z.string()) + .optional() + .openapi({ + deprecated: true, + description: + "Deprecated for composition. Use POST /api/v1/experiments and its requests array.", + }), priority: z.number().int().optional(), // Raw AGENTS.md body to deliver to the worker workspace. When present, the // API findOrCreates an `agents.md`-typed prompt and stores its id on the @@ -181,9 +188,7 @@ export const RequestResponseSchema = z profileId: z.string().optional(), profileVersionId: z.string().optional(), experimentId: z.string().optional(), - experimentRevisionId: z.string().optional(), - experimentExecutionId: z.string().optional(), - experimentExpectedRequestCount: z.number().int().min(1).optional(), + experimentExpectedRequestCount: z.number().int().min(0).optional(), experimentRequestIndex: z.number().int().min(0).optional(), experimentInitialRunId: z.string().optional(), experimentFinalizedAt: z.coerce.date().optional(), @@ -289,7 +294,7 @@ export const ListRequestsQuerySchema = z worker: MultiValueParam, taskPromptId: z.string().optional(), criteria: z.string().optional(), - submissionId: z.string().optional(), + experimentId: z.string().optional(), profileId: MultiValueParam, status: MultiValueParam, outcome: MultiValueParam, @@ -299,7 +304,7 @@ export const ListRequestsQuerySchema = z agentVersion: MultiValueParam, // Free-text, case-insensitive search across run id, scenario task, model, worker. search: z.string().optional(), - groupBy: z.enum(["task", "submissionId", "profile"]).optional(), + groupBy: z.enum(["task", "experimentId", "profile"]).optional(), limit: z.coerce.number().int().min(1).max(100).optional(), after: z.string().optional(), before: z.string().optional(), @@ -372,7 +377,7 @@ export const GroupUniformValuesSchema = z codebaseRevisionId: z.string().optional(), extensions: z.array(z.string()).optional(), status: RequestStatusSchema.optional(), - submissionId: z.string().optional(), + experimentId: z.string().optional(), task: z.string().optional(), }) .openapi("GroupUniformValues"); diff --git a/packages/shared/src/types/types.ts b/packages/shared/src/types/types.ts index 9108cb690..93d76d525 100644 --- a/packages/shared/src/types/types.ts +++ b/packages/shared/src/types/types.ts @@ -384,16 +384,18 @@ export interface RequestDocument { agentVersion?: string; // Agent software version prefix (e.g. "copilot-0.0.415") — FK → AgentVersion.agentVersion profileId?: string; // FK → ProfileDocument._id (the profile lineage) profileVersionId?: string; // FK → ProfileVersionDocument._id (exact version used) - experimentId?: string; - experimentRevisionId?: string; - experimentExecutionId?: string; - /** Expected request count for interrupted Experiment finalization. */ + experimentId?: string; // FK → ExperimentDocument._id + /** Expected native request count for interrupted ExperimentDocument finalization. + * Historical/imported requests omit it and remain view-only if their parent + * experiment document is missing. */ experimentExpectedRequestCount?: number; - /** Stable position within the Experiment's immutable request vector. */ + /** Stable position within the experiment's immutable request vector. */ experimentRequestIndex?: number; - /** Initial run id retained so recovery can rebuild the exact first vector. */ + /** Run id minted for the experiment's first execution. It remains unchanged + * across request retries so recovery can rebuild the exact initial vector. */ experimentInitialRunId?: string; - /** Set only after the parent Experiment has been published. */ + /** Set after the parent ExperimentDocument has been idempotently finalized. + * Missing on interrupted native writes so the scheduler can recover them. */ experimentFinalizedAt?: Date; /** Scheduling priority. Higher = processed first. Default: 0. */ priority: number; @@ -592,6 +594,12 @@ export type ServiceHandlerDocument = | HandlerServiceDocument | ExperimentHandlerServiceDocument; +export interface ExperimentQueueMessagePayload { + type: string; + experimentId: string; + experimentExecutionId: string; +} + /** * Field names whose values move from `RequestDocument` (top-level, legacy * shape) into `RequestDocument.run: RunState` (new shape introduced for From aedbc18ce22e227522900f14d6593a77a1922bd1 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Thu, 15 Oct 2026 23:11:58 -0700 Subject: [PATCH 048/210] fix(requests): preserve legacy batch correlation Restore submissionId as a request-batch correlation contract while keeping Experiment as the only aggregate. Require project scope for nested Experiment execution reads and publish the shared composition deprecation identifier. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: b05e74ff-44da-4e78-9f05-0e256009e7ee --- .../openapi-snapshot.test.ts.snap | 47 ++++++++++++++++++ apps/api/src/endpoints.test.ts | 49 +++++++++++++++++++ apps/api/src/experiment-openapi.test.ts | 7 +++ apps/api/src/grouping.test.ts | 9 ++++ apps/api/src/grouping.ts | 18 +++++-- apps/api/src/routes/experiments.test.ts | 30 ++++++++++++ apps/api/src/routes/experiments.ts | 7 ++- apps/api/src/routes/requests/archive.test.ts | 5 +- apps/api/src/routes/requests/index.ts | 44 +++++++++++++---- packages/shared/src/schemas/request.ts | 7 ++- packages/shared/src/types/types.ts | 12 ++++- 11 files changed, 219 insertions(+), 16 deletions(-) diff --git a/apps/api/src/__snapshots__/openapi-snapshot.test.ts.snap b/apps/api/src/__snapshots__/openapi-snapshot.test.ts.snap index c1d80e316..2b987b988 100644 --- a/apps/api/src/__snapshots__/openapi-snapshot.test.ts.snap +++ b/apps/api/src/__snapshots__/openapi-snapshot.test.ts.snap @@ -2207,6 +2207,9 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` ], "type": "string", }, + "submissionId": { + "type": "string", + }, "task": { "type": "string", }, @@ -3407,6 +3410,9 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` }, "type": "array", }, + "submissionId": { + "type": "string", + }, "taskPromptId": { "type": "string", }, @@ -5335,6 +5341,14 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "type": "string", }, }, + { + "in": "query", + "name": "submissionId", + "required": false, + "schema": { + "type": "string", + }, + }, { "in": "query", "name": "experimentId", @@ -6366,6 +6380,18 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "type": "string", }, }, + { + "description": "Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.", + "in": "query", + "name": "projectId", + "required": true, + "schema": { + "description": "Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.", + "example": "00000000-0000-0000-0000-000000000000", + "minLength": 1, + "type": "string", + }, + }, { "in": "query", "name": "limit", @@ -6429,6 +6455,18 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "type": "string", }, }, + { + "description": "Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.", + "in": "query", + "name": "projectId", + "required": true, + "schema": { + "description": "Project scope. Required on scoped list and root-create operations; requests without a resolvable project are rejected with 400. There is no default project.", + "example": "00000000-0000-0000-0000-000000000000", + "minLength": 1, + "type": "string", + }, + }, ], "responses": { "200": { @@ -9782,6 +9820,14 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "type": "string", }, }, + { + "in": "query", + "name": "submissionId", + "required": false, + "schema": { + "type": "string", + }, + }, { "in": "query", "name": "experimentId", @@ -9931,6 +9977,7 @@ exports[`OpenAPI spec snapshot > matches the committed snapshot 1`] = ` "schema": { "enum": [ "task", + "submissionId", "experimentId", "profile", ], diff --git a/apps/api/src/endpoints.test.ts b/apps/api/src/endpoints.test.ts index 893288464..3e1f50e5a 100644 --- a/apps/api/src/endpoints.test.ts +++ b/apps/api/src/endpoints.test.ts @@ -781,6 +781,36 @@ describe("API Endpoints", () => { expect(res.body.data[0]).toHaveProperty("key", "experiment-1"); }); + it("preserves grouped results when groupBy=submissionId", async () => { + const groupedDocs = [ + { + key: "submission-1", + label: "submission-1", + aggregates: { + count: 2, + turns: null, + duration: null, + promptTokens: null, + completionTokens: null, + }, + uniform: {}, + }, + ]; + (mocks.collection.aggregate as any) + .mockReturnValueOnce({ + toArray: vi.fn().mockResolvedValue([{ _id: "submission-1" }]), + }) + .mockReturnValueOnce({ toArray: vi.fn().mockResolvedValue(groupedDocs) }) + .mockReturnValueOnce({ toArray: vi.fn().mockResolvedValue([]) }) + .mockReturnValueOnce({ toArray: vi.fn().mockResolvedValue([]) }); + + const res = await request(testServer()).get( + `/api/v1/requests?groupBy=submissionId&projectId=${TEST_PROJECT_ID}`, + ); + expect(res.status).toBe(200); + expect(res.body.data[0]).toHaveProperty("key", "submission-1"); + }); + it("calls aggregate pipeline when groupBy is provided", async () => { (mocks.collection.aggregate as any) .mockReturnValueOnce({ toArray: vi.fn().mockResolvedValue([]) }); // keys (empty) @@ -1956,6 +1986,8 @@ describe("API Endpoints", () => { const doc = (mocks.collection.insertOne as any).mock.calls[0][0]; expect(doc).toHaveProperty("reasoningEffort", "high"); expect(doc).not.toHaveProperty("experimentId"); + expect(doc).toHaveProperty("submissionId", res.body.submissionId); + expect(res.body.submissionId).toEqual(expect.any(String)); expect(mocks.experimentCollection.updateOne).not.toHaveBeenCalled(); expect(res.headers).not.toHaveProperty("deprecation"); expect(res.headers).not.toHaveProperty("link"); @@ -1974,6 +2006,13 @@ describe("API Endpoints", () => { const docs = (mocks.collection.insertMany as any).mock.calls[0][0]; expect(docs).toHaveLength(3); expect(docs.every((doc: object) => !("experimentId" in doc))).toBe(true); + expect(res.body.submissionId).toEqual(expect.any(String)); + expect( + docs.every( + (doc: { submissionId?: string }) => + doc.submissionId === res.body.submissionId, + ), + ).toBe(true); expect(mocks.experimentCollection.updateOne).not.toHaveBeenCalled(); expect(res.headers.deprecation).toBe("true"); expect(res.headers.link).toBe( @@ -2285,6 +2324,7 @@ describe("API Endpoints", () => { ); for (const doc of docs) { expect(doc.experimentId).toBeUndefined(); + expect(doc.submissionId).toBe(res.body.submissionId); expect(Array.isArray(doc.gates)).toBe(true); const selectGate = doc.gates.find((g: { gate: string }) => g.gate === "select"); const buildGate = doc.gates.find((g: { gate: string }) => g.gate === "build"); @@ -2296,6 +2336,10 @@ describe("API Endpoints", () => { expect(buildGate.promptText).toBeUndefined(); } expect(mocks.experimentCollection.updateOne).not.toHaveBeenCalled(); + expect(res.body.submissionId).toEqual(expect.any(String)); + expect(res.headers.deprecation).toBe("true"); + expect(res.headers.link).toContain("POST /api/v1/experiments"); + expect(res.headers).not.toHaveProperty("sunset"); // Response surfaces the configured gate count. expect(res.body.gates).toBe(2); }); @@ -2454,6 +2498,11 @@ describe("API Endpoints", () => { expect(insertCall[0]).toHaveProperty("model", "gpt-4o"); expect(insertCall[0]).toHaveProperty("maxIterations", 5); expect(insertCall[0]).not.toHaveProperty("experimentId"); + expect(insertCall[0]).toHaveProperty( + "submissionId", + res.body.submissionId, + ); + expect(res.body.submissionId).toEqual(expect.any(String)); expect(mocks.experimentCollection.updateOne).not.toHaveBeenCalled(); }); diff --git a/apps/api/src/experiment-openapi.test.ts b/apps/api/src/experiment-openapi.test.ts index fd5288a78..7a6a1df3d 100644 --- a/apps/api/src/experiment-openapi.test.ts +++ b/apps/api/src/experiment-openapi.test.ts @@ -3,6 +3,7 @@ import { beforeAll, describe, expect, it, vi } from "vitest"; import type { OpenAPIObject } from "openapi3-ts/oas31"; +import { LEGACY_REQUEST_COMPOSITION_DEPRECATION_ID } from "shared"; vi.mock("db-migrations/check-migrations", () => ({ checkMigrations: vi.fn().mockResolvedValue({ @@ -34,6 +35,12 @@ beforeAll(async () => { }); describe("Experiment OpenAPI contract", () => { + it("exports the shared legacy composition deprecation identifier", () => { + expect(LEGACY_REQUEST_COMPOSITION_DEPRECATION_ID).toBe( + "legacy-request-composition", + ); + }); + it("publishes canonical experiment operations", () => { expect(document.paths).toHaveProperty("/api/v1/experiments"); expect(document.paths).toHaveProperty("/api/v1/experiments/{id}"); diff --git a/apps/api/src/grouping.test.ts b/apps/api/src/grouping.test.ts index 746498c58..9ecc86bf6 100644 --- a/apps/api/src/grouping.test.ts +++ b/apps/api/src/grouping.test.ts @@ -19,6 +19,14 @@ describe("buildGroupingPipeline", () => { expect(pipeline).toHaveLength(4); }); + it("preserves submissionId grouping", () => { + const pipeline = buildGroupingPipeline("submissionId"); + expect(pipeline).toHaveLength(4); + expect( + (pipeline[0].$addFields as Record)._groupKey, + ).toBeDefined(); + }); + it("$sort stage orders by key ascending", () => { const pipeline = buildGroupingPipeline("task"); expect(pipeline[3]).toEqual({ $sort: { key: 1 } }); @@ -74,6 +82,7 @@ describe("buildGroupingPipeline", () => { expect(group._agentVersions).toBeDefined(); expect(group._platforms).toBeDefined(); expect(group._statuses).toBeDefined(); + expect(group._submissionIds).toBeDefined(); expect(group._experimentIds).toBeDefined(); expect(group._tasks).toBeDefined(); expect(group._mcpKeys).toBeDefined(); diff --git a/apps/api/src/grouping.ts b/apps/api/src/grouping.ts index d3ae0f60b..307e2bedc 100644 --- a/apps/api/src/grouping.ts +++ b/apps/api/src/grouping.ts @@ -12,12 +12,22 @@ import type { GroupByKey, RunGroup, AggregateStats, GroupUniformValues } from "s * The pipeline is appended after a $match stage with the caller's filter. */ export function buildGroupingPipeline( - groupBy: "task" | "experimentId" | "profile", + groupBy: "task" | "submissionId" | "experimentId" | "profile", ): Document[] { const groupField = - groupBy === "task" ? "$taskPromptId" : groupBy === "profile" ? "$profileId" : "$experimentId"; + groupBy === "task" + ? "$taskPromptId" + : groupBy === "profile" + ? "$profileId" + : groupBy === "submissionId" + ? "$submissionId" + : "$experimentId"; const fallbackGroupField = - groupBy === "profile" ? { $literal: "no-profile" } : { $literal: "no-experiment" }; + groupBy === "profile" + ? { $literal: "no-profile" } + : groupBy === "submissionId" + ? { $literal: "no-submission" } + : { $literal: "no-experiment" }; // `task` groups purely by the always-present `taskPromptId` — it is // materialized on every run-creation path (findOrCreate → taskPrompt._id) and // backfilled onto legacy docs by migration 001, so the group key is always a @@ -131,6 +141,7 @@ export function buildGroupingPipeline( _agentVersions: { $addToSet: { $ifNull: ["$agentVersion", ""] } }, _platforms: { $addToSet: { $ifNull: ["$run.os.platform", ""] } }, _statuses: { $addToSet: "$run.status" }, + _submissionIds: { $addToSet: { $ifNull: ["$submissionId", ""] } }, _experimentIds: { $addToSet: { $ifNull: ["$experimentId", ""] } }, _tasks: { $addToSet: { $ifNull: ["$scenario.task", ""] } }, _mcpKeys: { $addToSet: "$_mcpKey" }, @@ -183,6 +194,7 @@ export function buildGroupingPipeline( agentVersion: { $cond: { if: { $and: [{ $eq: [{ $size: "$_agentVersions" }, 1] }, { $ne: [{ $arrayElemAt: ["$_agentVersions", 0] }, ""] }] }, then: { $arrayElemAt: ["$_agentVersions", 0] }, else: "$$REMOVE" } }, platform: { $cond: { if: { $and: [{ $eq: [{ $size: "$_platforms" }, 1] }, { $ne: [{ $arrayElemAt: ["$_platforms", 0] }, ""] }] }, then: { $arrayElemAt: ["$_platforms", 0] }, else: "$$REMOVE" } }, status: { $cond: { if: { $eq: [{ $size: "$_statuses" }, 1] }, then: { $arrayElemAt: ["$_statuses", 0] }, else: "$$REMOVE" } }, + submissionId: { $cond: { if: { $and: [{ $eq: [{ $size: "$_submissionIds" }, 1] }, { $ne: [{ $arrayElemAt: ["$_submissionIds", 0] }, ""] }] }, then: { $arrayElemAt: ["$_submissionIds", 0] }, else: "$$REMOVE" } }, experimentId: { $cond: { if: { $and: [{ $eq: [{ $size: "$_experimentIds" }, 1] }, { $ne: [{ $arrayElemAt: ["$_experimentIds", 0] }, ""] }] }, then: { $arrayElemAt: ["$_experimentIds", 0] }, else: "$$REMOVE" } }, task: { $cond: { if: { $and: [{ $eq: [{ $size: "$_tasks" }, 1] }, { $ne: [{ $arrayElemAt: ["$_tasks", 0] }, ""] }] }, then: { $arrayElemAt: ["$_tasks", 0] }, else: "$$REMOVE" } }, mcpServers: { $cond: { if: { $and: [{ $eq: [{ $size: "$_mcpKeys" }, 1] }, { $ne: [{ $arrayElemAt: ["$_mcpKeys", 0] }, ""] }] }, then: "$_firstMcpServers", else: "$$REMOVE" } }, diff --git a/apps/api/src/routes/experiments.test.ts b/apps/api/src/routes/experiments.test.ts index 677e1633f..d778f48c2 100644 --- a/apps/api/src/routes/experiments.test.ts +++ b/apps/api/src/routes/experiments.test.ts @@ -94,6 +94,36 @@ describe("Experiment API contract", () => { expect(retry.status).toBe(400); }); + it("requires and verifies project scope on execution routes", async () => { + const findOne = vi.fn().mockResolvedValue(null); + const { app } = harness({ + experimentCollection: { findOne }, + } as unknown as Partial); + + const historyWithoutProject = await request(app).get( + "/api/v1/experiments/experiment-1/executions", + ); + const exactWithoutProject = await request(app).get( + "/api/v1/experiments/experiment-1/executions/execution-1", + ); + const wrongProject = await request(app).get( + "/api/v1/experiments/experiment-1/executions?projectId=wrong-project", + ); + const wrongProjectExact = await request(app).get( + "/api/v1/experiments/experiment-1/executions/execution-1?projectId=wrong-project", + ); + + expect(historyWithoutProject.status).toBe(400); + expect(exactWithoutProject.status).toBe(400); + expect(wrongProject.status).toBe(404); + expect(wrongProjectExact.status).toBe(404); + expect(findOne).toHaveBeenCalledWith({ + _id: "experiment-1", + projectId: "wrong-project", + finalizedAt: { $exists: true }, + }); + }); + it("enforces explicit empty and compose modes", async () => { const { app } = harness(); diff --git a/apps/api/src/routes/experiments.ts b/apps/api/src/routes/experiments.ts index 824b1442b..4739afe58 100644 --- a/apps/api/src/routes/experiments.ts +++ b/apps/api/src/routes/experiments.ts @@ -525,15 +525,17 @@ export function registerExperimentsRoutes(ctx: RouteContext): void { tags: ["Experiments"], summary: "List current and historical experiment executions", params: z.object({ id: z.string().min(1) }), - query: z.object({ + query: ProjectIdQuerySchema.extend({ limit: z.coerce.number().int().min(1).max(100).default(50), after: CursorSchema, }), response: ExecutionListResponseSchema, errorResponses: { 404: { description: "Experiment not found" } }, handler: async (req, res) => { + const projectId = getQueryProjectId(req); const experiment = await ctx.experimentCollection.findOne({ _id: req.params.id, + projectId, finalizedAt: { $exists: true }, }); if (!experiment) { @@ -589,11 +591,14 @@ export function registerExperimentsRoutes(ctx: RouteContext): void { id: z.string().min(1), experimentExecutionId: z.string().min(1), }), + query: ProjectIdQuerySchema, response: ExecutionResponseSchema, errorResponses: { 404: { description: "Experiment execution not found" } }, handler: async (req, res) => { + const projectId = getQueryProjectId(req); const experiment = await ctx.experimentCollection.findOne({ _id: req.params.id, + projectId, finalizedAt: { $exists: true }, }); if (!experiment) { diff --git a/apps/api/src/routes/requests/archive.test.ts b/apps/api/src/routes/requests/archive.test.ts index e9ad843d5..bdb1fce40 100644 --- a/apps/api/src/routes/requests/archive.test.ts +++ b/apps/api/src/routes/requests/archive.test.ts @@ -304,6 +304,7 @@ function makeFixtureRun(id = "run-fixture-1") { workerType: "coder-acp-copilot", createdAt: new Date("2026-01-01T00:00:00Z"), priority: 0, + submissionId: "submission-abc", run: { _id: id, attemptNumber: 1, @@ -764,6 +765,7 @@ describe("run import/export — round-trip (export → import)", () => { updatedAt: new Date("2026-05-11T23:04:47.446Z"), maxIterations: 1, priority: 0, + submissionId: "sub-rich-1", run: { _id: runId, attemptNumber: 2, // ← not 1; previous code hard-coded 1 @@ -954,7 +956,7 @@ describe("run import/export — round-trip (export → import)", () => { describe("run import — task-prompt entity creation (#832)", () => { // Task-prompt entities back features, report triggers, group-by-task, // the runs-list task filter and the criteria/MDP analysis. The submission - // flow (POST /api/v1/requests) materializes them via + // request flow (POST /api/v1/requests) materializes them via // taskPromptStore.findOrCreate(scenario.task). Imported runs used to skip // this step entirely \u2014 `taskPromptId` was preserved from `run.yaml` but // no row was ever created, leaving a dangling reference. @@ -1001,6 +1003,7 @@ describe("run import — task-prompt entity creation (#832)", () => { // The inserted request points at it. const inserted = reqCollection.docs.get(id); expect(inserted.taskPromptId).toBe(expectedId); + expect(inserted.submissionId).toEqual(expect.any(String)); }); it("reuses an existing task prompt and does not create a duplicate", async () => { diff --git a/apps/api/src/routes/requests/index.ts b/apps/api/src/routes/requests/index.ts index 07987a124..0b5d2df81 100644 --- a/apps/api/src/routes/requests/index.ts +++ b/apps/api/src/routes/requests/index.ts @@ -37,6 +37,7 @@ import { isCriterionCompatibleWithGate, orderGates, computeTaskPromptId, + LEGACY_REQUEST_COMPOSITION_DEPRECATION_ID, } from "shared"; import { trackMetric } from "telemetry"; import type { @@ -236,9 +237,6 @@ const validatePersistedRequestTarget = (request: RequestDocument) => /** Maximum number of profile variations (including the base profile) allowed in one submit. */ const MAX_PROFILE_VARIATIONS = 25; -const LEGACY_EXPERIMENT_COMPOSITION_ID = - "scope.api.requests.legacy-experiment-composition.v1"; - function emitLegacyCompositionHeaders( res: { setHeader(name: string, value: string): void }, properties: readonly string[], @@ -253,7 +251,7 @@ function emitLegacyCompositionHeaders( name: "api.deprecated_input_used", value: 1, properties: { - identifier: LEGACY_EXPERIMENT_COMPOSITION_ID, + identifier: LEGACY_REQUEST_COMPOSITION_DEPRECATION_ID, properties: [...properties].sort().join(","), }, }); @@ -871,14 +869,14 @@ apiRoute(ctx.app, ctx.registry, { }); } - // Pass 2: build independent request documents. Comparative composition is - // represented only by POST /experiments. + // Preserve the legacy request-batch correlation value. Experiments remain + // explicit resources created only by POST /experiments. + const submissionId = uuidv4(); const allNewIds: string[] = []; const newDocs: RequestDocument[] = []; const variationResults: Array<{ profileId: string; label?: string; ids: string[] }> = []; const agentsMdPromptId = await resolveAgentsMdPromptId(); const agentsMdFields = buildAgentsMdFields(agentsMdPromptId); - const expectedRequestCount = resolved.length * count; for (const r of resolved) { const newIds: string[] = []; @@ -912,6 +910,7 @@ apiRoute(ctx.app, ctx.registry, { profileId: r.profile._id, profileVersionId: r.profileVersion.ref ?? r.profileVersion._id, ...(persistedVariationGates ? { gates: persistedVariationGates } : {}), + submissionId, ...agentsMdFields, run: { _id: runId, attemptNumber: 1, status: "pending", logsUrl: ctx.blobStorage.getLogsBlobUrl(`${requestId}/runs/${runId}/run.jsonl`) }, }; @@ -929,6 +928,7 @@ apiRoute(ctx.app, ctx.registry, { res.status(201).json({ ids: allNewIds, count: allNewIds.length, + submissionId, variations: variationResults, variationCount: variationEntries.length, status: "pending", @@ -1311,6 +1311,7 @@ apiRoute(ctx.app, ctx.registry, { const persistedObservations: string[] | undefined = observationsProvided ? [...new Set(resolvedObservations)] : undefined; + const submissionId = uuidv4(); // Handle multiple runs (count > 1) if (count > 1) { @@ -1345,6 +1346,7 @@ apiRoute(ctx.app, ctx.registry, { ...(profileVersionId ? { profileVersionId } : {}), ...(persistedGates ? { gates: persistedGates } : {}), ...(persistedObservations ? { observations: persistedObservations } : {}), + submissionId, ...agentsMdFields, // Mint a distinct run id for the first attempt. Blob artifacts // are scoped under `{requestId}/runs/{runId}/...` so retries @@ -1362,6 +1364,7 @@ apiRoute(ctx.app, ctx.registry, { res.status(201).json({ ids: newIds, count, + submissionId, workerType, taskPromptId, ...(model ? { model } : {}), @@ -1406,6 +1409,7 @@ apiRoute(ctx.app, ctx.registry, { ...(profileVersionId ? { profileVersionId } : {}), ...(persistedGates ? { gates: persistedGates } : {}), ...(persistedObservations ? { observations: persistedObservations } : {}), + submissionId, ...agentsMdFields, // Mint a distinct run id for the first attempt. Blob artifacts // are scoped under `{requestId}/runs/{runId}/...` so retries @@ -1420,6 +1424,7 @@ apiRoute(ctx.app, ctx.registry, { res.status(201).json({ id: requestId, + submissionId, workerType, ...(model ? { model } : {}), ...(effectiveReasoningEffort ? { reasoningEffort: effectiveReasoningEffort } : {}), @@ -1502,6 +1507,7 @@ apiRoute(ctx.app, ctx.registry, { const projectId = getQueryProjectId(req); const taskPromptIdFilter = req.query.taskPromptId as string; const criteriaFilter = req.query.criteria as string; + const submissionIdFilter = req.query.submissionId as string; const experimentIdFilter = req.query.experimentId as string; const searchFilter = req.query.search as string | undefined; const turnsFilterRaw = req.query.turns as string | undefined; @@ -1509,7 +1515,12 @@ apiRoute(ctx.app, ctx.registry, { const maxIterationsFilterRaw = req.query.maxIterations as string | undefined; const maxIterationsOpFilter = (req.query.maxIterationsOp as string | undefined) ?? "eq"; const includeDeleted = req.query.includeDeleted === "true"; - const groupByParam = req.query.groupBy as "task" | "experimentId" | "profile" | undefined; + const groupByParam = req.query.groupBy as + | "task" + | "submissionId" + | "experimentId" + | "profile" + | undefined; const limit = Math.min(Math.max(Number(req.query.limit) || 10, 1), 100); const afterParam = req.query.after as string | undefined; const beforeParam = req.query.before as string | undefined; @@ -1576,6 +1587,11 @@ apiRoute(ctx.app, ctx.registry, { pushClause(buildMultiClause("priority", priorityValues, { coerceNumber: true })); pushClause(buildMultiClause("agentVersion", agentVersionValues)); + if (submissionIdFilter) { + flat.submissionId = { + $regex: `^${submissionIdFilter.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`, + }; + } if (experimentIdFilter) { // Prefix-based matching: allow filtering by partial experiment ID. flat.experimentId = { $regex: `^${experimentIdFilter.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}` }; @@ -1675,7 +1691,12 @@ apiRoute(ctx.app, ctx.registry, { // Grouped mode: paginated RunGroup[] via two-phase aggregation if (groupByParam) { - const groupByField = groupByParam === "task" ? "taskPromptId" : groupByParam === "profile" ? "profileId" : "experimentId"; + const groupByField = + groupByParam === "task" + ? "taskPromptId" + : groupByParam === "profile" + ? "profileId" + : groupByParam; const groupByAggField = `$${groupByField}`; // Decode group cursor @@ -1908,6 +1929,7 @@ apiRoute(ctx.app, ctx.registry, { taskPromptId: z.string().optional(), criteria: z.string().optional(), features: z.string().optional(), + submissionId: z.string().optional(), experimentId: z.string().optional(), k: z.string().optional(), }).merge(ProjectIdQuerySchema), @@ -2092,6 +2114,7 @@ apiRoute(ctx.app, ctx.registry, { const foundIds = new Set(originalRuns.map(r => r._id)); const notFound = ids.filter((id: string) => !foundIds.has(id)); + const submissionId = uuidv4(); const newIds: string[] = []; const newDocs: RequestDocument[] = []; @@ -2230,6 +2253,7 @@ apiRoute(ctx.app, ctx.registry, { // Preserve AGENTS.md lineage across re-submits. ...(original.agentsMdPromptId ? { agentsMdPromptId: original.agentsMdPromptId } : {}), ...(original.agentsMdParentIds && original.agentsMdParentIds.length > 0 ? { agentsMdParentIds: original.agentsMdParentIds } : {}), + submissionId, // Bulk re-submit creates a brand-new request — mint a distinct // run id for the first attempt so blob artifacts live under // `{requestId}/runs/{runId}/...` (independent of the original run). @@ -2251,6 +2275,7 @@ apiRoute(ctx.app, ctx.registry, { submitted: newIds.length, failed: notFound, newIds, + submissionId, }); }, }); @@ -2673,6 +2698,7 @@ async function finalizePendingRun( createdAt: runDoc.createdAt ?? new Date(), priority: runDoc.priority ?? 0, taskPromptId: resolvedTaskPromptId, + ...(runDoc.submissionId ? {} : { submissionId: uuidv4() }), run: { ...(runState as unknown as RunState), // Per-attempt `run._id` is preserved from the yaml (NOT clobbered diff --git a/packages/shared/src/schemas/request.ts b/packages/shared/src/schemas/request.ts index 029c03e09..bf4c75743 100644 --- a/packages/shared/src/schemas/request.ts +++ b/packages/shared/src/schemas/request.ts @@ -187,6 +187,7 @@ export const RequestResponseSchema = z agentVersion: z.string().optional(), profileId: z.string().optional(), profileVersionId: z.string().optional(), + submissionId: z.string().optional(), experimentId: z.string().optional(), experimentExpectedRequestCount: z.number().int().min(0).optional(), experimentRequestIndex: z.number().int().min(0).optional(), @@ -294,6 +295,7 @@ export const ListRequestsQuerySchema = z worker: MultiValueParam, taskPromptId: z.string().optional(), criteria: z.string().optional(), + submissionId: z.string().optional(), experimentId: z.string().optional(), profileId: MultiValueParam, status: MultiValueParam, @@ -304,7 +306,9 @@ export const ListRequestsQuerySchema = z agentVersion: MultiValueParam, // Free-text, case-insensitive search across run id, scenario task, model, worker. search: z.string().optional(), - groupBy: z.enum(["task", "experimentId", "profile"]).optional(), + groupBy: z + .enum(["task", "submissionId", "experimentId", "profile"]) + .optional(), limit: z.coerce.number().int().min(1).max(100).optional(), after: z.string().optional(), before: z.string().optional(), @@ -377,6 +381,7 @@ export const GroupUniformValuesSchema = z codebaseRevisionId: z.string().optional(), extensions: z.array(z.string()).optional(), status: RequestStatusSchema.optional(), + submissionId: z.string().optional(), experimentId: z.string().optional(), task: z.string().optional(), }) diff --git a/packages/shared/src/types/types.ts b/packages/shared/src/types/types.ts index 93d76d525..016e980f8 100644 --- a/packages/shared/src/types/types.ts +++ b/packages/shared/src/types/types.ts @@ -384,6 +384,7 @@ export interface RequestDocument { agentVersion?: string; // Agent software version prefix (e.g. "copilot-0.0.415") — FK → AgentVersion.agentVersion profileId?: string; // FK → ProfileDocument._id (the profile lineage) profileVersionId?: string; // FK → ProfileVersionDocument._id (exact version used) + submissionId?: string; // Legacy request-batch correlation identifier (not a resource FK) experimentId?: string; // FK → ExperimentDocument._id /** Expected native request count for interrupted ExperimentDocument finalization. * Historical/imported requests omit it and remain view-only if their parent @@ -600,6 +601,9 @@ export interface ExperimentQueueMessagePayload { experimentExecutionId: string; } +export const LEGACY_REQUEST_COMPOSITION_DEPRECATION_ID = + "legacy-request-composition" as const; + /** * Field names whose values move from `RequestDocument` (top-level, legacy * shape) into `RequestDocument.run: RunState` (new shape introduced for @@ -733,7 +737,12 @@ export interface QueueProcessorConfig extends BaseQueueProcessorConfig { // --- Runs grouping types (shared between API and portal) --- -export type GroupByKey = "none" | "task" | "experimentId" | "profile"; +export type GroupByKey = + | "none" + | "task" + | "submissionId" + | "experimentId" + | "profile"; export interface AggregateStats { min: number; @@ -751,6 +760,7 @@ export interface GroupUniformValues { skillRevisions?: string[]; extensions?: string[]; status?: "pending" | "processing" | "done"; + submissionId?: string; experimentId?: string; task?: string; } From 48f244b80774d0f1fc4b9bc3b42a209b0cf62fa9 Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Thu, 15 Oct 2026 23:14:34 -0700 Subject: [PATCH 049/210] feat(shared): add experiment payload CAS updates Add representation-preserving request projection updates with root publication claims, versioned bucket CAS, resumable partial-failure outcomes, and inline/chunked concurrency coverage. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 8fe76b9e-1205-4910-b51b-e8fa51538125 --- .../src/experiments/experiment-store.test.ts | 309 +++++++++++++++++- .../src/experiments/experiment-store.ts | 270 ++++++++++++++- .../experiments/fixed-payload-store.test.ts | 237 +++++++++++++- .../src/experiments/fixed-payload-store.ts | 228 ++++++++++++- packages/shared/src/experiments/layout.ts | 28 +- packages/shared/src/experiments/routing.ts | 9 + .../shared/src/experiments/schemas.test.ts | 1 + packages/shared/src/experiments/schemas.ts | 11 + packages/shared/src/experiments/types.ts | 36 ++ 9 files changed, 1100 insertions(+), 29 deletions(-) diff --git a/packages/shared/src/experiments/experiment-store.test.ts b/packages/shared/src/experiments/experiment-store.test.ts index f9e0e0e1c..fe823a92a 100644 --- a/packages/shared/src/experiments/experiment-store.test.ts +++ b/packages/shared/src/experiments/experiment-store.test.ts @@ -4,10 +4,16 @@ import type { Collection, Document } from "mongodb"; import { describe, expect, it } from "vitest"; import { ExperimentStore } from "./experiment-store.js"; +import { FixedPayloadStore } from "./fixed-payload-store.js"; +import { + fingerprintExperimentPayload, + fingerprintExperimentRequestVector, +} from "./routing.js"; import { EXPERIMENT_STORAGE_PROFILE_VERSION, type ExperimentDocument, type ExperimentExecutionHistoryDocument, + type ExperimentRequestState, } from "./types.js"; function getPath(source: object, path: string): unknown { @@ -27,11 +33,23 @@ function setPath(target: object, path: string, value: unknown): void { if (typeof next !== "object" || next === null) { current[segment] = {}; } + current = current[segment] as Record; } current[segments.at(-1)!] = value; } +function unsetPath(target: object, path: string): void { + const segments = path.split("."); + let current = target as Record; + for (const segment of segments.slice(0, -1)) { + const next = current[segment]; + if (typeof next !== "object" || next === null) return; + current = next as Record; + } + delete current[segments.at(-1)!]; +} + function matches(document: object, filter: Document): boolean { return Object.entries(filter).every(([path, expected]) => { const actual = getPath(document, path); @@ -51,8 +69,13 @@ function matches(document: object, filter: Document): boolean { function atomicCollection(initial: ExperimentDocument) { let document = structuredClone(initial); + let findOneAndUpdateCalls = 0; + let failAtCall: number | undefined; return { current: () => structuredClone(document), + failOnFindOneAndUpdate(call: number) { + failAtCall = call; + }, async findOne(filter: Document) { return matches(document, filter) ? structuredClone(document) : null; }, @@ -61,8 +84,13 @@ function atomicCollection(initial: ExperimentDocument) { update: { $set?: Record; $inc?: Record; + $unset?: Record; }, ) { + findOneAndUpdateCalls += 1; + if (findOneAndUpdateCalls === failAtCall) { + throw new Error("injected root publication failure"); + } if (!matches(document, filter)) return null; const next = structuredClone(document); for (const [path, value] of Object.entries(update.$set ?? {})) { @@ -73,14 +101,39 @@ function atomicCollection(initial: ExperimentDocument) { if (typeof value !== "number") throw new Error(`Non-number ${path}`); setPath(next, path, value + increment); } + for (const path of Object.keys(update.$unset ?? {})) { + unsetPath(next, path); + } document = next; return structuredClone(document); }, + async updateOne( + filter: Document, + update: { + $set?: Record; + $inc?: Record; + $unset?: Record; + }, + ) { + const updated = await this.findOneAndUpdate(filter, update); + return { + matchedCount: updated ? 1 : 0, + modifiedCount: updated ? 1 : 0, + }; + }, }; } function experiment(): ExperimentDocument { const now = new Date("2026-01-01T00:00:00.000Z"); + const entries = [ + { + requestId: "request-1", + runId: "run-1", + dependencies: [], + blockers: [], + }, + ]; return { _id: "experiment-1", experimentId: "experiment-1", @@ -103,17 +156,11 @@ function experiment(): ExperimentDocument { requests: { storage: "inline", entryCount: 1, - payloadFingerprint: "payload", - entries: [ - { - requestId: "request-1", - runId: "run-1", - dependencies: [], - blockers: [], - }, - ], + payloadFingerprint: fingerprintExperimentPayload(entries), + payloadVersion: 1, + entries, }, - vectorFingerprint: "vector", + vectorFingerprint: fingerprintExperimentRequestVector(entries), handlerSummary: { report: { status: "queued", @@ -132,6 +179,44 @@ function experiment(): ExperimentDocument { }; } +function chunkCollection() { + const documents = new Map(); + return { + async updateOne( + filter: Document, + update: { $setOnInsert?: Document; $set?: Document }, + ) { + const id = String(filter._id); + const existing = documents.get(id); + if (!existing && update.$setOnInsert) { + documents.set(id, structuredClone(update.$setOnInsert)); + return { matchedCount: 1, modifiedCount: 1 }; + } + if (!existing) return { matchedCount: 0, modifiedCount: 0 }; + const matches = Object.entries(filter).every(([key, expected]) => { + const actual = existing[key]; + if ( + typeof expected === "object" && + expected !== null && + "$exists" in expected + ) { + return ( + (actual !== undefined) === + Boolean((expected as { $exists: unknown }).$exists) + ); + } + return actual === expected; + }); + if (!matches) return { matchedCount: 0, modifiedCount: 0 }; + if (update.$set) Object.assign(existing, structuredClone(update.$set)); + return { matchedCount: 1, modifiedCount: 1 }; + }, + async findOne(filter: Document) { + return documents.get(String(filter._id)) ?? null; + }, + }; +} + describe("ExperimentStore CAS contracts", () => { it("allows exactly one winner in a writer-freezer race", async () => { const experiments = atomicCollection(experiment()); @@ -248,4 +333,208 @@ describe("ExperimentStore CAS contracts", () => { claimToken: "claim-1", }); }); + + it("serializes request-state writers against the freezer", async () => { + const experiments = atomicCollection(experiment()); + const store = new ExperimentStore({ + experiments: + experiments as unknown as Collection, + executions: + {} as Collection, + chunks: {} as Collection, + }); + const projected = [ + { + requestId: "request-1", + runId: "run-1", + dependencies: [ + { handlerId: "observations", state: "ready" as const }, + ], + blockers: [], + }, + ]; + + const [writer, freezer] = await Promise.all([ + store.casUpdateRequestStates({ + projectId: "project-1", + experimentId: "experiment-1", + experimentExecutionId: "execution-1", + expectedExecutionVersion: 1, + updateId: "projection-1", + requests: projected, + }), + store.freezeCurrent({ + projectId: "project-1", + experimentId: "experiment-1", + experimentExecutionId: "execution-1", + expectedExecutionVersion: 1, + }), + ]); + + const writerWon = writer.status === "applied"; + expect(writerWon || freezer !== null).toBe(true); + expect(writerWon && freezer !== null).toBe(false); + if (writerWon) { + expect(writer.requests).toEqual(projected); + expect(writer.experiment.execution.requests.storage).toBe("inline"); + expect(writer.experiment.execution.version).toBe(3); + } else { + expect(writer).toMatchObject({ status: "stale" }); + expect(freezer?.execution.frozenAt).toBeInstanceOf(Date); + } + }); + + it("rejects request/run vector changes as an invariant violation", async () => { + const experiments = atomicCollection(experiment()); + const store = new ExperimentStore({ + experiments: + experiments as unknown as Collection, + executions: + {} as Collection, + chunks: {} as Collection, + }); + + await expect( + store.casUpdateRequestStates({ + projectId: "project-1", + experimentId: "experiment-1", + experimentExecutionId: "execution-1", + expectedExecutionVersion: 1, + updateId: "projection-invalid", + requests: [ + { + requestId: "request-1", + runId: "different-run", + dependencies: [], + blockers: [], + }, + ], + }), + ).resolves.toMatchObject({ + status: "invariant", + message: + "Request-state update cannot change the immutable request/run vector", + }); + }); + + it("surfaces a root publication fault and resumes the same update id", async () => { + const experiments = atomicCollection(experiment()); + experiments.failOnFindOneAndUpdate(2); + const store = new ExperimentStore({ + experiments: + experiments as unknown as Collection, + executions: + {} as Collection, + chunks: {} as Collection, + }); + const projected = [ + { + requestId: "request-1", + runId: "run-1", + dependencies: [ + { handlerId: "observations", state: "ready" as const }, + ], + blockers: [], + }, + ]; + const input = { + projectId: "project-1", + experimentId: "experiment-1", + experimentExecutionId: "execution-1", + expectedExecutionVersion: 1, + updateId: "projection-retry", + requests: projected, + }; + + await expect(store.casUpdateRequestStates(input)).resolves.toMatchObject({ + status: "partial-failure", + updateId: "projection-retry", + retryable: true, + message: "injected root publication failure", + }); + expect( + experiments.current().execution.requestStateUpdate?.updateId, + ).toBe("projection-retry"); + + const repaired = await store.casUpdateRequestStates(input); + expect(repaired.status).toBe("applied"); + if (repaired.status !== "applied") throw new Error("expected applied"); + expect(repaired.requests).toEqual(projected); + expect( + repaired.experiment.execution.requestStateUpdate, + ).toBeUndefined(); + }); + + it("publishes the same projection semantics through a chunked execution", async () => { + const chunks = chunkCollection(); + const payloadStore = new FixedPayloadStore( + chunks as unknown as Collection, + ); + const entries: ExperimentRequestState[] = Array.from( + { length: 70 }, + (_, index) => ({ + requestId: `request-${index}`, + runId: `run-${index}`, + dependencies: [], + blockers: [], + }), + ); + const identity = { + projectId: "project-1", + experimentId: "experiment-1", + ownerId: "execution-1", + generation: 1, + }; + const payload = await payloadStore.prepareRequests({ + identity, + entries, + inlineDocument: (value) => ({ + value, + padding: "x".repeat(256 * 1024), + }), + }); + if (payload.storage !== "chunked") throw new Error("expected chunked"); + const root = experiment(); + root.revision.memberCount = entries.length; + root.execution.requests = payload; + root.execution.vectorFingerprint = + fingerprintExperimentRequestVector(entries); + const experiments = atomicCollection(root); + const store = new ExperimentStore({ + experiments: + experiments as unknown as Collection, + executions: + {} as Collection, + chunks: chunks as unknown as Collection, + }); + const projected = entries.map((entry) => ({ + ...entry, + dependencies: [ + { handlerId: "observations", state: "ready" as const }, + ], + })); + + const result = await store.casUpdateRequestStates({ + projectId: "project-1", + experimentId: "experiment-1", + experimentExecutionId: "execution-1", + expectedExecutionVersion: 1, + updateId: "chunked-projection", + requests: projected, + }); + + expect(result.status).toBe("applied"); + if (result.status !== "applied") throw new Error("expected applied"); + const updatedPayload = result.experiment.execution.requests; + expect(updatedPayload.storage).toBe("chunked"); + if (updatedPayload.storage !== "chunked") { + throw new Error("expected chunked"); + } + expect(updatedPayload.bucketCount).toBe(payload.bucketCount); + expect(updatedPayload.assignmentVersion).toBe(payload.assignmentVersion); + expect(updatedPayload.chunkIds).toEqual(payload.chunkIds); + expect( + await payloadStore.readRequests(identity, updatedPayload), + ).toEqual(projected); + }); }); diff --git a/packages/shared/src/experiments/experiment-store.ts b/packages/shared/src/experiments/experiment-store.ts index ce9ab4f1e..da21e733d 100644 --- a/packages/shared/src/experiments/experiment-store.ts +++ b/packages/shared/src/experiments/experiment-store.ts @@ -11,7 +11,10 @@ import { ExperimentRequestStateSchema, ExperimentRevisionSchema, } from "./schemas.js"; -import { fingerprintExperimentPayload } from "./routing.js"; +import { + fingerprintExperimentPayload, + fingerprintExperimentRequestVector, +} from "./routing.js"; import { EXPERIMENT_STORAGE_PROFILE_VERSION, type ExperimentDocument, @@ -21,6 +24,7 @@ import { type ExperimentMetadata, type ExperimentPage, type ExperimentRequestState, + type ExperimentRequestStateUpdateResult, type ExperimentRevision, type FixedPayload, } from "./types.js"; @@ -128,7 +132,7 @@ export class ExperimentStore { attemptNumber: 1, version: 1, requests: payload, - vectorFingerprint: fingerprintExperimentPayload(requests), + vectorFingerprint: fingerprintExperimentRequestVector(requests), handlerSummary: input.handlerSummary ?? {}, blocking: input.blocking ?? [], createdAt: now, @@ -409,6 +413,7 @@ export class ExperimentStore { "execution.version": input.expectedExecutionVersion, "execution.frozenAt": { $exists: false }, "execution.rollover": { $exists: false }, + "execution.requestStateUpdate": { $exists: false }, } as Document, { $set: { @@ -423,6 +428,244 @@ export class ExperimentStore { return updated ? parseExperiment(updated) : null; } + async casUpdateRequestStates(input: { + projectId: string; + experimentId: string; + experimentExecutionId: string; + expectedExecutionVersion: number; + updateId: string; + requests: readonly ExperimentRequestState[]; + now?: Date; + }): Promise { + if (input.updateId.trim().length === 0 || input.updateId.length > 200) { + return { + status: "invariant", + message: "Request-state updateId must contain 1-200 characters", + }; + } + let requests: ExperimentRequestState[]; + try { + requests = input.requests.map((request) => + ExperimentRequestStateSchema.parse(request), + ) as ExperimentRequestState[]; + } catch (error) { + return { + status: "invariant", + message: error instanceof Error ? error.message : String(error), + }; + } + if ( + new Set(requests.map((request) => request.requestId)).size !== + requests.length + ) { + return { + status: "invariant", + message: "Request-state update contains duplicate request ids", + }; + } + const nextPayloadFingerprint = fingerprintExperimentPayload(requests); + const nextVectorFingerprint = + fingerprintExperimentRequestVector(requests); + let experiment = await this.getRaw(input.projectId, input.experimentId); + if (!experiment) return { status: "stale", reason: "experiment" }; + if ( + experiment.execution.experimentExecutionId !== + input.experimentExecutionId + ) { + return { status: "stale", reason: "execution" }; + } + if (experiment.execution.frozenAt) { + return { status: "stale", reason: "frozen" }; + } + if ( + experiment.execution.vectorFingerprint !== nextVectorFingerprint || + experiment.execution.requests.entryCount !== requests.length + ) { + return { + status: "invariant", + message: + "Request-state update cannot change the immutable request/run vector", + }; + } + + const activeClaim = experiment.execution.requestStateUpdate; + if (activeClaim) { + if (activeClaim.updateId !== input.updateId) { + return { + status: "contention", + activeUpdateId: activeClaim.updateId, + }; + } + if ( + activeClaim.nextPayloadFingerprint !== nextPayloadFingerprint || + activeClaim.expectedPayloadFingerprint !== + experiment.execution.requests.payloadFingerprint + ) { + return { + status: "invariant", + message: "Retried request-state update does not match its claim", + }; + } + if ( + experiment.execution.version !== + input.expectedExecutionVersion + 1 + ) { + return { status: "stale", reason: "version" }; + } + } else { + if ( + experiment.execution.version !== input.expectedExecutionVersion + ) { + return { status: "stale", reason: "version" }; + } + const claimedAt = input.now ?? new Date(); + let claimed: ExperimentDocument | null; + try { + claimed = await this.collections.experiments.findOneAndUpdate( + { + _id: input.experimentId, + projectId: input.projectId, + "execution.experimentExecutionId": + input.experimentExecutionId, + "execution.version": input.expectedExecutionVersion, + "execution.frozenAt": { $exists: false }, + "execution.rollover": { $exists: false }, + "execution.requestStateUpdate": { $exists: false }, + } as Document, + { + $set: { + "execution.requestStateUpdate": { + updateId: input.updateId, + expectedPayloadFingerprint: + experiment.execution.requests.payloadFingerprint, + nextPayloadFingerprint, + claimedAt, + }, + "execution.updatedAt": claimedAt, + updatedAt: claimedAt, + }, + $inc: { "execution.version": 1, stateVersion: 1 }, + } as Document, + { returnDocument: "after" }, + ); + } catch (error) { + return { + status: "partial-failure", + updateId: input.updateId, + updatedChunkIds: [], + message: error instanceof Error ? error.message : String(error), + retryable: true, + }; + } + if (!claimed) { + const raced = await this.getRaw( + input.projectId, + input.experimentId, + ); + if (raced?.execution.frozenAt) { + return { status: "stale", reason: "frozen" }; + } + if (raced?.execution.requestStateUpdate) { + return { + status: "contention", + activeUpdateId: + raced.execution.requestStateUpdate.updateId, + }; + } + return { status: "stale", reason: "version" }; + } + experiment = parseExperiment(claimed); + } + + const payloadResult = await this.payloads.casUpdateRequests({ + identity: this.executionIdentity(experiment), + payload: experiment.execution.requests, + entries: requests, + now: input.now, + }); + if (payloadResult.status !== "applied") { + if ( + payloadResult.status !== "partial-failure" && + payloadResult.updatedChunkIds.length === 0 + ) { + try { + await this.abortRequestStateUpdate(experiment, input.updateId); + } catch (error) { + return { + status: "partial-failure", + updateId: input.updateId, + updatedChunkIds: [], + message: error instanceof Error ? error.message : String(error), + retryable: true, + }; + } + } + if (payloadResult.status === "invariant") { + return { + status: "invariant", + message: payloadResult.message, + }; + } + if (payloadResult.status === "stale") { + return { status: "stale", reason: "version" }; + } + return { + status: "partial-failure", + updateId: input.updateId, + updatedChunkIds: payloadResult.updatedChunkIds, + message: payloadResult.message, + retryable: true, + }; + } + + const now = input.now ?? new Date(); + try { + const finalized = await this.collections.experiments.findOneAndUpdate( + { + _id: input.experimentId, + projectId: input.projectId, + "execution.experimentExecutionId": + input.experimentExecutionId, + "execution.version": input.expectedExecutionVersion + 1, + "execution.frozenAt": { $exists: false }, + "execution.requestStateUpdate.updateId": input.updateId, + } as Document, + { + $set: { + "execution.requests": payloadResult.payload, + "execution.updatedAt": now, + updatedAt: now, + }, + $unset: { "execution.requestStateUpdate": "" }, + $inc: { "execution.version": 1, stateVersion: 1 }, + } as Document, + { returnDocument: "after" }, + ); + if (!finalized) { + return { + status: "partial-failure", + updateId: input.updateId, + updatedChunkIds: payloadResult.updatedChunkIds, + message: "Request-state payload updated but root publication CAS failed", + retryable: true, + }; + } + return { + status: "applied", + experiment: parseExperiment(finalized), + requests, + }; + } catch (error) { + return { + status: "partial-failure", + updateId: input.updateId, + updatedChunkIds: payloadResult.updatedChunkIds, + message: error instanceof Error ? error.message : String(error), + retryable: true, + }; + } + } + async archiveCurrent(input: { projectId: string; experimentId: string; @@ -631,7 +874,7 @@ export class ExperimentStore { attemptNumber: current.attemptNumber + 1, version: 1, requests, - vectorFingerprint: fingerprintExperimentPayload(entries), + vectorFingerprint: fingerprintExperimentRequestVector(entries), handlerSummary: {}, blocking: [], createdAt: now, @@ -686,4 +929,25 @@ export class ExperimentStore { } return persisted; } + + private async abortRequestStateUpdate( + experiment: ExperimentDocument, + updateId: string, + ): Promise { + await this.collections.experiments.updateOne( + { + _id: experiment.experimentId, + projectId: experiment.projectId, + "execution.experimentExecutionId": + experiment.execution.experimentExecutionId, + "execution.version": experiment.execution.version, + "execution.requestStateUpdate.updateId": updateId, + } as Document, + { + $unset: { "execution.requestStateUpdate": "" }, + $set: { updatedAt: new Date() }, + $inc: { stateVersion: 1 }, + } as Document, + ); + } } diff --git a/packages/shared/src/experiments/fixed-payload-store.test.ts b/packages/shared/src/experiments/fixed-payload-store.test.ts index 9339dbecb..142415a30 100644 --- a/packages/shared/src/experiments/fixed-payload-store.test.ts +++ b/packages/shared/src/experiments/fixed-payload-store.test.ts @@ -18,16 +18,47 @@ function request(index: number): ExperimentRequestState { function chunkCollection(failAt?: number) { const documents = new Map(); let writes = 0; + let nextFailure = failAt; + function matches(document: Document, filter: Document): boolean { + return Object.entries(filter).every(([key, expected]) => { + const actual = document[key]; + if ( + typeof expected === "object" && + expected !== null && + "$exists" in expected + ) { + return ( + (actual !== undefined) === + Boolean((expected as { $exists: unknown }).$exists) + ); + } + return actual === expected; + }); + } return { documents, + failOnWrite(write: number) { + nextFailure = write; + }, + writeCount() { + return writes; + }, async updateOne( filter: Document, - update: { $setOnInsert: Document }, + update: { $setOnInsert?: Document; $set?: Document }, ) { writes += 1; - if (writes === failAt) throw new Error("injected write failure"); + if (writes === nextFailure) throw new Error("injected write failure"); const id = String(filter._id); - if (!documents.has(id)) documents.set(id, structuredClone(update.$setOnInsert)); + const existing = documents.get(id); + if (!existing && update.$setOnInsert) { + documents.set(id, structuredClone(update.$setOnInsert)); + return { matchedCount: 1, modifiedCount: 1 }; + } + if (!existing || !matches(existing, filter)) { + return { matchedCount: 0, modifiedCount: 0 }; + } + if (update.$set) Object.assign(existing, structuredClone(update.$set)); return { matchedCount: 1, modifiedCount: 1 }; }, async findOne(filter: Document) { @@ -127,4 +158,204 @@ describe("FixedPayloadStore", () => { store.readRequests({ ...identity, projectId: "other-project" }, payload), ).rejects.toThrow(/identity mismatch/); }); + + it.each(["inline", "chunked"] as const)( + "applies the same logical projection update for %s payloads", + async (storage) => { + const collection = chunkCollection(); + const store = new FixedPayloadStore( + collection as unknown as Collection, + ); + const ownerId = `execution-${storage}`; + const updateIdentity = { ...identity, ownerId }; + const entries = Array.from({ length: 70 }, (_, index) => request(index)); + const payload = await store.prepareRequests({ + identity: updateIdentity, + entries, + inlineDocument: (value) => ({ + value, + ...(storage === "chunked" + ? { padding: "x".repeat(256 * 1024) } + : {}), + }), + }); + expect(payload.storage).toBe(storage); + const projected = entries.map((entry, index) => ({ + ...entry, + dependencies: [ + { + handlerId: "observations", + state: index % 2 === 0 ? ("ready" as const) : ("waiting" as const), + }, + ], + blockers: + index % 2 === 0 + ? [] + : [ + { + handlerId: "observations", + reason: "dependency-not-ready" as const, + }, + ], + })); + + const result = await store.casUpdateRequests({ + identity: updateIdentity, + payload, + entries: projected, + }); + + expect(result.status).toBe("applied"); + if (result.status !== "applied") throw new Error("expected applied"); + expect(result.payload.storage).toBe(storage); + expect(result.payload.payloadVersion).toBe(payload.payloadVersion + 1); + if (payload.storage === "chunked" && result.payload.storage === "chunked") { + expect(result.payload.bucketCount).toBe(payload.bucketCount); + expect(result.payload.assignmentVersion).toBe(payload.assignmentVersion); + expect(result.payload.chunkIds).toEqual(payload.chunkIds); + } + expect( + await store.readRequests(updateIdentity, result.payload), + ).toEqual(projected); + }, + ); + + it("reports and resumes a fault-injected partial chunk update", async () => { + const collection = chunkCollection(); + const store = new FixedPayloadStore( + collection as unknown as Collection, + ); + const entries = Array.from({ length: 100 }, (_, index) => ({ + ...request(index), + dependencies: [ + { + handlerId: "observations", + state: "waiting" as const, + error: "x".repeat(1_500), + }, + ], + })); + const payload = await store.prepareRequests({ + identity, + entries, + inlineDocument: (value) => ({ + value, + padding: "x".repeat(256 * 1024), + }), + }); + expect(payload.storage).toBe("chunked"); + const projected = entries.map((entry) => ({ + ...entry, + dependencies: [{ handlerId: "observations", state: "ready" as const }], + })); + collection.failOnWrite(collection.writeCount() + 2); + + const failed = await store.casUpdateRequests({ + identity, + payload, + entries: projected, + }); + expect(failed).toMatchObject({ + status: "partial-failure", + message: "injected write failure", + }); + if (failed.status !== "partial-failure") { + throw new Error("expected partial failure"); + } + expect(failed.updatedChunkIds).toHaveLength(1); + + collection.failOnWrite(-1); + const repaired = await store.casUpdateRequests({ + identity, + payload, + entries: projected, + }); + expect(repaired.status).toBe("applied"); + if (repaired.status !== "applied") throw new Error("expected applied"); + expect(await store.readRequests(identity, repaired.payload)).toEqual( + projected, + ); + }); + + it("rejects frozen or ownership-mismatched buckets without success", async () => { + const collection = chunkCollection(); + const store = new FixedPayloadStore( + collection as unknown as Collection, + ); + const entries = [request(1)]; + const payload = await store.prepareRequests({ + identity, + entries, + inlineDocument: (value) => ({ + value, + padding: "x".repeat(256 * 1024), + }), + }); + if (payload.storage !== "chunked") throw new Error("expected chunked"); + const chunk = collection.documents.get(payload.chunkIds[0]!); + if (!chunk) throw new Error("missing chunk"); + chunk.frozenAt = new Date(); + + await expect( + store.casUpdateRequests({ + identity, + payload, + entries: [ + { + ...entries[0]!, + dependencies: [ + { handlerId: "observations", state: "ready" }, + ], + }, + ], + }), + ).resolves.toMatchObject({ status: "stale", updatedChunkIds: [] }); + + delete chunk.frozenAt; + chunk.ownerId = "other-execution"; + await expect( + store.casUpdateRequests({ + identity, + payload, + entries, + }), + ).resolves.toMatchObject({ + status: "invariant", + updatedChunkIds: [], + }); + }); + + it("rejects an update that exceeds the fixed entry budget", async () => { + const collection = chunkCollection(); + const store = new FixedPayloadStore( + collection as unknown as Collection, + ); + const payload = await store.prepareRequests({ + identity, + entries: [request(1)], + inlineDocument: (value) => ({ value }), + }); + + await expect( + store.casUpdateRequests({ + identity, + payload, + entries: [ + { + ...request(1), + dependencies: [ + { + handlerId: "observations", + state: "failed", + error: "x".repeat(4_096), + }, + ], + }, + ], + }), + ).resolves.toMatchObject({ + status: "invariant", + updatedChunkIds: [], + }); + }); }); diff --git a/packages/shared/src/experiments/fixed-payload-store.ts b/packages/shared/src/experiments/fixed-payload-store.ts index 9d7b91340..60097dd3f 100644 --- a/packages/shared/src/experiments/fixed-payload-store.ts +++ b/packages/shared/src/experiments/fixed-payload-store.ts @@ -3,11 +3,17 @@ import type { Collection, Document } from "mongodb"; import { z } from "zod"; -import { selectFixedPayloadLayout } from "./layout.js"; +import { + assertExperimentRequestEntryBudget, + bsonSize, + experimentPayloadBudgetBytes, + selectFixedPayloadLayout, +} from "./layout.js"; import { ExperimentRequestStateSchema, } from "./schemas.js"; import { + assignExperimentRequestBucket, computeExperimentChunkId, fingerprintExperimentPayload, } from "./routing.js"; @@ -30,8 +36,11 @@ interface ExperimentChunkDocument { storageProfileVersion: typeof EXPERIMENT_STORAGE_PROFILE_VERSION; assignmentVersion: typeof EXPERIMENT_REQUEST_BUCKET_ASSIGNMENT_VERSION; payloadFingerprint: string; + version: number; entries: Array<{ position: number; state: ExperimentRequestState }>; createdAt: Date; + updatedAt: Date; + frozenAt?: Date; } const ExperimentChunkDocumentSchema = z @@ -49,6 +58,7 @@ const ExperimentChunkDocumentSchema = z EXPERIMENT_REQUEST_BUCKET_ASSIGNMENT_VERSION, ), payloadFingerprint: z.string().min(1), + version: z.number().int().positive(), entries: z.array( z .object({ @@ -58,6 +68,8 @@ const ExperimentChunkDocumentSchema = z .strict(), ), createdAt: z.coerce.date(), + updatedAt: z.coerce.date(), + frozenAt: z.coerce.date().optional(), }) .strict(); @@ -84,6 +96,7 @@ function sameChunk( left.storageProfileVersion === right.storageProfileVersion && left.assignmentVersion === right.assignmentVersion && left.payloadFingerprint === right.payloadFingerprint && + left.version === right.version && fingerprintExperimentPayload(left.entries) === fingerprintExperimentPayload(right.entries) ); @@ -117,6 +130,7 @@ export class FixedPayloadStore { storage: "inline", entryCount: inlineEntries.length, payloadFingerprint, + payloadVersion: 1, entries: inlineEntries, }), chunkDocument: (chunkIndex, bucketCount, bucketEntries) => @@ -129,6 +143,7 @@ export class FixedPayloadStore { state, })), payloadFingerprint, + version: 1, createdAt: input.now ?? new Date(0), }), }); @@ -137,6 +152,7 @@ export class FixedPayloadStore { storage: "inline", entryCount: entries.length, payloadFingerprint, + payloadVersion: 1, entries, }; } @@ -152,6 +168,7 @@ export class FixedPayloadStore { state, })), payloadFingerprint, + version: 1, createdAt, }), ); @@ -167,6 +184,7 @@ export class FixedPayloadStore { storage: "chunked", entryCount: entries.length, payloadFingerprint, + payloadVersion: 1, assignmentVersion: EXPERIMENT_REQUEST_BUCKET_ASSIGNMENT_VERSION, bucketCount: layout.bucketCount, chunkIds: documents.map((document) => document._id), @@ -220,6 +238,208 @@ export class FixedPayloadStore { await this.readRequests(identity, payload); } + async casUpdateRequests(input: { + identity: FixedPayloadIdentity; + payload: FixedPayload; + entries: readonly ExperimentRequestState[]; + now?: Date; + }): Promise< + | { + status: "applied"; + payload: FixedPayload; + updatedChunkIds: string[]; + } + | { status: "stale"; updatedChunkIds: string[] } + | { status: "invariant"; message: string; updatedChunkIds: string[] } + | { + status: "partial-failure"; + message: string; + updatedChunkIds: string[]; + } + > { + let entries: ExperimentRequestState[]; + try { + entries = input.entries.map((entry) => { + const parsed = ExperimentRequestStateSchema.parse(entry); + assertExperimentRequestEntryBudget(parsed); + return parsed; + }); + if (entries.length !== input.payload.entryCount) { + return { + status: "invariant", + message: "Request-state update cannot change entry count", + updatedChunkIds: [], + }; + } + } catch (error) { + return { + status: "invariant", + message: error instanceof Error ? error.message : String(error), + updatedChunkIds: [], + }; + } + + const nextFingerprint = fingerprintExperimentPayload(entries); + const nextVersion = input.payload.payloadVersion + 1; + if (input.payload.storage === "inline") { + return { + status: "applied", + payload: { + ...input.payload, + payloadFingerprint: nextFingerprint, + payloadVersion: nextVersion, + entries, + }, + updatedChunkIds: [], + }; + } + const chunkedPayload = input.payload; + + const positionedBuckets = Array.from( + { length: chunkedPayload.bucketCount }, + () => + [] as Array<{ position: number; state: ExperimentRequestState }>, + ); + entries.forEach((state, position) => { + positionedBuckets[ + assignExperimentRequestBucket(state.requestId, chunkedPayload.bucketCount) + ]!.push({ position, state }); + }); + const expectedChunkIds = positionedBuckets.map((_entries, chunkIndex) => + computeExperimentChunkId({ + ...input.identity, + kind: "requests", + chunkIndex, + }), + ); + if ( + expectedChunkIds.length !== chunkedPayload.chunkIds.length || + expectedChunkIds.some( + (chunkId, index) => chunkId !== chunkedPayload.chunkIds[index], + ) + ) { + return { + status: "invariant", + message: "Chunk topology does not match the immutable ownership tuple", + updatedChunkIds: [], + }; + } + + const now = input.now ?? new Date(); + const desired = positionedBuckets.map((bucketEntries, chunkIndex) => + this.chunkDocument({ + identity: input.identity, + chunkIndex, + bucketCount: chunkedPayload.bucketCount, + entries: bucketEntries, + payloadFingerprint: nextFingerprint, + version: nextVersion, + createdAt: now, + }), + ); + const budget = experimentPayloadBudgetBytes(); + if ( + desired.some( + (document) => + bsonSize(document) > budget, + ) + ) { + return { + status: "invariant", + message: + "Projection update exceeds the existing fixed bucket BSON budget", + updatedChunkIds: [], + }; + } + + const updatedChunkIds: string[] = []; + for (const document of desired) { + try { + const result = await this.chunks.updateOne( + { + _id: document._id, + projectId: input.identity.projectId, + experimentId: input.identity.experimentId, + kind: "requests", + ownerId: input.identity.ownerId, + generation: input.identity.generation, + chunkIndex: document.chunkIndex, + bucketCount: chunkedPayload.bucketCount, + assignmentVersion: chunkedPayload.assignmentVersion, + payloadFingerprint: chunkedPayload.payloadFingerprint, + version: chunkedPayload.payloadVersion, + frozenAt: { $exists: false }, + } as Document, + { + $set: { + entries: document.entries, + payloadFingerprint: nextFingerprint, + version: nextVersion, + updatedAt: now, + }, + } as Document, + ); + if (result.modifiedCount === 1) { + updatedChunkIds.push(document._id); + continue; + } + const raw: unknown = await this.chunks.findOne({ + _id: document._id, + } as Document); + if (!raw) { + return { + status: updatedChunkIds.length > 0 ? "partial-failure" : "invariant", + message: `Missing experiment chunk ${document._id}`, + updatedChunkIds, + }; + } + const actual = ExperimentChunkDocumentSchema.parse( + raw, + ) as ExperimentChunkDocument; + if ( + actual.version === nextVersion && + actual.payloadFingerprint === nextFingerprint && + sameChunk(actual, document) + ) { + updatedChunkIds.push(document._id); + continue; + } + try { + this.assertIdentity(actual, input.identity, chunkedPayload); + } catch (error) { + return { + status: updatedChunkIds.length > 0 ? "partial-failure" : "invariant", + message: error instanceof Error ? error.message : String(error), + updatedChunkIds, + }; + } + if (updatedChunkIds.length > 0) { + return { + status: "partial-failure", + message: `Chunk ${document._id} lost its CAS`, + updatedChunkIds, + }; + } + return { status: "stale", updatedChunkIds }; + } catch (error) { + return { + status: "partial-failure", + message: error instanceof Error ? error.message : String(error), + updatedChunkIds, + }; + } + } + return { + status: "applied", + payload: { + ...chunkedPayload, + payloadFingerprint: nextFingerprint, + payloadVersion: nextVersion, + }, + updatedChunkIds, + }; + } + async discardUnpublished( payload: FixedPayload, ): Promise { @@ -236,6 +456,7 @@ export class FixedPayloadStore { bucketCount: number; entries: Array<{ position: number; state: ExperimentRequestState }>; payloadFingerprint: string; + version: number; createdAt: Date; }): ExperimentChunkDocument { return { @@ -251,8 +472,10 @@ export class FixedPayloadStore { storageProfileVersion: EXPERIMENT_STORAGE_PROFILE_VERSION, assignmentVersion: EXPERIMENT_REQUEST_BUCKET_ASSIGNMENT_VERSION, payloadFingerprint: input.payloadFingerprint, + version: input.version, entries: input.entries, createdAt: input.createdAt, + updatedAt: input.createdAt, }; } @@ -297,7 +520,8 @@ export class FixedPayloadStore { document.generation !== identity.generation || document.bucketCount !== payload.bucketCount || document.assignmentVersion !== payload.assignmentVersion || - document.payloadFingerprint !== payload.payloadFingerprint + document.payloadFingerprint !== payload.payloadFingerprint || + document.version !== payload.payloadVersion ) { throw new Error(`Experiment chunk ${document._id} identity mismatch`); } diff --git a/packages/shared/src/experiments/layout.ts b/packages/shared/src/experiments/layout.ts index c2ce92b07..562694a3f 100644 --- a/packages/shared/src/experiments/layout.ts +++ b/packages/shared/src/experiments/layout.ts @@ -25,7 +25,7 @@ export function bsonSize(value: object): number { return BSON.calculateObjectSize(value); } -function payloadBudgetBytes(): number { +export function experimentPayloadBudgetBytes(): number { return Math.floor( (EXPERIMENT_STORAGE_PROFILE.targetDocumentBytes - EXPERIMENT_STORAGE_PROFILE.metadataReserveBytes) * @@ -33,6 +33,20 @@ function payloadBudgetBytes(): number { ); } +export function assertExperimentRequestEntryBudget( + entry: ExperimentRequestState, +): void { + const bytes = bsonSize({ + position: Number.MAX_SAFE_INTEGER, + state: entry, + }); + if (bytes > EXPERIMENT_STORAGE_PROFILE.maxRequestEntryBytes) { + throw new Error( + `Experiment request ${entry.requestId} is ${bytes} bytes; maximum is ${EXPERIMENT_STORAGE_PROFILE.maxRequestEntryBytes}`, + ); + } +} + export function selectFixedPayloadLayout(input: { entries: readonly ExperimentRequestState[]; inlineDocument: (entries: ExperimentRequestState[]) => object; @@ -49,15 +63,7 @@ export function selectFixedPayloadLayout(input: { throw new Error(`Duplicate experiment requestId '${entry.requestId}'`); } ids.add(entry.requestId); - const bytes = bsonSize({ - position: Number.MAX_SAFE_INTEGER, - state: entry, - }); - if (bytes > EXPERIMENT_STORAGE_PROFILE.maxRequestEntryBytes) { - throw new Error( - `Experiment request ${entry.requestId} is ${bytes} bytes; maximum is ${EXPERIMENT_STORAGE_PROFILE.maxRequestEntryBytes}`, - ); - } + assertExperimentRequestEntryBudget(entry); } const inlineBytes = bsonSize(input.inlineDocument(entries)); @@ -76,7 +82,7 @@ export function selectFixedPayloadLayout(input: { throw new Error("An empty fixed payload must be stored inline"); } - const budget = payloadBudgetBytes(); + const budget = experimentPayloadBudgetBytes(); const maxEntriesPerBucket = Math.max( 1, Math.floor( diff --git a/packages/shared/src/experiments/routing.ts b/packages/shared/src/experiments/routing.ts index bd9afd8fe..dc5cacbf9 100644 --- a/packages/shared/src/experiments/routing.ts +++ b/packages/shared/src/experiments/routing.ts @@ -2,6 +2,7 @@ // Licensed under the MIT License. import { createHash } from "node:crypto"; +import type { ExperimentRequestState } from "./types.js"; const REQUEST_BUCKET_HASH_PREFIX = "experiment-request-bucket:v1\0"; @@ -49,3 +50,11 @@ export function fingerprintExperimentPayload(value: unknown): string { .update(JSON.stringify(value), "utf8") .digest("base64url"); } + +export function fingerprintExperimentRequestVector( + requests: readonly Pick[], +): string { + return fingerprintExperimentPayload( + requests.map(({ requestId, runId }) => ({ requestId, runId })), + ); +} diff --git a/packages/shared/src/experiments/schemas.test.ts b/packages/shared/src/experiments/schemas.test.ts index 9a4b6fb2d..64b80727c 100644 --- a/packages/shared/src/experiments/schemas.test.ts +++ b/packages/shared/src/experiments/schemas.test.ts @@ -64,6 +64,7 @@ describe("experiment schemas", () => { storage: "inline", entryCount: 0, payloadFingerprint: "f", + payloadVersion: 1, entries: [], }, vectorFingerprint: "v", diff --git a/packages/shared/src/experiments/schemas.ts b/packages/shared/src/experiments/schemas.ts index 0022421f3..d3a96e088 100644 --- a/packages/shared/src/experiments/schemas.ts +++ b/packages/shared/src/experiments/schemas.ts @@ -83,6 +83,7 @@ export const ExperimentFixedRequestPayloadSchema = z.discriminatedUnion( storage: z.literal("inline"), entryCount: z.number().int().nonnegative(), payloadFingerprint: IdSchema, + payloadVersion: z.number().int().positive(), entries: z.array(ExperimentRequestStateSchema), }) .strict() @@ -94,6 +95,7 @@ export const ExperimentFixedRequestPayloadSchema = z.discriminatedUnion( storage: z.literal("chunked"), entryCount: z.number().int().positive(), payloadFingerprint: IdSchema, + payloadVersion: z.number().int().positive(), assignmentVersion: z.literal( EXPERIMENT_REQUEST_BUCKET_ASSIGNMENT_VERSION, ), @@ -130,6 +132,15 @@ const ExperimentExecutionBaseSchema = z supersededAt: z.coerce.date().optional(), supersededByExperimentExecutionId: IdSchema.optional(), supersededReason: z.enum(["rollover", "retry"]).optional(), + requestStateUpdate: z + .object({ + updateId: IdSchema, + expectedPayloadFingerprint: IdSchema, + nextPayloadFingerprint: IdSchema, + claimedAt: z.coerce.date(), + }) + .strict() + .optional(), }) .strict(); diff --git a/packages/shared/src/experiments/types.ts b/packages/shared/src/experiments/types.ts index 8d8595259..a3b64d2fa 100644 --- a/packages/shared/src/experiments/types.ts +++ b/packages/shared/src/experiments/types.ts @@ -12,6 +12,7 @@ export interface InlineFixedPayload { storage: "inline"; entryCount: number; payloadFingerprint: string; + payloadVersion: number; entries: T[]; } @@ -19,6 +20,7 @@ export interface ChunkedFixedPayload { storage: "chunked"; entryCount: number; payloadFingerprint: string; + payloadVersion: number; assignmentVersion: typeof EXPERIMENT_REQUEST_BUCKET_ASSIGNMENT_VERSION; bucketCount: number; chunkIds: string[]; @@ -101,6 +103,13 @@ export interface ExperimentRolloverClaim { claimedAt: Date; } +export interface ExperimentRequestStateUpdateClaim { + updateId: string; + expectedPayloadFingerprint: string; + nextPayloadFingerprint: string; + claimedAt: Date; +} + export interface ExperimentExecution { experimentExecutionId: string; attemptNumber: number; @@ -119,6 +128,7 @@ export interface ExperimentExecution { supersededAt?: Date; supersededByExperimentExecutionId?: string; supersededReason?: "rollover" | "retry"; + requestStateUpdate?: ExperimentRequestStateUpdateClaim; rollover?: ExperimentRolloverClaim; } @@ -150,3 +160,29 @@ export interface ExperimentPage { experiments: ExperimentDocument[]; nextCursor?: string; } + +export type ExperimentRequestStateUpdateResult = + | { + status: "applied"; + experiment: ExperimentDocument; + requests: ExperimentRequestState[]; + } + | { + status: "stale"; + reason: "experiment" | "execution" | "version" | "frozen"; + } + | { + status: "contention"; + activeUpdateId?: string; + } + | { + status: "invariant"; + message: string; + } + | { + status: "partial-failure"; + updateId: string; + updatedChunkIds: string[]; + message: string; + retryable: true; + }; From a55c388120a803aa0ceb191f1a9acca0ed6d79ff Mon Sep 17 00:00:00 2001 From: Cedric Vidal Date: Fri, 16 Oct 2026 00:10:23 -0700 Subject: [PATCH 050/210] feat: add Experiment clients and documentation Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 4e02b3c3-5ec3-44f8-b88d-642673088e41 --- .../__snapshots__/cli-commands.test.ts.snap | 74 +- apps/cli/src/bundle.integration.test.ts | 2 +- apps/cli/src/commands/experiment.test.ts | 198 ++++ apps/cli/src/commands/experiment.ts | 882 ++++++++++++++++++ apps/cli/src/commands/run.test.ts | 65 +- apps/cli/src/commands/run.ts | 50 +- apps/cli/src/commands/submission.ts | 204 ---- apps/cli/src/index.ts | 4 +- apps/portal/src/App.tsx | 7 +- .../ExperimentStatusCard.stories.tsx | 59 ++ .../components/ExperimentStatusCard.test.tsx | 52 ++ .../src/components/ExperimentStatusCard.tsx | 56 ++ apps/portal/src/components/Layout.tsx | 1 + .../SubmissionStatusCard.stories.tsx | 79 -- .../components/SubmissionStatusCard.test.tsx | 68 -- .../src/components/SubmissionStatusCard.tsx | 54 -- apps/portal/src/lib/api.ts | 195 +++- apps/portal/src/lib/experiments.ts | 321 +++++++ apps/portal/src/pages/ExperimentDetail.tsx | 316 +++++++ apps/portal/src/pages/ExperimentsList.tsx | 120 +++ apps/portal/src/pages/RunDetail.tsx | 8 +- apps/portal/src/pages/RunsList.tsx | 70 +- apps/portal/src/pages/SubmissionDetail.tsx | 162 ---- apps/portal/src/pages/SubmitRun.tsx | 194 +++- apps/portal/src/types.ts | 71 +- website/astro.config.mjs | 2 + .../docs/guides/creating-experiments.mdx | 161 ++++ .../docs/guides/migrating-to-experiments.mdx | 147 +++ .../docs/guides/submitting-requests-api.mdx | 15 +- .../docs/guides/submitting-requests-cli.md | 17 +- .../docs/guides/submitting-requests-portal.md | 14 + .../src/content/docs/reference/rest-api.md | 17 +- 32 files changed, 2907 insertions(+), 778 deletions(-) create mode 100644 apps/cli/src/commands/experiment.test.ts create mode 100644 apps/cli/src/commands/experiment.ts delete mode 100644 apps/cli/src/commands/submission.ts create mode 100644 apps/portal/src/components/ExperimentStatusCard.stories.tsx create mode 100644 apps/portal/src/components/ExperimentStatusCard.test.tsx create mode 100644 apps/portal/src/components/ExperimentStatusCard.tsx delete mode 100644 apps/portal/src/components/SubmissionStatusCard.stories.tsx delete mode 100644 apps/portal/src/components/SubmissionStatusCard.test.tsx delete mode 100644 apps/portal/src/components/SubmissionStatusCard.tsx create mode 100644 apps/portal/src/lib/experiments.ts create mode 100644 apps/portal/src/pages/ExperimentDetail.tsx create mode 100644 apps/portal/src/pages/ExperimentsList.tsx delete mode 100644 apps/portal/src/pages/SubmissionDetail.tsx create mode 100644 website/src/content/docs/guides/creating-experiments.mdx create mode 100644 website/src/content/docs/guides/migrating-to-experiments.mdx diff --git a/apps/cli/src/__snapshots__/cli-commands.test.ts.snap b/apps/cli/src/__snapshots__/cli-commands.test.ts.snap index f972e2107..907676b78 100644 --- a/apps/cli/src/__snapshots__/cli-commands.test.ts.snap +++ b/apps/cli/src/__snapshots__/cli-commands.test.ts.snap @@ -200,6 +200,76 @@ exports[`CLI command registration > full command tree matches snapshot 1`] = ` }, }, }, + "experiment": { + "subcommands": { + "create": { + "options": [ + "--agent-version", + "--agents-md", + "--codebase", + "--count", + "--criteria", + "--description", + "--empty", + "--extensions", + "--gates", + "--max-iterations", + "--mcp-servers", + "--message", + "--model", + "--name", + "--observations", + "--output", + "--persona", + "--preview", + "--profile", + "--profile-variations-file", + "--project", + "--reasoning-effort", + "--resource-param", + "--resources", + "--scenario", + "--skills", + "--tags", + "--traits", + "--url", + "--worker", + ], + }, + "executions": { + "options": [ + "--cursor", + "--limit", + "--output", + "--project", + "--url", + ], + }, + "get": { + "options": [ + "--output", + "--project", + "--url", + ], + }, + "list": { + "options": [ + "--cursor", + "--limit", + "--output", + "--project", + "--url", + ], + }, + "retry": { + "options": [ + "--execution", + "--project", + "--url", + ], + }, + }, + }, "extension": { "subcommands": { "delete": { @@ -764,11 +834,11 @@ exports[`CLI command registration > full command tree matches snapshot 1`] = ` "download-batch": { "options": [ "--dir", + "--experiment-id", "--extract", "--ids", "--output", "--project", - "--submission-id", "--url", ], }, @@ -785,6 +855,7 @@ exports[`CLI command registration > full command tree matches snapshot 1`] = ` "--created-after", "--created-before", "--criteria", + "--experiment-id", "--include-deleted", "--max-iterations", "--model", @@ -798,7 +869,6 @@ exports[`CLI command registration > full command tree matches snapshot 1`] = ` "--sort-by", "--sort-dir", "--status", - "--submission-id", "--task", "--turns", "--url", diff --git a/apps/cli/src/bundle.integration.test.ts b/apps/cli/src/bundle.integration.test.ts index 11d8e0714..c1ca6b791 100644 --- a/apps/cli/src/bundle.integration.test.ts +++ b/apps/cli/src/bundle.integration.test.ts @@ -26,7 +26,7 @@ const MOCK_RESPONSES: Record = { id: "req-test-001", workerType: "coder-acp-copilot", run: { status: "done", outcome: "succeeded" }, - submissionId: "sub-abc123", + experimentId: "experiment-abc123", }, ], pageInfo: { hasNextPage: false, hasPreviousPage: false }, diff --git a/apps/cli/src/commands/experiment.test.ts b/apps/cli/src/commands/experiment.test.ts new file mode 100644 index 000000000..e21981f91 --- /dev/null +++ b/apps/cli/src/commands/experiment.test.ts @@ -0,0 +1,198 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { Command } from "commander"; +import { registerExperimentCommands } from "./experiment.js"; + +interface CapturedRequest { + url: string; + method: string; + body: string; +} + +const experiment = { + experimentId: "experiment-1", + projectId: "project-1", + metadata: { name: "Experiment 1" }, + revision: { + experimentRevisionId: "revision-1", + revisionNumber: 1, + memberCount: 0, + }, + execution: { + experimentExecutionId: "execution-1", + attemptNumber: 1, + readiness: "ready", + requests: [], + handlerProgress: {}, + blocking: [], + createdAt: "2026-01-01T00:00:00.000Z", + }, + readiness: "ready", + blocking: [], + createdRequestIds: [], + createdAt: "2026-01-01T00:00:00.000Z", +}; + +function makeProgram(): Command { + const program = new Command(); + registerExperimentCommands(program); + return program; +} + +function mockFetchWith( + body: unknown, +): { requests: CapturedRequest[] } { + const requests: CapturedRequest[] = []; + vi.stubGlobal( + "fetch", + vi.fn(async (request: Request) => { + requests.push({ + url: request.url, + method: request.method, + body: await request.text(), + }); + return new Response(JSON.stringify(body), { + status: 200, + headers: { "Content-Type": "application/json" }, + }); + }), + ); + return { requests }; +} + +describe("experiment commands", () => { + beforeEach(() => { + vi.restoreAllMocks(); + process.exitCode = undefined; + }); + + afterEach(() => { + vi.restoreAllMocks(); + process.exitCode = undefined; + }); + + it("previews composition without calling the API or warning", async () => { + const fetchSpy = vi.fn(); + vi.stubGlobal("fetch", fetchSpy); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + + await makeProgram().parseAsync( + [ + "experiment", + "create", + "--name", + "Nightly", + "--message", + "Run tests", + "--count", + "2", + "--preview", + "--output", + "json", + "--project", + "project-1", + "--url", + "http://localhost:3100", + ], + { from: "user" }, + ); + + expect(fetchSpy).not.toHaveBeenCalled(); + expect(warn).not.toHaveBeenCalled(); + expect(log.mock.calls.flat().join("\n")).toContain('"expandedRunCount": 2'); + expect(log.mock.calls.flat().join("\n")).toContain('"count": 2'); + }); + + it("creates an explicitly empty project-scoped experiment", async () => { + const { requests } = mockFetchWith(experiment); + vi.spyOn(console, "log").mockImplementation(() => {}); + + await makeProgram().parseAsync( + [ + "experiment", + "create", + "--name", + "Empty", + "--empty", + "--project", + "project-1", + "--url", + "http://localhost:3100", + ], + { from: "user" }, + ); + + expect(requests).toHaveLength(1); + expect(requests[0]).toMatchObject({ + method: "POST", + body: JSON.stringify({ + metadata: { name: "Empty" }, + empty: true, + }), + }); + expect(requests[0]?.url).toBe( + "http://localhost:3100/api/v1/experiments?projectId=project-1", + ); + }); + + it("gets an exact project-scoped execution", async () => { + const { requests } = mockFetchWith(experiment.execution); + vi.spyOn(console, "log").mockImplementation(() => {}); + + await makeProgram().parseAsync( + [ + "experiment", + "executions", + "experiment-1", + "execution-1", + "--project", + "project-1", + "--url", + "http://localhost:3100", + ], + { from: "user" }, + ); + + expect(requests[0]?.url).toBe( + "http://localhost:3100/api/v1/experiments/experiment-1/executions/execution-1?projectId=project-1", + ); + }); + + it("retries with the current execution identifier", async () => { + const { requests } = mockFetchWith({ + ...experiment, + execution: { + ...experiment.execution, + experimentExecutionId: "execution-2", + attemptNumber: 2, + }, + }); + vi.spyOn(console, "log").mockImplementation(() => {}); + + await makeProgram().parseAsync( + [ + "experiment", + "retry", + "experiment-1", + "--execution", + "execution-1", + "--project", + "project-1", + "--url", + "http://localhost:3100", + ], + { from: "user" }, + ); + + expect(requests[0]).toMatchObject({ + method: "POST", + body: JSON.stringify({ experimentExecutionId: "execution-1" }), + }); + expect(requests[0]?.url).toBe( + "http://localhost:3100/api/v1/experiments/experiment-1/retry?projectId=project-1", + ); + }); +}); diff --git a/apps/cli/src/commands/experiment.ts b/apps/cli/src/commands/experiment.ts new file mode 100644 index 000000000..9fd62faaf --- /dev/null +++ b/apps/cli/src/commands/experiment.ts @@ -0,0 +1,882 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { Command } from "commander"; +import { stringify as stringifyYaml } from "yaml"; +import { resolveScenarioAndPersona } from "../config-loader.js"; +import { apiFetch } from "../utils/api-client.js"; +import { requireProjectId } from "../utils/config.js"; +import { formatData, isMachineReadable } from "../utils/formatters.js"; +import { parseGatesOption } from "../utils/gates.js"; +import { configureHelp } from "../utils/helpFormatter.js"; +import { buildResourceBindingSpecs, collectRepeatable } from "../utils/resources.js"; +import { + getDefaultApiUrl, + withOutputOption, + withProjectOption, +} from "../utils/shared.js"; +import { errorText, label, successText, value } from "../utils/style.js"; +import type { DisplayField, OutputFormat } from "../utils/types.js"; + +interface ExperimentMetadata { + name: string; + description?: string; + tags?: string[]; +} + +interface ExperimentExecution { + experimentExecutionId: string; + attemptNumber: number; + version?: number; + readiness?: string; + requestCount: number; + requests: ExperimentRequestSummary[]; + handlerProgress: JsonRecord; + blocking: ExperimentBlocker[]; + currentReport?: { + reportId?: string; + url?: string; + updatedAt?: string; + }; + createdAt: string; + updatedAt?: string; + startedAt?: string; + finishedAt?: string; + discardedAt?: string; + discardReason?: string; + supersededAt?: string; + supersededByExperimentExecutionId?: string; + supersededReason?: "rollover" | "retry"; + archivedAt?: string; +} + +interface ExperimentBlocker { + handlerId: string; + reason: string; + requestId?: string; + runId?: string; + error?: string; +} + +interface ExperimentRequestSummary { + requestId: string; + runId: string; + task?: string; + status?: string; + outcome?: string; + workerType?: string; + model?: string; + profileId?: string; +} + +interface ExperimentView { + experimentId: string; + projectId: string; + metadata: ExperimentMetadata; + revision: { + experimentRevisionId: string; + revisionNumber: number; + memberCount: number; + membershipFingerprint?: string; + definitionFingerprint?: string; + createdAt?: string; + }; + execution: ExperimentExecution; + readiness?: string; + blocking: ExperimentBlocker[]; + createdRequestIds: string[]; + createdAt: string; + updatedAt?: string; + finalizedAt?: string; +} + +interface ExperimentPage { + items: ExperimentView[]; + nextCursor?: string; +} + +interface ExperimentExecutionPage { + items: ExperimentExecution[]; + nextCursor?: string; +} + +type JsonRecord = Record; + +function asRecord(value: unknown, name: string): JsonRecord { + if (!value || typeof value !== "object" || Array.isArray(value)) { + throw new Error(`Invalid ${name} response from Scope`); + } + return value as JsonRecord; +} + +function stringField( + value: JsonRecord, + key: string, + name: string, + optional = false, +): string | undefined { + const field = value[key]; + if (field === undefined && optional) return undefined; + if (typeof field !== "string" || field.length === 0) { + throw new Error(`Invalid ${name}.${key} response from Scope`); + } + return field; +} + +function numberField(value: JsonRecord, key: string, name: string): number { + const field = value[key]; + if (typeof field !== "number" || !Number.isFinite(field)) { + throw new Error(`Invalid ${name}.${key} response from Scope`); + } + return field; +} + +function parseBlocker(value: unknown): ExperimentBlocker { + const blocker = asRecord(value, "experiment blocker"); + return { + handlerId: stringField(blocker, "handlerId", "experiment blocker")!, + reason: stringField(blocker, "reason", "experiment blocker")!, + requestId: stringField(blocker, "requestId", "experiment blocker", true), + runId: stringField(blocker, "runId", "experiment blocker", true), + error: stringField(blocker, "error", "experiment blocker", true), + }; +} + +function parseRequestSummary(value: unknown): ExperimentRequestSummary { + const request = asRecord(value, "experiment request"); + return { + requestId: stringField(request, "requestId", "experiment request")!, + runId: stringField(request, "runId", "experiment request")!, + task: stringField(request, "task", "experiment request", true), + status: stringField(request, "status", "experiment request", true), + outcome: stringField(request, "outcome", "experiment request", true), + workerType: stringField(request, "workerType", "experiment request", true), + model: stringField(request, "model", "experiment request", true), + profileId: stringField(request, "profileId", "experiment request", true), + }; +} + +function parseExecution(value: unknown): ExperimentExecution { + const execution = asRecord(value, "experiment execution"); + const requests = execution.requests; + const requestVector = Array.isArray(requests) + ? { requestCount: requests.length, requests: requests.map(parseRequestSummary) } + : (() => { + const payload = requests === undefined + ? {} + : asRecord(requests, "experiment requests"); + const entries = Array.isArray(payload.entries) + ? payload.entries.map(parseRequestSummary) + : []; + return { + requestCount: + typeof payload.entryCount === "number" + ? payload.entryCount + : entries.length, + requests: entries, + }; + })(); + const blocking = Array.isArray(execution.blocking) + ? execution.blocking.map(parseBlocker) + : []; + const progress = asRecord( + execution.handlerProgress ?? execution.handlerSummary ?? {}, + "experiment handler progress", + ); + const report = execution.currentReport === undefined + ? undefined + : asRecord(execution.currentReport, "experiment report"); + return { + experimentExecutionId: stringField( + execution, + "experimentExecutionId", + "experiment execution", + )!, + attemptNumber: numberField( + execution, + "attemptNumber", + "experiment execution", + ), + readiness: stringField( + execution, + "readiness", + "experiment execution", + true, + ), + version: + typeof execution.version === "number" ? execution.version : undefined, + requestCount: requestVector.requestCount, + requests: requestVector.requests, + handlerProgress: progress, + blocking, + currentReport: report + ? { + reportId: stringField(report, "reportId", "experiment report", true), + url: stringField(report, "url", "experiment report", true), + updatedAt: stringField(report, "updatedAt", "experiment report", true), + } + : undefined, + createdAt: stringField( + execution, + "createdAt", + "experiment execution", + )!, + updatedAt: stringField(execution, "updatedAt", "experiment execution", true), + startedAt: stringField(execution, "startedAt", "experiment execution", true), + finishedAt: stringField(execution, "finishedAt", "experiment execution", true), + discardedAt: stringField(execution, "discardedAt", "experiment execution", true), + discardReason: stringField(execution, "discardReason", "experiment execution", true), + supersededAt: stringField(execution, "supersededAt", "experiment execution", true), + supersededByExperimentExecutionId: stringField( + execution, + "supersededByExperimentExecutionId", + "experiment execution", + true, + ), + supersededReason: + execution.supersededReason === "rollover" || + execution.supersededReason === "retry" + ? execution.supersededReason + : undefined, + archivedAt: stringField(execution, "archivedAt", "experiment execution", true), + }; +} + +function parseExperiment(value: unknown): ExperimentView { + const experiment = asRecord(value, "experiment"); + const metadata = asRecord(experiment.metadata, "experiment metadata"); + const revision = asRecord(experiment.revision, "experiment revision"); + const execution = parseExecution( + experiment.execution ?? experiment.currentExecution, + ); + const blockingValue = experiment.blocking ?? execution.blocking; + const blocking = Array.isArray(blockingValue) + ? blockingValue.map(parseBlocker) + : []; + const createdRequestIds = Array.isArray(experiment.createdRequestIds) + ? experiment.createdRequestIds.map((id) => { + if (typeof id !== "string") { + throw new Error("Invalid experiment.createdRequestIds response from Scope"); + } + return id; + }) + : []; + const tags = Array.isArray(metadata.tags) + ? metadata.tags.map((tag) => { + if (typeof tag !== "string") { + throw new Error("Invalid experiment metadata tag response from Scope"); + } + return tag; + }) + : undefined; + + return { + experimentId: stringField(experiment, "experimentId", "experiment")!, + projectId: stringField(experiment, "projectId", "experiment")!, + metadata: { + name: stringField(metadata, "name", "experiment metadata")!, + description: stringField( + metadata, + "description", + "experiment metadata", + true, + ), + tags, + }, + revision: { + experimentRevisionId: stringField( + revision, + "experimentRevisionId", + "experiment revision", + )!, + revisionNumber: numberField( + revision, + "revisionNumber", + "experiment revision", + ), + memberCount: + typeof revision.memberCount === "number" + ? revision.memberCount + : execution.requestCount, + membershipFingerprint: stringField( + revision, + "membershipFingerprint", + "experiment revision", + true, + ), + definitionFingerprint: stringField( + revision, + "definitionFingerprint", + "experiment revision", + true, + ), + createdAt: stringField(revision, "createdAt", "experiment revision", true), + }, + execution, + readiness: + stringField(experiment, "readiness", "experiment", true) ?? + execution.readiness, + blocking, + createdRequestIds, + createdAt: stringField(experiment, "createdAt", "experiment")!, + updatedAt: stringField(experiment, "updatedAt", "experiment", true), + finalizedAt: stringField(experiment, "finalizedAt", "experiment", true), + }; +} + +function parsePage(value: unknown): ExperimentPage { + const page = asRecord(value, "experiment page"); + if (!Array.isArray(page.items)) { + throw new Error("Invalid experiment page items response from Scope"); + } + return { + items: page.items.map(parseExperiment), + nextCursor: stringField(page, "nextCursor", "experiment page", true), + }; +} + +function parseExecutionPage(value: unknown): ExperimentExecutionPage { + const page = asRecord(value, "experiment execution page"); + if (!Array.isArray(page.items)) { + throw new Error("Invalid experiment execution page items response from Scope"); + } + return { + items: page.items.map(parseExecution), + nextCursor: stringField( + page, + "nextCursor", + "experiment execution page", + true, + ), + }; +} + +async function json(response: Response): Promise { + return response.json() as Promise; +} + +async function throwApiError(response: Response): Promise { + const value = await json(response); + const body = asRecord(value, "error"); + throw new Error( + typeof body.error === "string" ? body.error : `HTTP ${response.status}`, + ); +} + +function resolveTextOrFile(input: string): string { + return input.startsWith("@") + ? readFileSync(resolve(input.slice(1)), "utf8") + : input; +} + +const fields: DisplayField[] = [ + { key: "experimentId", label: "Experiment" }, + { + key: "metadata", + label: "Name", + formatter: (row: JsonRecord) => + String((row.metadata as ExperimentMetadata | undefined)?.name ?? ""), + }, + { + key: "execution", + label: "Attempt", + formatter: (row: JsonRecord) => + String((row.execution as ExperimentExecution | undefined)?.attemptNumber ?? ""), + }, + { key: "readiness", label: "Readiness" }, + { + key: "revision", + label: "Runs", + formatter: (row: JsonRecord) => + String( + (row.revision as ExperimentView["revision"] | undefined)?.memberCount ?? 0, + ), + }, + { key: "createdAt", label: "Created" }, +]; + +function addRunConfigurationOptions(command: Command): Command { + return command + .option("-s, --scenario ", "Scenario YAML file") + .option("-p, --persona ", "Persona YAML file") + .option("-t, --traits ", "Traits YAML file") + .option("-m, --message ", "Task prompt") + .option("-w, --worker ", "Registered worker ID") + .option("-c, --criteria ", "Evaluation criteria") + .option("--max-iterations ", "Max judge iterations", Number.parseInt) + .option("--model ", "Coding-agent model") + .option("--reasoning-effort ", "Reasoning effort") + .option("--mcp-servers ", "MCP server slugs") + .option("--skills ", "Skill slugs") + .option("--codebase ", "Codebase revision reference") + .option("--resources ", "Resource binding specs") + .option( + "--resource-param :=", + "Resource parameter override (repeatable)", + collectRepeatable, + [], + ) + .option("--extensions ", "VS Code extension IDs") + .option("--agent-version ", "Agent version") + .option("--profile ", "Base profile ID or version ref") + .option( + "--profile-variations-file ", + "JSON file containing profile variation refs", + ) + .option( + "--agents-md ", + "AGENTS.md content; prefix a path with @", + ) + .option("--gates ", "Gate configuration JSON or file") + .option("--observations ", "Observation criterion IDs") + .option( + "--count ", + "Occurrences per configuration (1-10)", + (value: string) => Number.parseInt(value, 10), + ); +} + +function buildRequest(options: Record): { + worker?: string; + request: JsonRecord; + profileCount: number; + occurrences: number; +} { + let message = + typeof options.message === "string" ? options.message : undefined; + let criteria = Array.isArray(options.criteria) + ? options.criteria.filter((item): item is string => typeof item === "string") + : undefined; + let personaInstructions: string | undefined; + let persona: Record | undefined; + if (typeof options.scenario === "string") { + const resolved = resolveScenarioAndPersona( + options.scenario, + typeof options.persona === "string" ? options.persona : undefined, + typeof options.traits === "string" ? options.traits : undefined, + ); + message ??= resolved.task; + if (!criteria?.length) criteria = resolved.criteria; + personaInstructions = resolved.personaInstructions; + persona = resolved.persona; + } + if (!message?.trim()) { + throw new Error("--message or --scenario is required unless --empty is used"); + } + + const occurrences = + typeof options.count === "number" ? options.count : 1; + if (!Number.isInteger(occurrences) || occurrences < 1 || occurrences > 10) { + throw new Error("--count must be an integer between 1 and 10"); + } + + const request: JsonRecord = { + scenario: { task: message.trim(), criteria: criteria ?? [] }, + }; + const copyString = (source: string, target = source): void => { + if (typeof options[source] === "string" && options[source]) { + request[target] = options[source]; + } + }; + copyString("model"); + copyString("reasoningEffort"); + copyString("agentVersion"); + copyString("profile", "profileId"); + copyString("codebase"); + if (typeof options.maxIterations === "number") { + request.maxIterations = options.maxIterations; + } + if (personaInstructions) request.personaInstructions = personaInstructions; + if (persona) request.persona = persona; + if (occurrences > 1) request.count = occurrences; + for (const [source, target] of [ + ["mcpServers", "mcpServers"], + ["skills", "skills"], + ["extensions", "extensions"], + ["observations", "observations"], + ] as const) { + if (Array.isArray(options[source]) && options[source].length > 0) { + request[target] = options[source]; + } + } + const resources = buildResourceBindingSpecs( + Array.isArray(options.resources) + ? options.resources.filter( + (item): item is string => typeof item === "string", + ) + : undefined, + Array.isArray(options.resourceParam) + ? options.resourceParam.filter( + (item): item is string => typeof item === "string", + ) + : [], + ); + if (resources) request.resources = resources; + if (typeof options.agentsMd === "string") { + const content = resolveTextOrFile(options.agentsMd); + if (content.trim()) request.agentsMd = content; + } + if (typeof options.gates === "string") { + request.gates = parseGatesOption( + options.gates, + typeof options.maxIterations === "number" + ? options.maxIterations + : undefined, + ); + } + + let profileCount = typeof options.profile === "string" ? 1 : 0; + if (typeof options.profileVariationsFile === "string") { + if (typeof options.profile !== "string") { + throw new Error( + "--profile is required with --profile-variations-file", + ); + } + const parsed: unknown = JSON.parse( + readFileSync(resolve(options.profileVariationsFile), "utf8"), + ); + if (!Array.isArray(parsed) || !parsed.every((item) => typeof item === "string")) { + throw new Error("profile variations file must be a JSON string array"); + } + request.profileVariations = parsed; + profileCount += parsed.length; + } + if (profileCount === 0) profileCount = 1; + + return { + worker: typeof options.worker === "string" ? options.worker : undefined, + request, + profileCount, + occurrences, + }; +} + +export function registerExperimentCommands(program: Command): void { + const experiment = program + .command("experiment") + .description("Create and inspect benchmark experiments") + .action(() => experiment.help()); + configureHelp(experiment); + + const create = addRunConfigurationOptions( + withProjectOption( + withOutputOption( + experiment + .command("create") + .description("Create an experiment from a run configuration") + .requiredOption("--name ", "Experiment name") + .option("--description ", "Experiment description") + .option("--tags ", "Experiment tags") + .option("--empty", "Create an explicit empty experiment") + .option( + "--preview", + "Print the composition and request body without creating", + ) + .option("-u, --url ", "API base URL", getDefaultApiUrl()), + ), + ), + ); + + create.action(async (options) => { + try { + const projectId = requireProjectId(options.project); + const metadata: ExperimentMetadata = { + name: options.name, + ...(options.description ? { description: options.description } : {}), + ...(options.tags?.length ? { tags: options.tags } : {}), + }; + if (options.empty) { + const conflicting = [ + "scenario", + "message", + "worker", + "criteria", + "profile", + "profileVariationsFile", + "count", + ].filter((key) => options[key] !== undefined); + if (conflicting.length > 0) { + throw new Error( + `--empty cannot be combined with run configuration options: ${conflicting.join(", ")}`, + ); + } + } + const built = options.empty ? undefined : buildRequest(options); + const body = options.empty + ? { metadata, empty: true } + : { metadata, request: built!.request }; + const expandedRunCount = built + ? built.profileCount * built.occurrences + : 0; + if (options.preview) { + const preview = { + expandedRunCount, + body, + }; + const format = (options.output ?? "json") as OutputFormat; + if (format === "json") { + console.log(JSON.stringify(preview, null, 2)); + return; + } + if (format === "yaml") { + console.log(stringifyYaml(preview).trimEnd()); + return; + } + console.log( + formatData( + [preview], + [ + { key: "expandedRunCount", label: "Runs" }, + { + key: "body", + label: "Create body", + formatter: () => JSON.stringify(body), + }, + ], + format, + ), + ); + return; + } + const workerQuery = built?.worker + ? `?worker=${encodeURIComponent(built.worker)}` + : ""; + const response = await apiFetch( + options.url, + `/experiments${workerQuery}`, + { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + projectId, + }, + ); + if (!response.ok) await throwApiError(response); + const created = parseExperiment(await json(response)); + const format = (options.output ?? "table") as OutputFormat; + if (isMachineReadable(format)) { + console.log(formatData([created], fields, format)); + return; + } + console.log( + `${successText("Experiment created:")} ${value(created.experimentId)}`, + ); + console.log(`${label("Name:")} ${value(created.metadata.name)}`); + console.log( + `${label("Runs:")} ${value(String(created.revision.memberCount))}`, + ); + console.log( + `${label("Execution:")} ${value(created.execution.experimentExecutionId)}`, + ); + } catch (error) { + console.error( + errorText("Error:"), + error instanceof Error ? error.message : error, + ); + process.exitCode = 1; + } + }); + + withProjectOption( + withOutputOption( + experiment + .command("list") + .description("List experiments") + .option("--cursor ", "Continue from a list cursor") + .option("--limit ", "Maximum items", Number.parseInt) + .option("-u, --url ", "API base URL", getDefaultApiUrl()), + ), + ).action(async (options) => { + try { + const projectId = requireProjectId(options.project); + const params = new URLSearchParams(); + if (options.cursor) params.set("cursor", options.cursor); + if (options.limit) params.set("limit", String(options.limit)); + const response = await apiFetch( + options.url, + `/experiments${params.size ? `?${params}` : ""}`, + { projectId }, + ); + if (!response.ok) await throwApiError(response); + const page = parsePage(await json(response)); + console.log( + formatData( + page.items, + fields, + (options.output ?? "table") as OutputFormat, + ), + ); + if (page.nextCursor && !isMachineReadable(options.output ?? "table")) { + console.log(`${label("Next cursor:")} ${value(page.nextCursor)}`); + } + } catch (error) { + console.error( + errorText("Error:"), + error instanceof Error ? error.message : error, + ); + process.exitCode = 1; + } + }); + + withProjectOption( + withOutputOption( + experiment + .command("get") + .description("Get an experiment and its current execution") + .argument("", "Experiment ID") + .option("-u, --url ", "API base URL", getDefaultApiUrl()), + ), + ).action(async (id: string, options) => { + try { + const projectId = requireProjectId(options.project); + const response = await apiFetch( + options.url, + `/experiments/${encodeURIComponent(id)}`, + { projectId }, + ); + if (!response.ok) await throwApiError(response); + const item = parseExperiment(await json(response)); + const format = (options.output ?? "table") as OutputFormat; + if (isMachineReadable(format)) { + console.log(formatData([item], fields, format)); + return; + } + console.log(`${label("Experiment:")} ${value(item.experimentId)}`); + console.log(`${label("Name:")} ${value(item.metadata.name)}`); + console.log( + `${label("Execution:")} ${value(item.execution.experimentExecutionId)}`, + ); + console.log( + `${label("Attempt:")} ${value(String(item.execution.attemptNumber))}`, + ); + console.log( + `${label("Readiness:")} ${value(item.readiness ?? "unknown")}`, + ); + console.log( + `${label("Runs:")} ${value(String(item.revision.memberCount))}`, + ); + } catch (error) { + console.error( + errorText("Error:"), + error instanceof Error ? error.message : error, + ); + process.exitCode = 1; + } + }); + + withProjectOption( + withOutputOption( + experiment + .command("executions") + .description("List current and historical experiment executions") + .argument("", "Experiment ID") + .argument("[executionId]", "Get one exact execution") + .option("--cursor ", "Continue from a list cursor") + .option("--limit ", "Maximum items", Number.parseInt) + .option("-u, --url ", "API base URL", getDefaultApiUrl()), + ), + ).action(async (id: string, executionId: string | undefined, options) => { + try { + const projectId = requireProjectId(options.project); + if (executionId) { + const response = await apiFetch( + options.url, + `/experiments/${encodeURIComponent(id)}/executions/${encodeURIComponent(executionId)}`, + { projectId }, + ); + if (!response.ok) await throwApiError(response); + const item = parseExecution(await json(response)); + console.log( + formatData( + [item], + [ + { key: "experimentExecutionId", label: "Execution" }, + { key: "attemptNumber", label: "Attempt" }, + { key: "readiness", label: "Readiness" }, + { key: "requestCount", label: "Runs" }, + { key: "supersededReason", label: "Superseded" }, + { key: "createdAt", label: "Created" }, + ], + (options.output ?? "table") as OutputFormat, + ), + ); + return; + } + const params = new URLSearchParams(); + if (options.cursor) params.set("cursor", options.cursor); + if (options.limit) params.set("limit", String(options.limit)); + const response = await apiFetch( + options.url, + `/experiments/${encodeURIComponent(id)}/executions${ + params.size ? `?${params}` : "" + }`, + { projectId }, + ); + if (!response.ok) await throwApiError(response); + const page = parseExecutionPage(await json(response)); + console.log( + formatData( + page.items, + [ + { key: "experimentExecutionId", label: "Execution" }, + { key: "attemptNumber", label: "Attempt" }, + { key: "readiness", label: "Readiness" }, + { key: "requestCount", label: "Runs" }, + { key: "supersededReason", label: "Superseded" }, + { key: "createdAt", label: "Created" }, + ], + (options.output ?? "table") as OutputFormat, + ), + ); + } catch (error) { + console.error( + errorText("Error:"), + error instanceof Error ? error.message : error, + ); + process.exitCode = 1; + } + }); + + withProjectOption( + experiment + .command("retry") + .description("Retry the current experiment execution") + .argument("", "Experiment ID") + .requiredOption( + "--execution ", + "Current experiment execution ID", + ) + .option("-u, --url ", "API base URL", getDefaultApiUrl()), + ).action(async (id: string, options) => { + try { + const projectId = requireProjectId(options.project); + const response = await apiFetch( + options.url, + `/experiments/${encodeURIComponent(id)}/retry`, + { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + experimentExecutionId: options.execution, + }), + projectId, + }, + ); + if (!response.ok) await throwApiError(response); + const item = parseExperiment(await json(response)); + console.log( + successText( + `Experiment retry started: attempt ${item.execution.attemptNumber} (${item.execution.experimentExecutionId})`, + ), + ); + } catch (error) { + console.error( + errorText("Error:"), + error instanceof Error ? error.message : error, + ); + process.exitCode = 1; + } + }); +} diff --git a/apps/cli/src/commands/run.test.ts b/apps/cli/src/commands/run.test.ts index b26334bab..bc40eb363 100644 --- a/apps/cli/src/commands/run.test.ts +++ b/apps/cli/src/commands/run.test.ts @@ -75,7 +75,7 @@ describe("run list", () => { id: "req-paginated-1", workerType: "coder-acp-copilot", run: { status: "done", outcome: "succeeded" }, - submissionId: "submission-12345678", + experimentId: "experiment-12345678", }, ], pageInfo: { @@ -99,7 +99,7 @@ describe("run list", () => { id: "req-array-1", workerType: "coder-acp-claude-code", run: { status: "running", outcome: "finished" }, - submissionId: "submission-abcdef12", + experimentId: "experiment-abcdef12", }, ]); @@ -117,7 +117,7 @@ describe("run list", () => { id: "req-json-1", workerType: "coder-acp-copilot", run: { status: "done", outcome: "succeeded" }, - submissionId: "submission-feedbeef", + experimentId: "experiment-feedbeef", }, ], pageInfo: { @@ -139,7 +139,7 @@ describe("run list", () => { id: "req-tsv-1", workerType: "coder-acp-copilot", run: { status: "done", outcome: "succeeded" }, - submissionId: "submission-11223344", + experimentId: "experiment-11223344", }, ], pageInfo: { @@ -149,7 +149,7 @@ describe("run list", () => { }); const output = await runListAndCaptureOutput(["-o", "tsv"]); - expect(output).toContain("req-tsv-1\tcoder-acp-copilot\tdone\tsubmissi"); + expect(output).toContain("req-tsv-1\tcoder-acp-copilot\tdone\texperime"); expect(output).not.toContain("Found 1 request(s):"); }); @@ -160,7 +160,7 @@ describe("run list", () => { id: "req-yaml-1", workerType: "coder-acp-copilot", run: { status: "done", outcome: "succeeded" }, - submissionId: "submission-a1b2c3d4", + experimentId: "experiment-a1b2c3d4", }, ], pageInfo: { @@ -236,6 +236,59 @@ describe("run submit", () => { const { body } = captureSubmit(); expect(body).not.toHaveProperty("agentsMd"); }); + + it("warns on deprecated multi-request composition", async () => { + mockFetchWith({ + ids: ["req-submit-3", "req-submit-4"], + count: 2, + status: "queued", + }); + vi.spyOn(console, "log").mockImplementation(() => {}); + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); + + await makeProgram().parseAsync( + [ + "run", "submit", + "-m", "repeat task", + "--worker", "dynamic-worker", + "--count", "2", + "--no-stream", + "-u", "http://localhost:3100", + "--project", "proj-test", + ], + { from: "user" }, + ); + + expect(warnSpy).toHaveBeenCalledOnce(); + expect(warnSpy.mock.calls.flat().join(" ")).toContain( + "legacy-request-composition", + ); + }); + + it("does not warn for an ordinary single request", async () => { + mockFetchWith({ + id: "req-submit-5", + workerType: "coder-acp-copilot", + status: "queued", + }); + vi.spyOn(console, "log").mockImplementation(() => {}); + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); + + await makeProgram().parseAsync( + [ + "run", "submit", + "-m", "single task", + "--worker", "dynamic-worker", + "--count", "1", + "--no-stream", + "-u", "http://localhost:3100", + "--project", "proj-test", + ], + { from: "user" }, + ); + + expect(warnSpy).not.toHaveBeenCalled(); + }); }); describe("run retry", () => { diff --git a/apps/cli/src/commands/run.ts b/apps/cli/src/commands/run.ts index ab2f7c15d..0c559a223 100644 --- a/apps/cli/src/commands/run.ts +++ b/apps/cli/src/commands/run.ts @@ -21,6 +21,9 @@ import { apiFetch, getApiBasePath } from "../utils/api-client.js"; import { parseGatesOption } from "../utils/gates.js"; import { buildResourceBindingSpecs, collectRepeatable } from "../utils/resources.js"; +const LEGACY_REQUEST_COMPOSITION_DEPRECATION = + "legacy-request-composition" as const; + /** * Resolve a CLI option that may be either a literal string or a `@path` * reference to a file whose contents should be read. Used for flags like @@ -213,6 +216,17 @@ run body.profileVariations = parsed; } + if ( + (typeof body.count === "number" && body.count > 1) || + (Array.isArray(body.profileVariations) && body.profileVariations.length > 0) + ) { + console.warn( + `${label("Deprecation:")} [${LEGACY_REQUEST_COMPOSITION_DEPRECATION}] ` + + "Use `scope experiment create` for composed benchmarks. " + + "`scope run submit` remains permanent for a single request.", + ); + } + // In variation mode the API derives the worker per-variation from each // profile's workerType, and explicitly rejects `?worker=`. Skip the // query param so the request isn't 400'd, and warn if --worker was @@ -250,13 +264,13 @@ run const result = await response.json(); // A variation submit creates one request per profile and returns - // { ids, variations, submissionId, ... } with no `id` or `workerType`. + // { ids, variations, experimentId, ... } with no `id` or `workerType`. // Printing it through the single-request path rendered `undefined` and - // then crashed in chalk, so the whole submission looked like it failed + // then crashed in chalk, so the whole request expansion looked like it failed // when in fact every request had been created. if (Array.isArray(result.ids) && result.ids.length > 0 && !result.id) { console.log(`${successText('Submitted:')} ${value(String(result.count ?? result.ids.length))} request(s) across ${value(String(result.variationCount ?? result.ids.length))} profile(s)`); - if (result.submissionId) console.log(`${label('Submission:')} ${value(result.submissionId)}`); + if (result.experimentId) console.log(`${label('Experiment:')} ${value(result.experimentId)}`); for (const variation of (result.variations ?? [])) { const ids: string[] = variation.ids ?? (variation.id ? [variation.id] : []); const name = variation.label ?? variation.profileName ?? variation.profileId ?? 'variation'; @@ -266,13 +280,13 @@ run for (const warning of (Array.isArray(result.warnings) ? result.warnings : [])) { console.log(`${errorText('⚠ Warning:')} ${warning}`); } - // Streaming follows a single request; a submission has several. + // Streaming follows a single request; an expanded composition has several. printFollowUpCommands(result.ids[0]); return; } console.log(`${successText('Request submitted:')} ${value(result.id)}`); - if (result.submissionId) console.log(`${label('Submission:')} ${value(result.submissionId)}`); + if (result.experimentId) console.log(`${label('Experiment:')} ${value(result.experimentId)}`); console.log(`${label('Worker:')} ${value(result.workerType)}`); if (result.model) console.log(`${label('Model:')} ${value(result.model)}`); if (result.reasoningEffort) console.log(`${label('Reasoning Effort:')} ${value(result.reasoningEffort)}`); @@ -509,7 +523,7 @@ run .option("--search ", "Free-text search over id, task, model, and worker") .option("--created-after ", "Only runs created at/after this ISO-8601 datetime") .option("--created-before ", "Only runs created at/before this ISO-8601 datetime") - .option("--submission-id ", "Filter by submission ID") + .option("--experiment-id ", "Filter by experiment ID") .option("--turns ", "Filter by actual turns (e.g. '>=5', '<=10', '=3')") .option("--max-iterations ", "Filter by configured maxIterations (e.g. '>=5', '<=10', '=3')") .option("--sort-by ", "Sort field: created, updated, priority, worker, status, id, duration") @@ -550,8 +564,8 @@ run if (options.createdBefore) { params.set("createdBefore", options.createdBefore); } - if (options.submissionId) { - params.set("submissionId", options.submissionId); + if (options.experimentId) { + params.set("experimentId", options.experimentId); } const parseIterExpr = (raw: string, name: string): { op: "eq" | "gte" | "lte"; value: number } => { const m = /^(>=|<=|=)?\s*(\d+)$/.exec(String(raw).trim()); @@ -623,8 +637,8 @@ run return o === 'succeeded' ? successText(s) : o === 'failed' || o === 'finished' ? errorText(s) : value(s); }, }, - { key: 'submissionId', label: 'Submission', - formatter: (req: any) => req.submissionId ? req.submissionId.substring(0, 8) : '–', + { key: 'experimentId', label: 'Experiment', + formatter: (req: Record) => typeof req.experimentId === "string" ? req.experimentId.substring(0, 8) : '–', }, { key: 'createdAt', label: 'Created', formatter: (req: any) => formatDate(req.createdAt), @@ -792,24 +806,24 @@ run .command("download-batch") .description("Download multiple runs at once into a single batch archive") .option("-i, --ids ", "One or more run IDs") - .option("--submission-id ", "Download all runs for a submission") + .option("--experiment-id ", "Download all runs for an experiment") .option("-o, --output ", "Output file path (default: batch-.tar.gz)") .option("-e, --extract", "Extract the archive after downloading") .option("-d, --dir ", "Extraction directory (implies --extract)") .option("-u, --url ", "API base URL", getDefaultApiUrl()) - .option("--project ", "Project ID for scoped operations (required with --submission-id)") + .option("--project ", "Project ID for scoped operations (required with --experiment-id)") .action(async (options) => { const { url } = options; const shouldExtract = options.extract || !!options.dir; try { - // Resolve IDs: either from --ids or by querying --submission-id + // Resolve IDs: either from --ids or by querying --experiment-id let ids: string[] = options.ids || []; - if (options.submissionId) { - console.log(`${label('Fetching runs for submission')} ${value(options.submissionId)}...`); + if (options.experimentId) { + console.log(`${label('Fetching runs for experiment')} ${value(options.experimentId)}...`); const projectId = requireProjectId(options.project); - const listResp = await apiFetch(url, `/requests?submissionId=${encodeURIComponent(options.submissionId)}&limit=1000`, { projectId }); + const listResp = await apiFetch(url, `/requests?experimentId=${encodeURIComponent(options.experimentId)}&limit=1000`, { projectId }); if (!listResp.ok) { const error = await listResp.json(); console.error(errorText("Error fetching runs:"), error); @@ -818,7 +832,7 @@ run const listData = await listResp.json(); const runs = listData.data || listData; if (!Array.isArray(runs) || runs.length === 0) { - console.error(errorText("No runs found for this submission")); + console.error(errorText("No runs found for this experiment")); process.exit(1); } ids = runs.map((r: { _id: string }) => r._id); @@ -826,7 +840,7 @@ run } if (ids.length === 0) { - console.error(errorText("Error: provide --ids or --submission-id")); + console.error(errorText("Error: provide --ids or --experiment-id")); process.exit(1); } diff --git a/apps/cli/src/commands/submission.ts b/apps/cli/src/commands/submission.ts deleted file mode 100644 index 835e7f3ed..000000000 --- a/apps/cli/src/commands/submission.ts +++ /dev/null @@ -1,204 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { Command } from "commander"; -import { configureHelp } from "../utils/helpFormatter.js"; -import { formatData, isMachineReadable } from "../utils/formatters.js"; -import type { DisplayField, OutputFormat } from "../utils/types.js"; -import { - getDefaultApiUrl, - withOutputOption, - withProjectOption, -} from "../utils/shared.js"; -import { requireProjectId } from "../utils/config.js"; -import { apiFetch } from "../utils/api-client.js"; -import { errorText, label, successText, value } from "../utils/style.js"; - -interface SubmissionSummary { - submissionId: string; - submissionRunId: string; - attemptNumber: number; - readiness: string; - createdAt: string; - requestIds: string[]; - requests: Array<{ - requestId: string; - runId: string; - task: string; - status: string; - outcome?: string; - }>; - blocking: Array<{ - requestId: string; - runId: string; - reason: string; - }>; -} -async function responseJson(response: Response): Promise { - return response.json() as Promise; -} - -async function throwApiError(response: Response): Promise { - const body = await responseJson<{ error?: string }>(response); - throw new Error(body.error ?? `HTTP ${response.status}`); -} - -const fields: DisplayField[] = [ - { key: "submissionId", label: "Submission" }, - { key: "attemptNumber", label: "Attempt" }, - { key: "readiness", label: "Readiness" }, - { - key: "requestIds", - label: "Runs", - formatter: (row: Record) => - String((row.requestIds as string[] | undefined)?.length ?? 0), - }, - { key: "createdAt", label: "Created" }, -]; - -export function registerSubmissionCommands(program: Command): void { - const submission = program - .command("submission") - .description("Inspect and retry grouped run submissions") - .action(() => submission.help()); - configureHelp(submission); - - withProjectOption( - withOutputOption( - submission - .command("list") - .description("List submissions") - .option("-u, --url ", "API base URL", getDefaultApiUrl()), - ), - ).action(async (options) => { - try { - const projectId = requireProjectId(options.project); - const response = await apiFetch(options.url, "/submissions", { projectId }); - if (!response.ok) await throwApiError(response); - const body = await responseJson<{ submissions: SubmissionSummary[] }>(response); - console.log( - formatData(body.submissions, fields, (options.output ?? "table") as OutputFormat), - ); - } catch (error) { - console.error(errorText("Error:"), error instanceof Error ? error.message : error); - process.exitCode = 1; - } - }); - - withOutputOption( - submission - .command("get") - .description("Get a submission and its current request/run vector") - .argument("", "Submission ID") - .option("-u, --url ", "API base URL", getDefaultApiUrl()), - ).action(async (id: string, options) => { - try { - const response = await apiFetch( - options.url, - `/submissions/${encodeURIComponent(id)}`, - ); - if (!response.ok) await throwApiError(response); - const doc = await responseJson(response); - const format = (options.output ?? "table") as OutputFormat; - if (isMachineReadable(format)) { - console.log(formatData([doc], fields, format)); - return; - } - console.log(`${label("Submission:")} ${value(doc.submissionId)}`); - console.log(`${label("Attempt:")} ${value(String(doc.attemptNumber))}`); - console.log(`${label("Readiness:")} ${value(doc.readiness)}`); - console.log(`${label("Submission run:")} ${value(doc.submissionRunId)}`); - for (const request of doc.requests) { - console.log( - ` ${value(request.requestId)} ${request.status}` + - `${request.outcome ? `/${request.outcome}` : ""} run=${request.runId}`, - ); - } - for (const blocking of doc.blocking) { - console.log( - ` blocked ${blocking.requestId}/${blocking.runId}: ${blocking.reason}`, - ); - } - } catch (error) { - console.error(errorText("Error:"), error instanceof Error ? error.message : error); - process.exitCode = 1; - } - }); - - withOutputOption( - submission - .command("runs") - .description("List current and archived submission attempts") - .argument("", "Submission ID") - .option("-u, --url ", "API base URL", getDefaultApiUrl()), - ).action(async (id: string, options) => { - try { - const response = await apiFetch( - options.url, - `/submissions/${encodeURIComponent(id)}/runs`, - ); - if (!response.ok) await throwApiError(response); - const body = await responseJson<{ - runs: Array<{ - _id: string; - attemptNumber: number; - createdAt: string; - requests: unknown[]; - supersededReason?: string; - }>; - }>(response); - const runFields: DisplayField[] = [ - { key: "_id", label: "Submission Run" }, - { key: "attemptNumber", label: "Attempt" }, - { - key: "requests", - label: "Runs", - formatter: (row: Record) => - String((row.requests as unknown[] | undefined)?.length ?? 0), - }, - { key: "supersededReason", label: "Superseded" }, - { key: "createdAt", label: "Created" }, - ]; - console.log( - formatData(body.runs, runFields, (options.output ?? "table") as OutputFormat), - ); - } catch (error) { - console.error(errorText("Error:"), error instanceof Error ? error.message : error); - process.exitCode = 1; - } - }); - - submission - .command("retry") - .description("Retry the current submission processing attempt") - .argument("", "Submission ID") - .requiredOption("--submission-run ", "Current submission run ID") - .option("-u, --url ", "API base URL", getDefaultApiUrl()) - .action(async (id: string, options) => { - try { - const response = await apiFetch( - options.url, - `/submissions/${encodeURIComponent(id)}/retry`, - { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ submissionRunId: options.submissionRun }), - }, - ); - if (!response.ok) await throwApiError(response); - const result = await responseJson<{ - submissionRunId: string; - attemptNumber: number; - readiness: string; - }>(response); - console.log( - successText( - `Submission retry started: attempt ${result.attemptNumber} (${result.submissionRunId}, ${result.readiness})`, - ), - ); - } catch (error) { - console.error(errorText("Error:"), error instanceof Error ? error.message : error); - process.exitCode = 1; - } - }); -} diff --git a/apps/cli/src/index.ts b/apps/cli/src/index.ts index 6d59d10a6..a9278391a 100644 --- a/apps/cli/src/index.ts +++ b/apps/cli/src/index.ts @@ -25,7 +25,7 @@ import { registerTaskPromptCommands } from "./commands/task-prompt.js"; import { registerProfileCommands } from "./commands/profile.js"; import { registerProjectCommands } from "./commands/project.js"; import { registerSecretCommands } from "./commands/secret.js"; -import { registerSubmissionCommands } from "./commands/submission.js"; +import { registerExperimentCommands } from "./commands/experiment.js"; import { registerUpdateCommand } from "./commands/update.js"; import { checkForUpdates } from "./utils/update-check.js"; import { errorText } from "./utils/style.js"; @@ -71,7 +71,7 @@ configureHelp(program); registerSecretCommands(program); registerProjectCommands(program); registerRunCommands(program); -registerSubmissionCommands(program); +registerExperimentCommands(program); registerCriteriaCommands(program); registerPromptFeatureCommands(program); registerReportCommands(program); diff --git a/apps/portal/src/App.tsx b/apps/portal/src/App.tsx index 56e6a2d79..195a75400 100644 --- a/apps/portal/src/App.tsx +++ b/apps/portal/src/App.tsx @@ -6,7 +6,8 @@ import { Layout } from "@/components/Layout"; import { RunsList } from "@/pages/RunsList"; import { RunDetail } from "@/pages/RunDetail"; import { SubmitRun } from "@/pages/SubmitRun"; -import { SubmissionDetail } from "@/pages/SubmissionDetail"; +import { ExperimentDetail } from "@/pages/ExperimentDetail"; +import { ExperimentsList } from "@/pages/ExperimentsList"; import { CriteriaList } from "@/pages/CriteriaList"; import { CriterionDetail } from "@/pages/CriterionDetail"; import { CriterionPreviewPanel } from "@/pages/CriterionPreviewPanel"; @@ -86,7 +87,9 @@ export function App() {
} /> } /> - } /> + } /> + } /> + } /> }> } /> diff --git a/apps/portal/src/components/ExperimentStatusCard.stories.tsx b/apps/portal/src/components/ExperimentStatusCard.stories.tsx new file mode 100644 index 000000000..af93dd5c9 --- /dev/null +++ b/apps/portal/src/components/ExperimentStatusCard.stories.tsx @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import type { Meta, StoryObj } from "@storybook/react-vite"; +import type { ExperimentView } from "@/lib/experiments"; +import { ExperimentStatusCard } from "./ExperimentStatusCard"; + +const experiment: ExperimentView = { + experimentId: "experiment-123", + projectId: "project-123", + metadata: { name: "Profile comparison", tags: ["nightly"] }, + revision: { + experimentRevisionId: "revision-1", + revisionNumber: 1, + memberCount: 2, + }, + createdAt: "2026-10-15T00:00:00.000Z", + createdRequestIds: ["request-1", "request-2"], + readiness: "processing", + execution: { + experimentExecutionId: "execution-1", + attemptNumber: 2, + requestCount: 2, + createdAt: "2026-10-15T00:00:00.000Z", + requests: [], + handlerProgress: { + observations: { status: "done" }, + report: { status: "processing" }, + }, + blocking: [], + }, + blocking: [], +}; + +const meta = { + title: "Experiments/ExperimentStatusCard", + component: ExperimentStatusCard, + args: { experiment }, +} satisfies Meta; + +export default meta; +type Story = StoryObj; + +export const Processing: Story = {}; + +export const Blocked: Story = { + args: { + experiment: { + ...experiment, + readiness: "blocked", + blocking: [ + { + handlerId: "observations", + reason: "dependency-failed", + }, + ], + }, + }, +}; diff --git a/apps/portal/src/components/ExperimentStatusCard.test.tsx b/apps/portal/src/components/ExperimentStatusCard.test.tsx new file mode 100644 index 000000000..e01e90b3c --- /dev/null +++ b/apps/portal/src/components/ExperimentStatusCard.test.tsx @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +// @vitest-environment happy-dom +import { cleanup, render, screen } from "@testing-library/react"; +import { afterEach, describe, expect, it } from "vitest"; +import type { ExperimentView } from "@/lib/experiments"; +import { ExperimentStatusCard } from "./ExperimentStatusCard"; + +afterEach(cleanup); + +describe("ExperimentStatusCard", () => { + it("renders readiness and exact handler progress", () => { + const experiment: ExperimentView = { + experimentId: "experiment-1", + projectId: "project-1", + metadata: { name: "Compiler comparison" }, + revision: { + experimentRevisionId: "revision-1", + revisionNumber: 1, + memberCount: 2, + }, + createdAt: "2026-10-15T00:00:00.000Z", + createdRequestIds: ["request-1", "request-2"], + readiness: "blocked", + execution: { + experimentExecutionId: "execution-1", + attemptNumber: 3, + requestCount: 2, + createdAt: "2026-10-15T00:00:00.000Z", + requests: [], + handlerProgress: { + observations: { status: "done" }, + report: { status: "processing" }, + }, + blocking: [], + }, + blocking: [ + { + handlerId: "observations", + reason: "dependency-failed", + }, + ], + }; + + render(); + + expect(screen.getByText("blocked")).toBeDefined(); + expect(screen.getByText("3")).toBeDefined(); + expect(screen.getByText("1/2")).toBeDefined(); + }); +}); diff --git a/apps/portal/src/components/ExperimentStatusCard.tsx b/apps/portal/src/components/ExperimentStatusCard.tsx new file mode 100644 index 000000000..5128838cc --- /dev/null +++ b/apps/portal/src/components/ExperimentStatusCard.tsx @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { Badge } from "@/components/ui/badge"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import type { ExperimentView } from "@/lib/experiments"; + +export function ExperimentStatusCard({ + experiment, +}: { + experiment: ExperimentView; +}) { + const readiness = experiment.readiness ?? "unknown"; + const variant = + readiness === "failed" || readiness === "blocked" + ? "destructive" + : readiness === "processing" || readiness === "done" + ? "default" + : readiness === "ready" + ? "outline" + : "secondary"; + const handlers = Object.values(experiment.execution.handlerProgress); + const completedHandlers = handlers.filter( + (handler) => + handler && + typeof handler === "object" && + "status" in handler && + handler.status === "done", + ).length; + return ( + + + Processing + {readiness} + + +
+
Attempt
+
+ {experiment.execution.attemptNumber} +
+
+
+
Handlers complete
+
+ {completedHandlers}/{handlers.length} +
+
+
+
Blocking runs
+
{experiment.blocking.length}
+
+
+
+ ); +} diff --git a/apps/portal/src/components/Layout.tsx b/apps/portal/src/components/Layout.tsx index 2a08d36cd..c3eb9e9be 100644 --- a/apps/portal/src/components/Layout.tsx +++ b/apps/portal/src/components/Layout.tsx @@ -95,6 +95,7 @@ const navGroups: NavGroup[] = [ scoped: true, items: [ { to: "/runs", label: "Runs", icon: List }, + { to: "/experiments", label: "Experiments", icon: FlaskConical }, { to: "/statistics", label: "Statistics", icon: BarChart3 }, { to: "/reports", label: "Reports", icon: FileText }, { to: "/insights", label: "Insights", icon: Lightbulb }, diff --git a/apps/portal/src/components/SubmissionStatusCard.stories.tsx b/apps/portal/src/components/SubmissionStatusCard.stories.tsx deleted file mode 100644 index 0c465e7e9..000000000 --- a/apps/portal/src/components/SubmissionStatusCard.stories.tsx +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { Meta, StoryObj } from "@storybook/react-vite"; -import { SubmissionStatusCard } from "./SubmissionStatusCard"; -import type { Submission } from "@/types"; - -const submission: Submission = { - submissionId: "submission-123", - projectId: "project-123", - requestIds: ["request-1", "request-2"], - createdAt: new Date().toISOString(), - submissionRunId: "submission-run-1", - attemptNumber: 2, - readiness: "processing", - requests: [ - { - requestId: "request-1", - runId: "run-1", - task: "Implement the feature", - status: "done", - outcome: "succeeded", - workerType: "coder-acp-copilot", - }, - { - requestId: "request-2", - runId: "run-2", - task: "Implement the feature", - status: "done", - outcome: "failed", - workerType: "coder-acp-copilot", - }, - ], - dependencyProjection: [ - { - requestId: "request-1", - runId: "run-1", - handlerId: "pp-observations", - state: "ready", - }, - { - requestId: "request-2", - runId: "run-2", - handlerId: "pp-observations", - state: "ready", - }, - ], - blocking: [], - handlerProgress: { - "pp-readout": { status: "processing", version: 1 }, - }, -}; -const meta = { - title: "Submissions/SubmissionStatusCard", - component: SubmissionStatusCard, - args: { submission }, -} satisfies Meta; - -export default meta; -type Story = StoryObj; - -export const Processing: Story = {}; - -export const Blocked: Story = { - args: { - submission: { - ...submission, - readiness: "blocked", - blocking: [ - { - requestId: "request-2", - runId: "run-2", - handlerId: "pp-observations", - reason: "dependency-failed", - }, - ], - }, - }, -}; diff --git a/apps/portal/src/components/SubmissionStatusCard.test.tsx b/apps/portal/src/components/SubmissionStatusCard.test.tsx deleted file mode 100644 index b735e762e..000000000 --- a/apps/portal/src/components/SubmissionStatusCard.test.tsx +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -// @vitest-environment happy-dom -import { cleanup, render, screen } from "@testing-library/react"; -import { afterEach, describe, expect, it } from "vitest"; -import type { Submission } from "@/types"; -import { SubmissionStatusCard } from "./SubmissionStatusCard"; - -afterEach(cleanup); - -describe("SubmissionStatusCard", () => { - it("renders readiness and exact observation progress", () => { - const submission: Submission = { - submissionId: "submission-1", - projectId: "project-1", - requestIds: ["request-1", "request-2"], - createdAt: new Date().toISOString(), - submissionRunId: "submission-run-1", - attemptNumber: 3, - readiness: "blocked", - requests: [ - { - requestId: "request-1", - runId: "run-1", - task: "Task", - status: "done", - workerType: "worker", - }, - { - requestId: "request-2", - runId: "run-2", - task: "Task", - status: "done", - workerType: "worker", - }, - ], - dependencyProjection: [ - { - requestId: "request-1", - runId: "run-1", - handlerId: "pp-observations", - state: "ready", - }, - { - requestId: "request-2", - runId: "run-2", - handlerId: "pp-observations", - state: "failed", - }, - ], - blocking: [ - { - requestId: "request-2", - runId: "run-2", - handlerId: "pp-observations", - reason: "dependency-failed", - }, - ], - }; - - render(); - - expect(screen.getByText("blocked")).toBeDefined(); - expect(screen.getByText("3")).toBeDefined(); - expect(screen.getByText("1/2")).toBeDefined(); - }); -}); diff --git a/apps/portal/src/components/SubmissionStatusCard.tsx b/apps/portal/src/components/SubmissionStatusCard.tsx deleted file mode 100644 index f711bdd1c..000000000 --- a/apps/portal/src/components/SubmissionStatusCard.tsx +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { Badge } from "@/components/ui/badge"; -import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; -import type { Submission } from "@/types"; - -const readinessVariant: Record< - Submission["readiness"], - "default" | "secondary" | "destructive" | "outline" -> = { - waiting: "secondary", - ready: "outline", - blocked: "destructive", - processing: "default", - done: "default", - failed: "destructive", -}; - -export function SubmissionStatusCard({ - submission, -}: { - submission: Submission; -}) { - const ready = submission.dependencyProjection.filter( - (dependency) => dependency.state === "ready", - ).length; - return ( - - - Processing - - {submission.readiness} - - - -
-
Attempt
-
{submission.attemptNumber}
-
-
-
Observations ready
-
- {ready}/{submission.requests.length} -
-
-
-
Blocking runs
-
{submission.blocking.length}
-
-
-
- ); -} diff --git a/apps/portal/src/lib/api.ts b/apps/portal/src/lib/api.ts index 1258ac38e..8dc195932 100644 --- a/apps/portal/src/lib/api.ts +++ b/apps/portal/src/lib/api.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import type { Run, RunState, CriteriaDocument, CriteriaGraphData, GeneratePromptResponse, AnalysisResponse, PromptFeatureDocument, Report, BulkReportStatus, BulkReportSummary, ReportTemplate, ReportTrigger, ReportTemplateSystemPrompt, KeyDocument, KeyValidationResult, CreateKeyRequest, UpdateKeyRequest, CodingAgent, AgentVersion, McpServerDocument, CreateMcpServerRequest, UpdateMcpServerRequest, BulkResubmitOverrides, Insight, InsightWithReference, TaskPrompt, TaskPromptFeatureExtractionResult, Model, FeatureFlag, SkillDocument, SkillSearchResult, SkillDiscoveryResult, SkillRevisionDocument, CodebaseDocument, CodebaseRevisionDocument, CodebaseSourceType, ResourceDocument, ResourceRevisionDocument, ResourceBindingSpec, CreateResourceBody, CreateResourceRevisionBody, ExtensionDocument, ExtensionSearchResult, ExtensionVersionInfo, MdpResponse, AccountDocument, CreateAccountRequest, UpdateAccountRequest, ProfileWithVersion, ProfileVersionDocument, ProfileDocument, RunGroup, RunFacetsResponse, CursorPaginatedResponse, IterationOp, GateConfig, GateId, PromptType, RunSortField, RunSortDir, CriterionKind, TaxonomyElementId, CriterionSubject, Submission } from "@/types"; +import type { Run, RunState, CriteriaDocument, CriteriaGraphData, GeneratePromptResponse, AnalysisResponse, PromptFeatureDocument, Report, BulkReportStatus, BulkReportSummary, ReportTemplate, ReportTrigger, ReportTemplateSystemPrompt, KeyDocument, KeyValidationResult, CreateKeyRequest, UpdateKeyRequest, CodingAgent, AgentVersion, McpServerDocument, CreateMcpServerRequest, UpdateMcpServerRequest, BulkResubmitOverrides, Insight, InsightWithReference, TaskPrompt, TaskPromptFeatureExtractionResult, Model, FeatureFlag, SkillDocument, SkillSearchResult, SkillDiscoveryResult, SkillRevisionDocument, CodebaseDocument, CodebaseRevisionDocument, CodebaseSourceType, ResourceDocument, ResourceRevisionDocument, ResourceBindingSpec, CreateResourceBody, CreateResourceRevisionBody, ExtensionDocument, ExtensionSearchResult, ExtensionVersionInfo, MdpResponse, AccountDocument, CreateAccountRequest, UpdateAccountRequest, ProfileWithVersion, ProfileVersionDocument, ProfileDocument, RunGroup, RunFacetsResponse, CursorPaginatedResponse, IterationOp, GateConfig, GateId, PromptType, RunSortField, RunSortDir, CriterionKind, TaxonomyElementId, CriterionSubject } from "@/types"; import type { Project, CreateProjectRequest, UpdateProjectRequest } from "@/types"; import { qs } from "./url"; @@ -9,6 +9,17 @@ import { recordServerDate } from "./serverClock"; import { apiClient } from "./api-client"; import { getSelectedProjectId, ProjectRequiredError } from "./project-scope"; import { MAX_ARCHIVE_UPLOAD_LABEL } from "./codebaseUpload"; +import { + parseExperiment, + parseExperimentExecution, + parseExperimentExecutionPage, + parseExperimentPage, + type ExperimentExecutionPageView, + type ExperimentExecutionView, + type ExperimentMetadataView, + type ExperimentPageView, + type ExperimentView, +} from "./experiments"; const BASE = "/api/v1"; @@ -85,7 +96,7 @@ export interface RunFilterParams { profileId?: string | string[]; taskPromptId?: string; criteria?: string; - submissionId?: string; + experimentId?: string; search?: string; createdAfter?: string; createdBefore?: string; @@ -108,7 +119,7 @@ function runFilterQs(f: RunFilterParams): Record => @@ -178,8 +219,8 @@ export const api = { })}`, undefined, { scoped: true }); }, - /** List runs grouped by task/profile/submissionId, with cursor pagination and server-side filtering */ - listRunGroups: (opts: RunFilterParams & { groupBy: "task" | "submissionId" | "profile"; sortBy?: RunSortField; sortDir?: RunSortDir; limit?: number; after?: string; before?: string; last?: boolean }): Promise> => { + /** List runs grouped by task/profile/experimentId, with cursor pagination and server-side filtering */ + listRunGroups: (opts: RunFilterParams & { groupBy: "task" | "experimentId" | "profile"; sortBy?: RunSortField; sortDir?: RunSortDir; limit?: number; after?: string; before?: string; last?: boolean }): Promise> => { return request(`/requests${qs({ groupBy: opts.groupBy, ...runFilterQs(opts), @@ -209,29 +250,19 @@ export const api = { }, /** Submit a new run (or multiple runs if count > 1) */ - submitRun: (body: { - scenario: { task: string; criteria: string[]; version?: "v1" | "v2" }; - observations?: string[]; - worker?: string; - model?: string; - reasoningEffort?: string; - maxIterations?: number; - personaInstructions?: string; - persona?: { personality: string; experience: string; verbosity: string; type: string }; - count?: number; - mcpServers?: string[]; - skills?: string[]; - extensions?: string[]; - resources?: ResourceBindingSpec[]; - agentVersion?: string; - profileId?: string; - profileVariations?: string[]; - agentsMd?: string; - agentsMdParentIds?: string[]; - gates?: GateConfig[]; - codebase?: string; - codebaseRevisionId?: string; - }): Promise<(Run & { message: string; submissionId: string }) | { ids: string[]; count: number; message: string; submissionId: string }> => { + submitRun: (body: RunCreateInput): Promise< + (Run & { + message: string; + experimentId?: string; + submissionId?: string; + }) | { + ids: string[]; + count: number; + message: string; + experimentId?: string; + submissionId?: string; + } + > => { const { worker, ...payload } = body; const url = worker ? `/requests?worker=${encodeURIComponent(worker)}` : `/requests`; return request(url, { @@ -240,26 +271,98 @@ export const api = { }, { scoped: true }); }, - listSubmissions: (): Promise<{ submissions: Submission[] }> => - request("/submissions", undefined, { scoped: true }), - - getSubmission: (id: string): Promise => - request(`/submissions/${id}`), + createExperiment: async (body: { + metadata: ExperimentMetadataView; + request?: RunCreateInput; + empty?: boolean; + }): Promise => { + const worker = body.request?.worker; + const requestBody = body.request + ? { ...body.request, worker: undefined } + : undefined; + const path = worker + ? `/experiments?worker=${encodeURIComponent(worker)}` + : "/experiments"; + const value = await request( + path, + { + method: "POST", + body: JSON.stringify({ + metadata: body.metadata, + ...(requestBody ? { request: requestBody } : {}), + ...(body.empty ? { empty: true } : {}), + }), + }, + { scoped: true }, + ); + return parseExperiment(value); + }, + + listExperiments: async (opts?: { + cursor?: string; + limit?: number; + }): Promise => { + const value = await request( + `/experiments${qs({ + cursor: opts?.cursor, + limit: opts?.limit ? String(opts.limit) : undefined, + })}`, + undefined, + { scoped: true }, + ); + return parseExperimentPage(value); + }, + + getExperiment: async (id: string): Promise => { + const value = await request( + `/experiments/${encodeURIComponent(id)}`, + undefined, + { scoped: true }, + ); + return parseExperiment(value); + }, + + listExperimentExecutions: async ( + id: string, + opts?: { cursor?: string; limit?: number }, + ): Promise => { + const value = await request( + `/experiments/${encodeURIComponent(id)}/executions${qs({ + cursor: opts?.cursor, + limit: opts?.limit ? String(opts.limit) : undefined, + })}`, + undefined, + { scoped: true }, + ); + return parseExperimentExecutionPage(value); + }, + + getExperimentExecution: async ( + id: string, + experimentExecutionId: string, + ): Promise => { + const value = await request( + `/experiments/${encodeURIComponent(id)}/executions/${encodeURIComponent(experimentExecutionId)}`, + undefined, + { scoped: true }, + ); + return parseExperimentExecution(value); + }, - retrySubmission: ( + retryExperiment: async ( id: string, - submissionRunId: string, - ): Promise<{ - submissionId: string; - submissionRunId: string; - attemptNumber: number; - readiness: Submission["readiness"]; - blocking: Submission["blocking"]; - }> => - request(`/submissions/${id}/retry`, { - method: "POST", - body: JSON.stringify({ submissionRunId }), - }), + experimentExecutionId: string, + ): Promise => { + const value = await request( + `/experiments/${encodeURIComponent(id)}/retry`, + { + method: "POST", + body: JSON.stringify({ experimentExecutionId }), + }, + { scoped: true }, + ); + return parseExperiment(value); + }, /** Soft-delete a run */ deleteRun: (id: string): Promise<{ id: string; deleted: boolean }> => { diff --git a/apps/portal/src/lib/experiments.ts b/apps/portal/src/lib/experiments.ts new file mode 100644 index 000000000..9132075db --- /dev/null +++ b/apps/portal/src/lib/experiments.ts @@ -0,0 +1,321 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +export const LEGACY_REQUEST_COMPOSITION_DEPRECATION = + "legacy-request-composition" as const; + +export interface ExperimentMetadataView { + name: string; + description?: string; + tags?: string[]; + createdBy?: string; +} + +export interface ExperimentRevisionView { + experimentRevisionId: string; + revisionNumber: number; + memberCount: number; + membershipFingerprint?: string; + definitionFingerprint?: string; + createdAt?: string; +} + +export interface ExperimentBlockerView { + handlerId: string; + reason: string; + requestId?: string; + runId?: string; + error?: string; +} + +export interface ExperimentRequestSummaryView { + requestId: string; + runId: string; + task?: string; + status?: string; + outcome?: string; + workerType?: string; + model?: string; + profileId?: string; +} + +export interface ExperimentExecutionView { + experimentExecutionId: string; + attemptNumber: number; + version?: number; + readiness?: string; + requestCount: number; + requests: ExperimentRequestSummaryView[]; + handlerProgress: Record; + blocking: ExperimentBlockerView[]; + currentReport?: { reportId?: string; url?: string; updatedAt?: string }; + createdAt: string; + updatedAt?: string; + startedAt?: string; + finishedAt?: string; + discardedAt?: string; + discardReason?: string; + supersededAt?: string; + supersededByExperimentExecutionId?: string; + supersededReason?: "rollover" | "retry"; + archivedAt?: string; +} + +export interface ExperimentView { + experimentId: string; + projectId: string; + metadata: ExperimentMetadataView; + revision: ExperimentRevisionView; + execution: ExperimentExecutionView; + readiness?: string; + blocking: ExperimentBlockerView[]; + createdRequestIds: string[]; + createdAt: string; + updatedAt?: string; + finalizedAt?: string; +} + +export interface ExperimentPageView { + items: ExperimentView[]; + nextCursor?: string; +} + +export interface ExperimentExecutionPageView { + items: ExperimentExecutionView[]; + nextCursor?: string; +} + +function record(value: unknown, name: string): Record { + if (!value || typeof value !== "object" || Array.isArray(value)) { + throw new Error(`Invalid ${name} response from Scope`); + } + return value as Record; +} + +function requiredString( + value: Record, + key: string, + name: string, +): string { + const candidate = value[key]; + if (typeof candidate !== "string" || candidate.length === 0) { + throw new Error(`Invalid ${name}.${key} response from Scope`); + } + return candidate; +} + +function optionalString( + value: Record, + key: string, +): string | undefined { + const candidate = value[key]; + if (candidate === undefined || candidate === null) return undefined; + if (typeof candidate !== "string") { + throw new Error(`Invalid ${key} response from Scope`); + } + return candidate; +} + +function requiredNumber( + value: Record, + key: string, + name: string, +): number { + const candidate = value[key]; + if (typeof candidate !== "number" || !Number.isFinite(candidate)) { + throw new Error(`Invalid ${name}.${key} response from Scope`); + } + return candidate; +} + +function parseBlocker(value: unknown): ExperimentBlockerView { + const item = record(value, "experiment blocker"); + return { + handlerId: requiredString(item, "handlerId", "experiment blocker"), + reason: requiredString(item, "reason", "experiment blocker"), + requestId: optionalString(item, "requestId"), + runId: optionalString(item, "runId"), + error: optionalString(item, "error"), + }; +} + +function parseRequestSummary(value: unknown): ExperimentRequestSummaryView { + const item = record(value, "experiment request"); + return { + requestId: requiredString(item, "requestId", "experiment request"), + runId: requiredString(item, "runId", "experiment request"), + task: optionalString(item, "task"), + status: optionalString(item, "status"), + outcome: optionalString(item, "outcome"), + workerType: optionalString(item, "workerType"), + model: optionalString(item, "model"), + profileId: optionalString(item, "profileId"), + }; +} + +function parseRequestVector( + value: unknown, +): { requestCount: number; requests: ExperimentRequestSummaryView[] } { + if (Array.isArray(value)) { + const requests = value.map(parseRequestSummary); + return { requestCount: requests.length, requests }; + } + const payload = record(value, "experiment request vector"); + const entries = Array.isArray(payload.entries) + ? payload.entries.map(parseRequestSummary) + : []; + const entryCount = + typeof payload.entryCount === "number" ? payload.entryCount : entries.length; + return { requestCount: entryCount, requests: entries }; +} + +export function parseExperimentExecution( + value: unknown, +): ExperimentExecutionView { + const execution = record(value, "experiment execution"); + const vector = parseRequestVector(execution.requests ?? []); + const blocking = Array.isArray(execution.blocking) + ? execution.blocking.map(parseBlocker) + : []; + const progressValue = execution.handlerProgress ?? execution.handlerSummary ?? {}; + const handlerProgress = record(progressValue, "experiment handler progress"); + const reportValue = execution.currentReport; + const currentReport = + reportValue === undefined + ? undefined + : (() => { + const report = record(reportValue, "experiment report"); + return { + reportId: optionalString(report, "reportId"), + url: optionalString(report, "url"), + updatedAt: optionalString(report, "updatedAt"), + }; + })(); + + return { + experimentExecutionId: requiredString( + execution, + "experimentExecutionId", + "experiment execution", + ), + attemptNumber: requiredNumber( + execution, + "attemptNumber", + "experiment execution", + ), + version: + typeof execution.version === "number" ? execution.version : undefined, + readiness: optionalString(execution, "readiness"), + requestCount: vector.requestCount, + requests: vector.requests, + handlerProgress, + blocking, + currentReport, + createdAt: requiredString(execution, "createdAt", "experiment execution"), + updatedAt: optionalString(execution, "updatedAt"), + startedAt: optionalString(execution, "startedAt"), + finishedAt: optionalString(execution, "finishedAt"), + discardedAt: optionalString(execution, "discardedAt"), + discardReason: optionalString(execution, "discardReason"), + supersededAt: optionalString(execution, "supersededAt"), + supersededByExperimentExecutionId: optionalString( + execution, + "supersededByExperimentExecutionId", + ), + supersededReason: + execution.supersededReason === "rollover" || + execution.supersededReason === "retry" + ? execution.supersededReason + : undefined, + archivedAt: optionalString(execution, "archivedAt"), + }; +} + +export function parseExperiment(value: unknown): ExperimentView { + const experiment = record(value, "experiment"); + const metadata = record(experiment.metadata, "experiment metadata"); + const revision = record(experiment.revision, "experiment revision"); + const executionValue = experiment.execution ?? experiment.currentExecution; + const execution = parseExperimentExecution(executionValue); + const blockingValue = experiment.blocking ?? execution.blocking; + const blocking = Array.isArray(blockingValue) + ? blockingValue.map(parseBlocker) + : []; + const createdRequestIds = Array.isArray(experiment.createdRequestIds) + ? experiment.createdRequestIds.map((id) => { + if (typeof id !== "string") { + throw new Error("Invalid experiment.createdRequestIds response from Scope"); + } + return id; + }) + : []; + + return { + experimentId: requiredString(experiment, "experimentId", "experiment"), + projectId: requiredString(experiment, "projectId", "experiment"), + metadata: { + name: requiredString(metadata, "name", "experiment metadata"), + description: optionalString(metadata, "description"), + tags: Array.isArray(metadata.tags) + ? metadata.tags.map((tag) => { + if (typeof tag !== "string") { + throw new Error("Invalid experiment metadata tag response from Scope"); + } + return tag; + }) + : undefined, + createdBy: optionalString(metadata, "createdBy"), + }, + revision: { + experimentRevisionId: requiredString( + revision, + "experimentRevisionId", + "experiment revision", + ), + revisionNumber: requiredNumber( + revision, + "revisionNumber", + "experiment revision", + ), + memberCount: + typeof revision.memberCount === "number" + ? revision.memberCount + : execution.requestCount, + membershipFingerprint: optionalString(revision, "membershipFingerprint"), + definitionFingerprint: optionalString(revision, "definitionFingerprint"), + createdAt: optionalString(revision, "createdAt"), + }, + execution, + readiness: + optionalString(experiment, "readiness") ?? execution.readiness, + blocking, + createdRequestIds, + createdAt: requiredString(experiment, "createdAt", "experiment"), + updatedAt: optionalString(experiment, "updatedAt"), + finalizedAt: optionalString(experiment, "finalizedAt"), + }; +} + +export function parseExperimentPage(value: unknown): ExperimentPageView { + const page = record(value, "experiment page"); + if (!Array.isArray(page.items)) { + throw new Error("Invalid experiment page items response from Scope"); + } + return { + items: page.items.map(parseExperiment), + nextCursor: optionalString(page, "nextCursor"), + }; +} + +export function parseExperimentExecutionPage( + value: unknown, +): ExperimentExecutionPageView { + const page = record(value, "experiment execution page"); + if (!Array.isArray(page.items)) { + throw new Error("Invalid experiment execution page items response from Scope"); + } + return { + items: page.items.map(parseExperimentExecution), + nextCursor: optionalString(page, "nextCursor"), + }; +} diff --git a/apps/portal/src/pages/ExperimentDetail.tsx b/apps/portal/src/pages/ExperimentDetail.tsx new file mode 100644 index 000000000..857633ba3 --- /dev/null +++ b/apps/portal/src/pages/ExperimentDetail.tsx @@ -0,0 +1,316 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { useState } from "react"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { ArrowLeft, FileText, RotateCcw } from "lucide-react"; +import { Link, useParams } from "react-router-dom"; +import { toast } from "sonner"; +import { ExperimentStatusCard } from "@/components/ExperimentStatusCard"; +import { ShortId } from "@/components/ShortId"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { ApiError, api } from "@/lib/api"; +import type { ExperimentExecutionView } from "@/lib/experiments"; +import { formatDate } from "@/lib/utils"; + +function ExecutionSummary({ + execution, +}: { + execution: ExperimentExecutionView; +}) { + return ( + + + + Execution attempt {execution.attemptNumber} + + + +
+
Execution ID
+ +
+
+
Runs
+
{execution.requestCount}
+
+
+
Created
+
{formatDate(execution.createdAt)}
+
+
+
+ ); +} + +export function ExperimentDetail() { + const { id } = useParams<{ id: string }>(); + const queryClient = useQueryClient(); + const [selectedExecutionId, setSelectedExecutionId] = useState(); + const experimentQuery = useQuery({ + queryKey: ["experiment", id], + queryFn: () => api.getExperiment(id!), + enabled: Boolean(id), + refetchInterval: (query) => { + const readiness = query.state.data?.readiness; + return readiness === "done" || + readiness === "failed" || + readiness === "blocked" + ? false + : 5_000; + }, + }); + const executionsQuery = useQuery({ + queryKey: ["experiment-executions", id], + queryFn: () => api.listExperimentExecutions(id!, { limit: 50 }), + enabled: Boolean(id) && experimentQuery.isSuccess, + }); + const selectedExecutionQuery = useQuery({ + queryKey: ["experiment-execution", id, selectedExecutionId], + queryFn: () => api.getExperimentExecution(id!, selectedExecutionId!), + enabled: Boolean(id && selectedExecutionId), + }); + const retry = useMutation({ + mutationFn: () => + api.retryExperiment( + experimentQuery.data!.experimentId, + experimentQuery.data!.execution.experimentExecutionId, + ), + onSuccess: () => { + toast.success("Experiment processing restarted"); + void queryClient.invalidateQueries({ queryKey: ["experiment", id] }); + void queryClient.invalidateQueries({ + queryKey: ["experiment-executions", id], + }); + }, + onError: (error) => { + toast.error(error instanceof Error ? error.message : "Retry failed"); + }, + }); + + if (experimentQuery.isLoading) { + return ( +
+ Loading experiment… +
+ ); + } + if (experimentQuery.isError || !experimentQuery.data) { + const correlationOnly = + experimentQuery.error instanceof ApiError && + experimentQuery.error.status === 404; + return ( +
+ + + + + {correlationOnly + ? "Historical experiment correlation" + : "Experiment could not be loaded"} + + + + {correlationOnly ? ( + <> +

+ {id} is + attached to historical runs but has no canonical Experiment + document. +

+

+ This correlation is view-only. It cannot be retried or used to + trigger processing. +

+ + ) : ( +

+ {experimentQuery.error instanceof Error + ? experimentQuery.error.message + : "The experiment request failed."} +

+ )} +
+
+
+ ); + } + + const experiment = experimentQuery.data; + const canRetry = !["waiting", "processing"].includes( + experiment.readiness ?? "", + ); + + return ( +
+
+
+ +
+

+ {experiment.metadata.name} +

+ +
+

+ Created {formatDate(experiment.createdAt)} +

+
+ +
+ + {experiment.metadata.description && ( +

+ {experiment.metadata.description} +

+ )} + {experiment.metadata.tags && experiment.metadata.tags.length > 0 && ( +
+ {experiment.metadata.tags.map((tag) => ( + + {tag} + + ))} +
+ )} + + + + {experiment.blocking.length > 0 && ( + + + Blocking dependencies + + + {experiment.blocking.map((blocking, index) => ( +
+ {blocking.requestId && ( + + {blocking.requestId.slice(0, 8)} + + )} + {blocking.reason} + + {blocking.handlerId} + + {blocking.error && {blocking.error}} +
+ ))} +
+
+ )} + + + + Current runs + + + {experiment.execution.requests.length === 0 ? ( +

+ {experiment.execution.requestCount === 0 + ? "This experiment is empty." + : `${experiment.execution.requestCount} linked runs are stored outside the inline response.`} +

+ ) : ( + experiment.execution.requests.map((request) => ( + +
+
+ + + {request.task ?? request.requestId} + +
+
+ {request.requestId} · {request.runId} +
+
+
+ {request.status && ( + {request.status} + )} + {request.outcome && ( + {request.outcome} + )} +
+ + )) + )} +
+
+ + + + Execution history + + + {executionsQuery.isLoading && ( +

+ Loading execution history… +

+ )} + {executionsQuery.data?.items.map((execution) => ( + + ))} +
+
+ + {selectedExecutionQuery.isLoading && ( +

Loading execution…

+ )} + {selectedExecutionQuery.data && ( + + )} +
+ ); +} diff --git a/apps/portal/src/pages/ExperimentsList.tsx b/apps/portal/src/pages/ExperimentsList.tsx new file mode 100644 index 000000000..5df215565 --- /dev/null +++ b/apps/portal/src/pages/ExperimentsList.tsx @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { useState } from "react"; +import { useQuery } from "@tanstack/react-query"; +import { FlaskConical, Plus } from "lucide-react"; +import { Link } from "react-router-dom"; +import { ShortId } from "@/components/ShortId"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { + Card, + CardContent, + CardHeader, + CardTitle, +} from "@/components/ui/card"; +import { api } from "@/lib/api"; +import { formatDate } from "@/lib/utils"; + +export function ExperimentsList() { + const [cursor, setCursor] = useState(); + const experimentsQuery = useQuery({ + queryKey: ["experiments", cursor], + queryFn: () => api.listExperiments({ cursor, limit: 50 }), + }); + + return ( +
+
+
+

Experiments

+

+ Reproducible benchmark compositions and their processing history. +

+
+ +
+ + {experimentsQuery.isLoading && ( +

Loading experiments…

+ )} + {experimentsQuery.isError && ( +

+ {experimentsQuery.error instanceof Error + ? experimentsQuery.error.message + : "Experiments could not be loaded."} +

+ )} + {experimentsQuery.data?.items.length === 0 && ( + + + +
+

No experiments yet

+

+ Create one from a run configuration or start explicitly empty. +

+
+
+
+ )} +
+ {experimentsQuery.data?.items.map((experiment) => ( + + + +
+ + {experiment.metadata.name} + +
+ + Created {formatDate(experiment.createdAt)} +
+
+ + {experiment.readiness ?? "unknown"} + +
+ + {experiment.revision.memberCount} runs + Revision {experiment.revision.revisionNumber} + Attempt {experiment.execution.attemptNumber} + +
+ + ))} +
+ + {experimentsQuery.data?.nextCursor && ( +
+ +
+ )} +
+ ); +} diff --git a/apps/portal/src/pages/RunDetail.tsx b/apps/portal/src/pages/RunDetail.tsx index 9eaed350f..81d3429bb 100644 --- a/apps/portal/src/pages/RunDetail.tsx +++ b/apps/portal/src/pages/RunDetail.tsx @@ -905,15 +905,15 @@ export function RunDetail() { /> )} - {run.submissionId && ( + {run.experimentId && ( - {run.submissionId.slice(0, 8)} + {run.experimentId.slice(0, 8)} )} /> diff --git a/apps/portal/src/pages/RunsList.tsx b/apps/portal/src/pages/RunsList.tsx index c7257fc97..31007a293 100644 --- a/apps/portal/src/pages/RunsList.tsx +++ b/apps/portal/src/pages/RunsList.tsx @@ -56,7 +56,7 @@ import { isAgentAvailable, isAgentVersionAvailable, STATUS_LIST, OUTCOME_LIST } import type { Run, RunStatus, RunOutcome, IterationOp, BulkResubmitOverrides, RunSortField, RunFacetBucket } from "@/types"; import { buildRunWorkerFilterOptions } from "./run-worker-filter-options"; -const FILTER_KEYS = ["worker", "status", "outcome", "taskPromptId", "submissionId", "criteria", "model", "profile", "os", "priority", "version", "dateFrom", "dateTo", "groupBy", "turns", "turnsOp", "maxIter", "maxIterOp"] as const; +const FILTER_KEYS = ["worker", "status", "outcome", "taskPromptId", "experimentId", "criteria", "model", "profile", "os", "priority", "version", "dateFrom", "dateTo", "groupBy", "turns", "turnsOp", "maxIter", "maxIterOp"] as const; /** * Describes how to fetch a given (1-based) page from the cursor-paginated @@ -132,18 +132,18 @@ const GROUP_MEMBER_PAGE = 100; /** * Map a server group key (issue #1138 server-side grouping) to the extra * server-side filter that selects that group's member runs. `task` groups by - * `taskPromptId`, `profile` by `profileId`, `submissionId` by `submissionId` - * (the literal `no-submission`/`no-profile` keys mean "missing", expressed as + * `taskPromptId`, `profile` by `profileId`, `experimentId` by `experimentId` + * (the literal `no-experiment`/`no-profile` keys mean "missing", expressed as * the `__empty__` sentinel so the API matches rows lacking the field). */ function groupKeyExtraFilter( - groupBy: "task" | "submissionId" | "profile", + groupBy: "task" | "experimentId" | "profile", key: string, -): { taskPromptId?: string; submissionId?: string; profileId?: string[] } { +): { taskPromptId?: string; experimentId?: string; profileId?: string[] } { if (groupBy === "task") return { taskPromptId: key }; if (groupBy === "profile") return { profileId: [key === "no-profile" ? EMPTY_FILTER_VALUE : key] }; - return { submissionId: key === "no-submission" ? EMPTY_FILTER_VALUE : key }; + return { experimentId: key === "no-experiment" ? EMPTY_FILTER_VALUE : key }; } /** Compact inline badges with overflow (+N) dropdown for dense table cells. */ @@ -313,7 +313,7 @@ const COLUMN_OPTIONS: CustomizeColumnsOption[] = [ // growth-ecosystems/scope-project#127). { id: "status", label: "Status" }, { id: "outcome", label: "Outcome" }, - { id: "submission", label: "Submission" }, + { id: "experiment", label: "Experiment" }, { id: "task", label: "Task" }, { id: "criteria", label: "Criteria" }, { id: "worker", label: "Worker" }, @@ -339,18 +339,18 @@ const COLUMN_IDS = COLUMN_OPTIONS.map((o) => o.id); // Segmented toggle used in the list header for the Group By control. Kept // inline because it is only used here. -const GROUP_BY_OPTIONS: ReadonlyArray<{ value: "profile" | "task" | "submissionId"; label: string }> = [ +const GROUP_BY_OPTIONS: ReadonlyArray<{ value: "profile" | "task" | "experimentId"; label: string }> = [ { value: "profile", label: "Profile" }, { value: "task", label: "Task" }, - { value: "submissionId", label: "Submission" }, + { value: "experimentId", label: "Experiment" }, ]; function GroupByToggle({ value, onChange, }: { - value: "none" | "profile" | "task" | "submissionId"; - onChange: (next: "none" | "profile" | "task" | "submissionId") => void; + value: "none" | "profile" | "task" | "experimentId"; + onChange: (next: "none" | "profile" | "task" | "experimentId") => void; }) { return (