diff --git a/apps/server/scripts/migrate-dev-db.test.ts b/apps/server/scripts/migrate-dev-db.test.ts index 1bb442490c82..df01cacfba8a 100644 --- a/apps/server/scripts/migrate-dev-db.test.ts +++ b/apps/server/scripts/migrate-dev-db.test.ts @@ -292,6 +292,7 @@ it.layer(NodeServices.layer)("migrate-dev-db", (it) => { [1, "ProjectRuntime"], [2, "DevelopmentProfiles"], [3, "TaskHandoffState"], + [4, "RuntimeRouting"], ], ); assert.deepStrictEqual(state.audit, []); @@ -385,14 +386,14 @@ it.layer(NodeServices.layer)("migrate-dev-db", (it) => { }; }), ); - // Reconciled history keeps its original timestamps; Task/Handoff state is new work and - // runs as the third fork migration on top of it. + // Reconciled history keeps its original timestamps; newer fork work runs on top of it. assert.deepStrictEqual( state.fork.map((row) => [row.migration_id, row.name]), [ [1, "ProjectRuntime"], [2, "DevelopmentProfiles"], [3, "TaskHandoffState"], + [4, "RuntimeRouting"], ], ); assert.deepStrictEqual( diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 87dee9aaa2e3..505f4bb559b9 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -54,6 +54,8 @@ export const RPC_REQUIRED_SCOPES = { [PROJECT_RUNTIME_RPC_METHODS.readTask]: AuthOrchestrationReadScope, [PROJECT_RUNTIME_RPC_METHODS.listHandoffs]: AuthOrchestrationReadScope, [PROJECT_RUNTIME_RPC_METHODS.readHandoff]: AuthOrchestrationReadScope, + [PROJECT_RUNTIME_RPC_METHODS.readRouting]: AuthOrchestrationReadScope, + [PROJECT_RUNTIME_RPC_METHODS.resolveRoute]: AuthOrchestrationReadScope, [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: AuthOrchestrationOperateScope, [ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: AuthOrchestrationReadScope, diff --git a/apps/server/src/developmentProfiles/DevelopmentProfileService.test.ts b/apps/server/src/developmentProfiles/DevelopmentProfileService.test.ts index d091039d7a81..50c95dcec5cf 100644 --- a/apps/server/src/developmentProfiles/DevelopmentProfileService.test.ts +++ b/apps/server/src/developmentProfiles/DevelopmentProfileService.test.ts @@ -10,6 +10,7 @@ import { DevelopmentProfileProjectNotFoundError, EffectiveProjectInstructions, ProjectId, + ProviderInstanceId, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -507,3 +508,61 @@ it.effect( assert.deepEqual(yield* service.getAssignment(projectA), assignment); }).pipe(Effect.provide(layerTest)), ); + +it.effect("writes instructions and routing under one profile revision", () => + Effect.gen(function* () { + const service = yield* DevelopmentProfileService.DevelopmentProfileService; + const implementation = { + role: "implementation" as const, + candidates: [{ providerInstanceId: ProviderInstanceId.make("codex"), model: "gpt-6" }], + fallback: "inherit" as const, + }; + const created = yield* service.create( + { name: "Routing policy", instructions: "Use the main model" }, + actor, + ); + assert.deepEqual(created.routing, { roleRoutes: [] }); + + const updated = yield* service.update( + { + profileId: created.profileId, + name: "Routing policy", + instructions: "Use the routed model", + routing: { roleRoutes: [implementation] }, + expectedRevision: 1, + }, + actor, + ); + assert.equal(updated.revision, 2); + assert.deepEqual(updated.routing, { roleRoutes: [implementation] }); + + const stale = yield* service + .update( + { + profileId: created.profileId, + name: "Routing policy", + instructions: "Stale instructions", + routing: { roleRoutes: [] }, + expectedRevision: 1, + }, + actor, + ) + .pipe(Effect.flip); + assert.instanceOf(stale, DevelopmentProfileConflictError); + const afterStale = yield* service.read(created.profileId); + assert.equal(afterStale.instructions, "Use the routed model"); + assert.deepEqual(afterStale.routing, { roleRoutes: [implementation] }); + + const instructionsOnly = yield* service.update( + { + profileId: created.profileId, + name: "Routing policy", + instructions: "Only instructions changed", + expectedRevision: 2, + }, + actor, + ); + assert.equal(instructionsOnly.revision, 3); + assert.deepEqual(instructionsOnly.routing, { roleRoutes: [implementation] }); + }).pipe(Effect.provide(layerTest)), +); diff --git a/apps/server/src/developmentProfiles/DevelopmentProfileService.ts b/apps/server/src/developmentProfiles/DevelopmentProfileService.ts index ef3d9161ef5a..799e27a58811 100644 --- a/apps/server/src/developmentProfiles/DevelopmentProfileService.ts +++ b/apps/server/src/developmentProfiles/DevelopmentProfileService.ts @@ -17,6 +17,7 @@ import { ProjectDevelopmentProfileSetInput, ProjectId, ProjectRuntimeInstructions, + RuntimeProfileRoutingPolicy, TrimmedNonEmptyString, } from "@t3tools/contracts"; import * as Context from "effect/Context"; @@ -83,6 +84,7 @@ interface ProfileRow { readonly profile_id: string; readonly name: string; readonly instructions: string; + readonly routing_json: string | null; readonly revision: number; readonly created_at: string; readonly updated_at: string; @@ -115,16 +117,28 @@ const decodeAssignment = Schema.decodeUnknownEffect(ProjectDevelopmentProfile); const decodeProject = Schema.decodeUnknownEffect(DevelopmentProfileProject); const ProjectInstructionsJson = Schema.fromJsonString(ProjectRuntimeInstructions); const decodeProjectInstructions = Schema.decodeUnknownEffect(ProjectInstructionsJson); +const ProfileRoutingJson = Schema.fromJsonString(RuntimeProfileRoutingPolicy); +const decodeProfileRouting = Schema.decodeUnknownEffect(ProfileRoutingJson); +const encodeProfileRouting = Schema.encodeEffect(ProfileRoutingJson); -const toProfile = (row: ProfileRow) => ({ - profileId: DevelopmentProfileId.make(row.profile_id), - name: row.name, - instructions: row.instructions, - revision: row.revision, - createdAt: row.created_at, - updatedAt: row.updated_at, - createdBy: row.created_by, - updatedBy: row.updated_by, +const emptyProfileRouting = (): RuntimeProfileRoutingPolicy => ({ roleRoutes: [] }); + +const toProfile = Effect.fn("DevelopmentProfileService.toProfile")(function* (row: ProfileRow) { + const routing = + row.routing_json === null + ? emptyProfileRouting() + : yield* decodeProfileRouting(row.routing_json); + return { + profileId: DevelopmentProfileId.make(row.profile_id), + name: row.name, + instructions: row.instructions, + routing, + revision: row.revision, + createdAt: row.created_at, + updatedAt: row.updated_at, + createdBy: row.created_by, + updatedBy: row.updated_by, + }; }); const toAssignment = (row: AssignmentRow) => ({ @@ -185,10 +199,10 @@ const make = Effect.gen(function* () { profileId: DevelopmentProfileId, ) { const rows = yield* sql`SELECT - profile_id, name, instructions, revision, created_at, updated_at, created_by, updated_by + profile_id, name, instructions, routing_json, revision, created_at, updated_at, created_by, updated_by FROM development_profiles WHERE profile_id = ${profileId}`; if (rows[0] === undefined) return yield* new DevelopmentProfileNotFoundError({ profileId }); - return yield* decodeProfile(toProfile(rows[0])); + return yield* decodeProfile(yield* toProfile(rows[0])); }); const findAssignment = Effect.fn("DevelopmentProfileService.findAssignment")(function* ( @@ -220,9 +234,11 @@ const make = Effect.gen(function* () { )( function* () { const rows = yield* sql`SELECT - profile_id, name, instructions, revision, created_at, updated_at, created_by, updated_by + profile_id, name, instructions, routing_json, revision, created_at, updated_at, created_by, updated_by FROM development_profiles ORDER BY created_at, profile_id`; - return yield* Effect.forEach(rows, (row) => decodeProfile(toProfile(row))); + return yield* Effect.forEach(rows, (row) => + Effect.flatMap(toProfile(row), (profile) => decodeProfile(profile)), + ); }, sql.withTransaction, sqlErrors, @@ -250,15 +266,17 @@ const make = Effect.gen(function* () { profileId: DevelopmentProfileId.make(yield* newId), name: data.name, instructions: data.instructions, + routing: data.routing ?? emptyProfileRouting(), revision: 1, createdAt: timestamp, updatedAt: timestamp, createdBy: actor, updatedBy: actor, }); + const routingJson = yield* encodeProfileRouting(record.routing); yield* sql`INSERT INTO development_profiles - (profile_id, name, instructions, revision, created_at, updated_at, created_by, updated_by) - VALUES (${record.profileId}, ${record.name}, ${record.instructions}, ${record.revision}, ${record.createdAt}, ${record.updatedAt}, ${record.createdBy}, ${record.updatedBy})`; + (profile_id, name, instructions, routing_json, revision, created_at, updated_at, created_by, updated_by) + VALUES (${record.profileId}, ${record.name}, ${record.instructions}, ${routingJson}, ${record.revision}, ${record.createdAt}, ${record.updatedAt}, ${record.createdBy}, ${record.updatedBy})`; return record; }, sql.withTransaction, @@ -278,13 +296,15 @@ const make = Effect.gen(function* () { ...existing, name: data.name, instructions: data.instructions, + routing: data.routing ?? existing.routing, revision: existing.revision + 1, updatedAt, updatedBy: actor, }); + const routingJson = yield* encodeProfileRouting(record.routing); const changed = yield* sql`UPDATE development_profiles - SET name = ${record.name}, instructions = ${record.instructions}, revision = ${record.revision}, - updated_at = ${record.updatedAt}, updated_by = ${record.updatedBy} + SET name = ${record.name}, instructions = ${record.instructions}, routing_json = ${routingJson}, + revision = ${record.revision}, updated_at = ${record.updatedAt}, updated_by = ${record.updatedBy} WHERE profile_id = ${record.profileId} AND revision = ${existing.revision} RETURNING profile_id`; if (changed.length !== 1) { diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 54c971767108..40a466b3bb78 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -1,7 +1,6 @@ import { CommandId, type RunId, - isProviderAvailable, MessageId, type ModelSelection, NodeId, @@ -56,7 +55,6 @@ import { type ProviderInteractionMode, type ProviderInstanceId, type ProviderOptionDescriptor, - type ProviderOptionSelection, ProviderRequestKind, type RuntimeMode, type ScheduledTask, @@ -103,6 +101,11 @@ import { isSnoozed } from "../orchestration-v2/ThreadSettlementService.ts"; import { userFacingDispatchErrorMessage } from "../orchestration-v2/UserFacingErrors.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; +import { + providerConstraintMessages, + providerEligibilityIssues, + providerOptionSelectionProblems, +} from "../provider/providerEligibility.ts"; import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts"; import * as ServerSettings from "../serverSettings.ts"; import { @@ -362,68 +365,6 @@ function capabilityModelOption(descriptor: ProviderOptionDescriptor): Orchestrat }; } -function providerConstraints( - provider: ServerProvider | undefined, - supportsOrchestrationV2: boolean, -): ReadonlyArray { - const constraints: Array = []; - if (!supportsOrchestrationV2) { - constraints.push("No V2 provider adapter is registered."); - } - if (provider === undefined) return constraints; - if (!isProviderAvailable(provider)) { - constraints.push(provider.unavailableReason ?? "Provider driver is unavailable."); - } - if (!provider.enabled) { - constraints.push("Provider instance is disabled."); - // Disabled snapshots contain placeholders for installation, health, and auth. - return constraints; - } - if (!provider.installed) constraints.push("Provider executable is not installed."); - if (provider.status === "error" || provider.status === "disabled") { - constraints.push(provider.message ?? `Provider status is ${provider.status}.`); - } - if (provider.auth.status === "unauthenticated") { - constraints.push("Provider is not authenticated."); - } - return constraints; -} - -/** Skip checks without descriptors; reject duplicate IDs because consumers disagree on precedence. */ -function invalidOptionSelections( - selections: ReadonlyArray, - descriptors: ReadonlyArray | undefined, -): ReadonlyArray { - const problems: Array = []; - const seen = new Set(); - for (const selection of selections) { - if (seen.has(selection.id)) { - problems.push(`Option ${selection.id} was specified more than once.`); - continue; - } - seen.add(selection.id); - if (descriptors === undefined) continue; - const descriptor = descriptors.find((candidate) => candidate.id === selection.id); - if (descriptor === undefined) { - const known = descriptors.map((candidate) => candidate.id).join(", "); - problems.push(`Unknown option ${selection.id}; supported options: ${known || "none"}.`); - continue; - } - if (descriptor.type === "boolean" && typeof selection.value !== "boolean") { - problems.push(`Option ${selection.id} expects a boolean value.`); - continue; - } - if ( - descriptor.type === "select" && - !descriptor.options.some((choice) => choice.id === selection.value) - ) { - const choices = descriptor.options.map((choice) => choice.id).join(", "); - problems.push(`Option ${selection.id} must be one of: ${choices}.`); - } - } - return problems; -} - function taskStatusForRun( run: Pick | undefined, ): OrchestratorMcpDelegateTaskResult["status"] { @@ -1352,7 +1293,8 @@ const make = Effect.gen(function* () { ); } const healthyCandidates = candidates.filter( - (candidate) => providerConstraints(candidate, true).length === 0, + (candidate) => + providerConstraintMessages(providerEligibilityIssues(candidate, true)).length === 0, ); const inheritedCandidate = healthyCandidates.find( (candidate) => candidate.instanceId === input.parent.thread.modelSelection.instanceId, @@ -1397,9 +1339,8 @@ const make = Effect.gen(function* () { `Provider instance ${instanceId} uses driver ${provider.driver}, not ${requestedDriver}.`, ); } - const constraints = providerConstraints( - provider, - orchestrationCapableInstanceIds.has(provider.instanceId), + const constraints = providerConstraintMessages( + providerEligibilityIssues(provider, orchestrationCapableInstanceIds.has(provider.instanceId)), ); if (constraints.length > 0) { return yield* failure( @@ -1437,7 +1378,7 @@ const make = Effect.gen(function* () { if (requestedOptions !== undefined) { const descriptors = provider.models.find((candidate) => candidate.slug === model) ?.capabilities?.optionDescriptors; - const invalid = invalidOptionSelections(requestedOptions, descriptors); + const invalid = providerOptionSelectionProblems(requestedOptions, descriptors); if (invalid.length > 0) { return yield* failure( "invalid_request", @@ -2081,9 +2022,11 @@ const make = Effect.gen(function* () { runtimeMode: limits.runtimeMode, interactionMode: limits.interactionMode, providers: providers.map((provider) => { - const constraints = providerConstraints( - provider, - orchestrationCapableInstanceIds.has(provider.instanceId), + const constraints = providerConstraintMessages( + providerEligibilityIssues( + provider, + orchestrationCapableInstanceIds.has(provider.instanceId), + ), ); const { listed, omitted } = listCapabilityModels({ provider, diff --git a/apps/server/src/mcp/toolkits/project/runtimeTools.ts b/apps/server/src/mcp/toolkits/project/runtimeTools.ts index 2e284c5d7a03..cb5e4229059c 100644 --- a/apps/server/src/mcp/toolkits/project/runtimeTools.ts +++ b/apps/server/src/mcp/toolkits/project/runtimeTools.ts @@ -2,6 +2,7 @@ import { OrchestratorMcpFailure, PositiveInt, ProjectId, + PROJECT_RUNTIME_BOUNDS, ProjectRuntimeContext, ProjectRuntimeError, ProjectRuntimeHandoff, @@ -53,6 +54,21 @@ const projectId = Schema.optional( }), ); +// Routing is user/orchestrator configuration in this gate. Keeping it out of +// agent-facing tool schemas avoids expanding every Runtime task tool prompt. +const { routing: _taskRouting, ...AgentProjectRuntimeTaskFields } = ProjectRuntimeTask.fields; +const AgentProjectRuntimeTask = Schema.Struct(AgentProjectRuntimeTaskFields); +const { routing: _createTaskRouting, ...AgentProjectRuntimeTaskCreateFields } = + ProjectRuntimeTaskCreateInput.fields; +const { routing: _updateTaskRouting, ...AgentProjectRuntimeTaskUpdateFields } = + ProjectRuntimeTaskUpdateInput.fields; +const AgentProjectRuntimeTaskListResult = Schema.Struct({ + ...ProjectRuntimeTaskListResult.fields, + tasks: Schema.Array(AgentProjectRuntimeTask).check( + Schema.isMaxLength(PROJECT_RUNTIME_BOUNDS.listMaxLimit), + ), +}); + const worktreeMetadataNote = "base.branch, base.worktreePath, and base.revision are descriptive only; they do not create, move, bind, or authorize a worktree or change the thread workspace."; @@ -110,7 +126,7 @@ export const ProjectTaskListTool = Tool.make("t3_project_task_list", { description: "List Runtime tasks, oldest first; optional status. Pass `nextCursor` back as `cursor`.", parameters: Schema.Struct({ projectId, ...ProjectRuntimeTaskListInput.fields }), - success: ProjectRuntimeTaskListResult, + success: AgentProjectRuntimeTaskListResult, }) .annotate(Tool.Readonly, true) .annotate(Tool.Destructive, false) @@ -120,7 +136,7 @@ export const ProjectTaskReadTool = Tool.make("t3_project_task_read", { ...shared, description: "Read one Runtime task by `taskId`, including its revision.", parameters: Schema.Struct({ projectId, ...ProjectRuntimeTaskReadInput.fields }), - success: ProjectRuntimeTask, + success: AgentProjectRuntimeTask, }) .annotate(Tool.Readonly, true) .annotate(Tool.Destructive, false) @@ -129,8 +145,8 @@ export const ProjectTaskReadTool = Tool.make("t3_project_task_read", { export const ProjectTaskCreateTool = Tool.make("t3_project_task_create", { ...shared, description: `Create a Runtime task. The server records the author. A blocker requires \`status:"blocked"\`, \`status:"blocked"\` requires a blocker, and \`status:"done"\` requires \`result\`. Verification milestones above \`implemented\` require passing evidence, and \`verified\` cannot coexist with failing evidence. ${worktreeMetadataNote}`, - parameters: Schema.Struct({ projectId, ...ProjectRuntimeTaskCreateInput.fields }), - success: ProjectRuntimeTask, + parameters: Schema.Struct({ projectId, ...AgentProjectRuntimeTaskCreateFields }), + success: AgentProjectRuntimeTask, }) .annotate(Tool.Destructive, false) .annotate(Tool.OpenWorld, false); @@ -138,8 +154,8 @@ export const ProjectTaskCreateTool = Tool.make("t3_project_task_create", { export const ProjectTaskUpdateTool = Tool.make("t3_project_task_update", { ...shared, description: `Update a Runtime task using compare-and-set: pass the revision last read as \`expectedRevision\`; a stale value returns \`ProjectRuntimeConflictError\`, so reread and retry. Omitted fields stay unchanged; null clears optional metadata. \`blocker:null\` clears the blocker, a blocker requires \`status:"blocked"\`, and \`status:"blocked"\` requires a blocker. \`status:"done"\` requires \`result\`. \`verification:null\` resets to milestone \`none\` with no evidence; milestones above \`implemented\` require passing evidence, and \`verified\` cannot coexist with failing evidence. ${worktreeMetadataNote}`, - parameters: Schema.Struct({ projectId, ...ProjectRuntimeTaskUpdateInput.fields }), - success: ProjectRuntimeTask, + parameters: Schema.Struct({ projectId, ...AgentProjectRuntimeTaskUpdateFields }), + success: AgentProjectRuntimeTask, }).annotate(Tool.OpenWorld, false); export const ProjectHandoffAppendTool = Tool.make("t3_project_handoff_append", { diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index 3fa285dd69fc..4792ba0c13b8 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -41,6 +41,9 @@ const RPC_AGGREGATES = { [PROJECT_RUNTIME_RPC_METHODS.updateTask]: "projectRuntime", [PROJECT_RUNTIME_RPC_METHODS.listHandoffs]: "projectRuntime", [PROJECT_RUNTIME_RPC_METHODS.readHandoff]: "projectRuntime", + [PROJECT_RUNTIME_RPC_METHODS.readRouting]: "projectRuntime", + [PROJECT_RUNTIME_RPC_METHODS.saveRouting]: "projectRuntime", + [PROJECT_RUNTIME_RPC_METHODS.resolveRoute]: "projectRuntime", [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: "orchestrationV2", [ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: "orchestration", diff --git a/apps/server/src/persistence/ForkMigrations.test.ts b/apps/server/src/persistence/ForkMigrations.test.ts index 2c28d04cc8bd..64888f6429ab 100644 --- a/apps/server/src/persistence/ForkMigrations.test.ts +++ b/apps/server/src/persistence/ForkMigrations.test.ts @@ -93,14 +93,17 @@ const seedLegacyForkHome = Effect.gen(function* () { const legacyData = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; - const [runtime] = yield* sql`SELECT * FROM project_runtime WHERE project_id = 'legacy-project'`; + const [runtime] = yield* sql`SELECT project_id, enabled, revision, instructions_json, + instructions_revision, created_at, updated_at + FROM project_runtime WHERE project_id = 'legacy-project'`; const [source] = yield* sql`SELECT * FROM project_runtime_sources WHERE source_id = 'legacy-source'`; const [task] = yield* sql`SELECT * FROM project_runtime_tasks WHERE task_id = 'legacy-task'`; const [handoff] = yield* sql`SELECT * FROM project_runtime_handoffs WHERE handoff_id = 'legacy-handoff'`; - const [profile] = - yield* sql`SELECT * FROM development_profiles WHERE profile_id = 'legacy-profile'`; + const [profile] = yield* sql`SELECT profile_id, name, instructions, revision, created_at, + updated_at, created_by, updated_by + FROM development_profiles WHERE profile_id = 'legacy-profile'`; const [assignment] = yield* sql`SELECT * FROM project_development_profiles WHERE project_id = 'legacy-project'`; return { runtime, source, task, handoff, profile, assignment }; @@ -119,7 +122,8 @@ describe("fork migration namespace", () => { const tables = yield* sql<{ readonly name: string }>` SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ( 'project_runtime', 'project_runtime_sources', 'project_runtime_tasks', - 'project_runtime_handoffs', 'development_profiles', 'project_development_profiles' + 'project_runtime_handoffs', 'project_runtime_routing', 'development_profiles', + 'project_development_profiles' ) ORDER BY name `; assert.deepStrictEqual( @@ -129,6 +133,7 @@ describe("fork migration namespace", () => { "project_development_profiles", "project_runtime", "project_runtime_handoffs", + "project_runtime_routing", "project_runtime_sources", "project_runtime_tasks", ], @@ -204,6 +209,10 @@ describe("fork migration namespace", () => { migration_id: 3, name: "TaskHandoffState", }, + { + migration_id: 4, + name: "RuntimeRouting", + }, ], ); assert.deepStrictEqual( @@ -315,10 +324,20 @@ const frozenForkSchema: ReadonlyArray = [ "project_runtime_handoffs_task_idx", "CREATE INDEX project_runtime_handoffs_task_idx ON project_runtime_handoffs(project_id, task_id, created_at, handoff_id)", ], + [ + "table", + "project_runtime_routing", + "CREATE TABLE project_runtime_routing ( project_id TEXT PRIMARY KEY REFERENCES projection_projects(project_id) ON DELETE CASCADE, routing_json TEXT, revision INTEGER NOT NULL CHECK (revision >= 1), created_at TEXT NOT NULL, updated_at TEXT NOT NULL )", + ], + [ + "trigger", + "project_runtime_routing_project_deleted", + "CREATE TRIGGER project_runtime_routing_project_deleted AFTER UPDATE OF deleted_at ON projection_projects WHEN NEW.deleted_at IS NOT NULL BEGIN DELETE FROM project_runtime_routing WHERE project_id = NEW.project_id; END", + ], [ "table", "development_profiles", - "CREATE TABLE development_profiles ( profile_id TEXT PRIMARY KEY, name TEXT NOT NULL CHECK (length(name) BETWEEN 1 AND 200), instructions TEXT NOT NULL CHECK (length(instructions) <= 32000), revision INTEGER NOT NULL CHECK (revision >= 1), created_at TEXT NOT NULL, updated_at TEXT NOT NULL, created_by TEXT NOT NULL CHECK (length(created_by) BETWEEN 1 AND 200), updated_by TEXT NOT NULL CHECK (length(updated_by) BETWEEN 1 AND 200) )", + "CREATE TABLE development_profiles ( profile_id TEXT PRIMARY KEY, name TEXT NOT NULL CHECK (length(name) BETWEEN 1 AND 200), instructions TEXT NOT NULL CHECK (length(instructions) <= 32000), revision INTEGER NOT NULL CHECK (revision >= 1), created_at TEXT NOT NULL, updated_at TEXT NOT NULL, created_by TEXT NOT NULL CHECK (length(created_by) BETWEEN 1 AND 200), updated_by TEXT NOT NULL CHECK (length(updated_by) BETWEEN 1 AND 200) , routing_json TEXT)", ], [ "index", diff --git a/apps/server/src/persistence/ForkMigrations.ts b/apps/server/src/persistence/ForkMigrations.ts index 4bbcd23869ce..8026c891aab7 100644 --- a/apps/server/src/persistence/ForkMigrations.ts +++ b/apps/server/src/persistence/ForkMigrations.ts @@ -7,6 +7,7 @@ import { projectRuntimeSchema } from "./Migrations/Fork/001_ProjectRuntime.ts"; import DevelopmentProfiles from "./Migrations/Fork/002_DevelopmentProfiles.ts"; import ProjectRuntime from "./Migrations/Fork/001_ProjectRuntime.ts"; import TaskHandoffState from "./Migrations/Fork/003_TaskHandoffState.ts"; +import RuntimeRouting from "./Migrations/Fork/004_RuntimeRouting.ts"; // Fork-owned schema lives in its own ledger. Upstream's numeric history stays // upstream's alone, so neither side can skip the other's migrations by id. @@ -14,6 +15,7 @@ const forkMigrationEntries = [ [1, "ProjectRuntime", ProjectRuntime], [2, "DevelopmentProfiles", DevelopmentProfiles], [3, "TaskHandoffState", TaskHandoffState], + [4, "RuntimeRouting", RuntimeRouting], ] as const; export const FORK_MIGRATION_TABLE = "t3_fork_migrations"; diff --git a/apps/server/src/persistence/Migrations/Fork/001_ProjectRuntime.test.ts b/apps/server/src/persistence/Migrations/Fork/001_ProjectRuntime.test.ts index 5f9707d962c1..6331bee228fc 100644 --- a/apps/server/src/persistence/Migrations/Fork/001_ProjectRuntime.test.ts +++ b/apps/server/src/persistence/Migrations/Fork/001_ProjectRuntime.test.ts @@ -22,6 +22,7 @@ it.effect( { migration_id: 1, name: "ProjectRuntime" }, { migration_id: 2, name: "DevelopmentProfiles" }, { migration_id: 3, name: "TaskHandoffState" }, + { migration_id: 4, name: "RuntimeRouting" }, ], ); const projects = yield* sql<{ diff --git a/apps/server/src/persistence/Migrations/Fork/003_TaskHandoffState.test.ts b/apps/server/src/persistence/Migrations/Fork/003_TaskHandoffState.test.ts index fbf58149ca39..47d1c5972ef4 100644 --- a/apps/server/src/persistence/Migrations/Fork/003_TaskHandoffState.test.ts +++ b/apps/server/src/persistence/Migrations/Fork/003_TaskHandoffState.test.ts @@ -237,6 +237,7 @@ it.effect("rewrites legacy task and handoff payloads into the v1 shape", () => { migration_id: 1, name: "ProjectRuntime" }, { migration_id: 2, name: "DevelopmentProfiles" }, { migration_id: 3, name: "TaskHandoffState" }, + { migration_id: 4, name: "RuntimeRouting" }, ], ); diff --git a/apps/server/src/persistence/Migrations/Fork/004_RuntimeRouting.test.ts b/apps/server/src/persistence/Migrations/Fork/004_RuntimeRouting.test.ts new file mode 100644 index 000000000000..adbd267caa29 --- /dev/null +++ b/apps/server/src/persistence/Migrations/Fork/004_RuntimeRouting.test.ts @@ -0,0 +1,139 @@ +import { assert, it } from "@effect/vitest"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { runMigrations } from "../../Migrations.ts"; +import DevelopmentProfilesMigration from "./002_DevelopmentProfiles.ts"; +import ProjectRuntimeMigration from "./001_ProjectRuntime.ts"; +import TaskHandoffStateMigration from "./003_TaskHandoffState.ts"; + +const timestamp = "2026-10-27T00:00:00.000Z"; + +const seedProject = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`PRAGMA foreign_keys = ON`; + yield* sql`INSERT INTO projection_projects (project_id, title, workspace_root, scripts_json, created_at, updated_at) + VALUES ('routing-project', 'Routing', '/routing', '[]', ${timestamp}, ${timestamp})`; +}); + +const forkSchema = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`PRAGMA foreign_keys = ON`; + yield* runMigrations({ toMigrationInclusive: 67 }); + yield* ProjectRuntimeMigration; + yield* DevelopmentProfilesMigration; + yield* TaskHandoffStateMigration; + yield* sql`CREATE TABLE t3_fork_migrations ( + migration_id integer PRIMARY KEY NOT NULL, + created_at datetime NOT NULL DEFAULT current_timestamp, + name VARCHAR(255) NOT NULL + )`; + yield* sql`INSERT INTO t3_fork_migrations (migration_id, name, created_at) VALUES + (1, 'ProjectRuntime', ${timestamp}), + (2, 'DevelopmentProfiles', ${timestamp}), + (3, 'TaskHandoffState', ${timestamp})`; +}); + +it.effect("adds routing columns and table to a fresh database", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations(); + const profileColumns = yield* sql<{ readonly name: string }>` + PRAGMA table_info(development_profiles)`; + assert.includeMembers( + profileColumns.map((column) => column.name), + ["routing_json"], + ); + const tables = yield* sql<{ readonly name: string }>` + SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'project_runtime_routing'`; + assert.deepEqual(tables, [{ name: "project_runtime_routing" }]); + assert.deepEqual(yield* runMigrations(), []); + }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), +); + +it.effect("preserves existing fork records when migrations 1-3 upgrade", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* forkSchema; + yield* seedProject; + yield* sql`INSERT INTO development_profiles + (profile_id, name, instructions, revision, created_at, updated_at, created_by, updated_by) + VALUES ('profile', 'Policy', 'Instructions', 4, ${timestamp}, ${timestamp}, 'user:test', 'user:test')`; + yield* sql`INSERT INTO project_development_profiles + (project_id, profile_id, revision, created_at, updated_at) + VALUES ('routing-project', 'profile', 2, ${timestamp}, ${timestamp})`; + yield* sql`INSERT INTO project_runtime + (project_id, enabled, revision, created_at, updated_at) + VALUES ('routing-project', 1, 9, ${timestamp}, ${timestamp})`; + yield* sql`INSERT INTO project_runtime_tasks + (task_id, project_id, status, revision, created_at, payload_json) + VALUES ('task', 'routing-project', 'active', 5, ${timestamp}, ${JSON.stringify({ + taskId: "task", + projectId: "routing-project", + title: "Ship", + scope: "Preserve rows", + owner: "user:test", + acceptanceCriteria: [], + status: "active", + blocker: null, + verification: { milestone: "none", evidence: [] }, + latestHandoffId: null, + revision: 5, + createdAt: timestamp, + updatedAt: timestamp, + createdBy: "user:test", + updatedBy: "user:test", + })})`; + + const executed = yield* runMigrations(); + assert.deepEqual(executed, [ + [68, "ShellStopRequestIndex"], + [69, "ThreadMessageSearch"], + ]); + const [profile] = yield* sql`SELECT profile_id, instructions, revision, routing_json + FROM development_profiles WHERE profile_id = 'profile'`; + assert.deepEqual(profile, { + profile_id: "profile", + instructions: "Instructions", + revision: 4, + routing_json: null, + }); + const [task] = yield* sql`SELECT task_id, revision, payload_json + FROM project_runtime_tasks WHERE task_id = 'task'`; + assert.isDefined(task); + assert.equal(task!.revision, 5); + assert.isUndefined(JSON.parse(String(task!.payload_json)).routing); + assert.deepEqual(yield* runMigrations(), []); + }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), +); + +it.effect("adds fork routing schema to a current upstream-origin database", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations({ toMigrationInclusive: 69 }); + assert.deepEqual(yield* runMigrations(), []); + const migrations = yield* sql<{ readonly migration_id: number; readonly name: string }>` + SELECT migration_id, name FROM t3_fork_migrations ORDER BY migration_id`; + assert.deepEqual(migrations, [ + { migration_id: 1, name: "ProjectRuntime" }, + { migration_id: 2, name: "DevelopmentProfiles" }, + { migration_id: 3, name: "TaskHandoffState" }, + { migration_id: 4, name: "RuntimeRouting" }, + ]); + }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), +); + +it.effect("removes project routing with soft-deleted projects", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations(); + yield* seedProject; + yield* sql`INSERT INTO project_runtime_routing + (project_id, routing_json, revision, created_at, updated_at) + VALUES ('routing-project', NULL, 1, ${timestamp}, ${timestamp})`; + yield* sql`UPDATE projection_projects SET deleted_at = ${timestamp} + WHERE project_id = 'routing-project'`; + assert.deepEqual(yield* sql`SELECT 1 FROM project_runtime_routing`, []); + }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), +); diff --git a/apps/server/src/persistence/Migrations/Fork/004_RuntimeRouting.ts b/apps/server/src/persistence/Migrations/Fork/004_RuntimeRouting.ts new file mode 100644 index 000000000000..060e72bb4664 --- /dev/null +++ b/apps/server/src/persistence/Migrations/Fork/004_RuntimeRouting.ts @@ -0,0 +1,33 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +/** + * Profile and project routing are structured JSON. Task routing needs no column + * because it already lives in `project_runtime_tasks.payload_json`; a null + * routing value on existing rows means "no routing policy". + */ +const runtimeRoutingSchema = [ + `ALTER TABLE development_profiles ADD COLUMN routing_json TEXT`, + + `CREATE TABLE project_runtime_routing ( + project_id TEXT PRIMARY KEY REFERENCES projection_projects(project_id) ON DELETE CASCADE, + routing_json TEXT, + revision INTEGER NOT NULL CHECK (revision >= 1), + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + )`, + + `CREATE TRIGGER project_runtime_routing_project_deleted + AFTER UPDATE OF deleted_at ON projection_projects + WHEN NEW.deleted_at IS NOT NULL + BEGIN + DELETE FROM project_runtime_routing WHERE project_id = NEW.project_id; + END`, +] as const; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + for (const statement of runtimeRoutingSchema) { + yield* sql.unsafe(statement).unprepared; + } +}); diff --git a/apps/server/src/projectRuntime/ProjectRuntimeRpc.test.ts b/apps/server/src/projectRuntime/ProjectRuntimeRpc.test.ts index a76df95e1f22..fab914f7c348 100644 --- a/apps/server/src/projectRuntime/ProjectRuntimeRpc.test.ts +++ b/apps/server/src/projectRuntime/ProjectRuntimeRpc.test.ts @@ -25,6 +25,13 @@ import * as WorkspaceFileSystem from "../workspace/WorkspaceFileSystem.ts"; import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; import * as Runtime from "./ProjectRuntimeService.ts"; import * as Sources from "./ProjectRuntimeSourceAccess.ts"; +import * as RuntimeRoutingService from "../runtimeRouting/RuntimeRoutingService.ts"; +import * as RuntimeRoutingProviderView from "../runtimeRouting/RuntimeRoutingProviderView.ts"; +import { + DEFAULT_SERVER_SETTINGS, + ProviderInstanceId, + type ServerProvider, +} from "@t3tools/contracts"; import { makeHandlers } from "./ProjectRuntimeRpc.ts"; const group = RpcGroup.make(...PROJECT_RUNTIME_RPCS).middleware(RpcScopeAuthorization); @@ -33,8 +40,16 @@ const workspace = WorkspaceFileSystem.layer.pipe( Layer.provideMerge(WorkspacePaths.layer), Layer.provide(Layer.mock(KnownWorkspaces.KnownWorkspaces)({ assertContains: () => Effect.void })), ); +const routingProviderView = Layer.succeed(RuntimeRoutingProviderView.RuntimeRoutingProviderView, { + read: Effect.succeed({ + providers: [] as ReadonlyArray, + orchestrationCapableInstanceIds: new Set(), + settings: DEFAULT_SERVER_SETTINGS, + }), +}); const layer = Sources.layer.pipe( Layer.provideMerge(Runtime.layer.pipe(Layer.provide(DevelopmentProfileService.layer))), + Layer.provideMerge(RuntimeRoutingService.layer.pipe(Layer.provide(routingProviderView))), Layer.provideMerge(ProjectStore.layer), Layer.provideMerge(workspace), Layer.provideMerge(Sqlite.layerMemory), @@ -318,6 +333,7 @@ it.effect("redacts persistence details at the user transport boundary", () => ), }), Layer.mock(Sources.ProjectRuntimeSourceAccess)({}), + Layer.mock(RuntimeRoutingService.RuntimeRoutingService)({}), ), ), ); @@ -336,3 +352,47 @@ it.effect("redacts persistence details at the user transport boundary", () => assert.notInclude(JSON.stringify(failure), "internal stack"); }).pipe(Effect.scoped), ); + +it.effect("round-trips project routing and resolves it without launching work", () => + Effect.gen(function* () { + const { client } = yield* setup; + const routing = { + roleRoutes: [ + { + role: "implementation" as const, + candidates: [{ providerInstanceId: ProviderInstanceId.make("codex"), model: "gpt-6" }], + fallback: "inherit" as const, + }, + ], + }; + assert.isNull(yield* client[M.readRouting]({ projectId: a })); + const saved = yield* client[M.saveRouting]({ + projectId: a, + routing, + expectedRevision: 0, + }); + assert.equal(saved.revision, 1); + assert.deepEqual(yield* client[M.readRouting]({ projectId: a }), saved); + assert.equal( + (yield* client[M.saveRouting]({ + projectId: a, + routing, + expectedRevision: 0, + }).pipe(Effect.flip))._tag, + "ProjectRuntimeRoutingConflictError", + ); + + const resolution = yield* client[M.resolveRoute]({ projectId: a }); + assert.equal(resolution.status, "inherited"); + assert.equal(resolution.rejected[0]?.reason, "provider_instance_missing"); + assert.deepEqual(yield* client[M.readRouting]({ projectId: a }), saved); + + const reset = yield* client[M.saveRouting]({ + projectId: a, + routing: null, + expectedRevision: 1, + }); + assert.equal(reset.revision, 2); + assert.isNull(reset.routing); + }).pipe(Effect.scoped, Effect.provide(layer)), +); diff --git a/apps/server/src/projectRuntime/ProjectRuntimeRpc.ts b/apps/server/src/projectRuntime/ProjectRuntimeRpc.ts index 28624c471450..a662f55e1185 100644 --- a/apps/server/src/projectRuntime/ProjectRuntimeRpc.ts +++ b/apps/server/src/projectRuntime/ProjectRuntimeRpc.ts @@ -2,6 +2,7 @@ import { PROJECT_RUNTIME_RPC_METHODS, ProjectRuntimeError, ProjectRuntimeRequestError, + RuntimeRoutingError, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; @@ -10,10 +11,12 @@ import type { RpcGroup } from "effect/rpc"; import { WsRpcGroup } from "@t3tools/contracts"; import * as ProjectRuntimeService from "./ProjectRuntimeService.ts"; import * as ProjectRuntimeSourceAccess from "./ProjectRuntimeSourceAccess.ts"; +import * as RuntimeRoutingService from "../runtimeRouting/RuntimeRoutingService.ts"; const isRuntimeError = Schema.is(ProjectRuntimeError); +const isRuntimeRoutingError = Schema.is(RuntimeRoutingError); const toRpcError = (error: unknown) => - isRuntimeError(error) + isRuntimeError(error) || isRuntimeRoutingError(error) ? error : new ProjectRuntimeRequestError({ reason: Predicate.isTagged(error, "ProjectNotFoundError") @@ -28,6 +31,7 @@ export const makeHandlers = Effect.fn("ProjectRuntimeRpc.makeHandlers")(function ) { const runtime = yield* ProjectRuntimeService.ProjectRuntimeService; const sources = yield* ProjectRuntimeSourceAccess.ProjectRuntimeSourceAccess; + const routing = yield* RuntimeRoutingService.RuntimeRoutingService; const actor = { actor: `user:${sessionId}` }; return { [PROJECT_RUNTIME_RPC_METHODS.status]: ({ projectId }) => @@ -58,5 +62,11 @@ export const makeHandlers = Effect.fn("ProjectRuntimeRpc.makeHandlers")(function runtime.listHandoffs(projectId, input).pipe(Effect.mapError(toRpcError)), [PROJECT_RUNTIME_RPC_METHODS.readHandoff]: ({ projectId, ...input }) => runtime.readHandoff(projectId, input.handoffId).pipe(Effect.mapError(toRpcError)), + [PROJECT_RUNTIME_RPC_METHODS.readRouting]: ({ projectId }) => + routing.readProjectRouting(projectId).pipe(Effect.mapError(toRpcError)), + [PROJECT_RUNTIME_RPC_METHODS.saveRouting]: ({ projectId, ...input }) => + routing.saveProjectRouting(projectId, input).pipe(Effect.mapError(toRpcError)), + [PROJECT_RUNTIME_RPC_METHODS.resolveRoute]: (input) => + routing.resolveRoute(input).pipe(Effect.mapError(toRpcError)), } satisfies Partial>>; }); diff --git a/apps/server/src/projectRuntime/ProjectRuntimeService.test.ts b/apps/server/src/projectRuntime/ProjectRuntimeService.test.ts index 0e3ce6454223..bf465279142b 100644 --- a/apps/server/src/projectRuntime/ProjectRuntimeService.test.ts +++ b/apps/server/src/projectRuntime/ProjectRuntimeService.test.ts @@ -1523,3 +1523,48 @@ it.effect( ); }).pipe(Effect.provide(layerTest)), ); + +it.effect("keeps task routing under the normal task revision CAS", () => + Effect.gen(function* () { + const service = yield* setup; + const routing = (model: string, fallback: "continue" | "inherit" | "fail" = "inherit") => ({ + role: "implementation" as const, + candidates: [{ providerInstanceId: ProviderInstanceId.make("codex"), model }], + fallback, + }); + const created = yield* service.createTask( + projectA, + { ...taskInput, routing: routing("gpt-6") }, + actor, + ); + assert.deepEqual(created.routing, routing("gpt-6")); + + const routed = yield* service.updateTask( + projectA, + { taskId: created.taskId, expectedRevision: 1, routing: routing("gpt-7", "fail") }, + otherActor, + ); + assert.equal(routed.revision, 2); + assert.deepEqual(routed.routing, routing("gpt-7", "fail")); + + const stale = yield* service + .updateTask( + projectA, + { taskId: created.taskId, expectedRevision: 1, routing: routing("gpt-8") }, + actor, + ) + .pipe(Effect.flip); + assert.instanceOf(stale, ProjectRuntimeConflictError); + const afterStale = yield* service.readTask(projectA, created.taskId); + assert.equal(afterStale.revision, 2); + assert.equal(afterStale.scope, created.scope); + assert.deepEqual(afterStale.routing, routing("gpt-7", "fail")); + + const cleared = yield* service.updateTask( + projectA, + { taskId: created.taskId, expectedRevision: 2, routing: null }, + actor, + ); + assert.equal(cleared.routing, undefined); + }).pipe(Effect.provide(layerTest)), +); diff --git a/apps/server/src/projectRuntime/ProjectRuntimeService.ts b/apps/server/src/projectRuntime/ProjectRuntimeService.ts index 35949e794132..193770113a0d 100644 --- a/apps/server/src/projectRuntime/ProjectRuntimeService.ts +++ b/apps/server/src/projectRuntime/ProjectRuntimeService.ts @@ -283,6 +283,10 @@ function applyTaskPatch( if (patch.nextAction === null) delete result.nextAction; else result.nextAction = patch.nextAction; } + if (patch.routing !== undefined) { + if (patch.routing === null) delete result.routing; + else result.routing = patch.routing; + } return result; } diff --git a/apps/server/src/provider/providerEligibility.ts b/apps/server/src/provider/providerEligibility.ts new file mode 100644 index 000000000000..6eabbb02d5d7 --- /dev/null +++ b/apps/server/src/provider/providerEligibility.ts @@ -0,0 +1,110 @@ +import { + isProviderAvailable, + type ProviderOptionDescriptor, + type ProviderOptionSelection, + type ServerProvider, +} from "@t3tools/contracts"; + +/** + * The shared provider checks behind both child-task dispatch and Runtime route + * resolution. Codes are stable for routing receipts; messages stay the human + * strings the Orchestrator already reports. + */ +export type ProviderEligibilityIssueCode = + | "orchestration_unsupported" + | "provider_unavailable" + | "provider_disabled" + | "provider_not_installed" + | "provider_not_ready" + | "provider_auth_required"; + +export interface ProviderEligibilityIssue { + readonly code: ProviderEligibilityIssueCode; + readonly detail: string; +} + +export function providerEligibilityIssues( + provider: ServerProvider | undefined, + supportsOrchestrationV2: boolean, +): ReadonlyArray { + const issues: Array = []; + if (!supportsOrchestrationV2) { + issues.push({ + code: "orchestration_unsupported", + detail: "No V2 provider adapter is registered.", + }); + } + if (provider === undefined) return issues; + if (!isProviderAvailable(provider)) { + issues.push({ + code: "provider_unavailable", + detail: provider.unavailableReason ?? "Provider driver is unavailable.", + }); + } + if (!provider.enabled) { + issues.push({ + code: "provider_disabled", + detail: "Provider instance is disabled.", + }); + // Disabled snapshots contain placeholders for installation, health, and auth. + return issues; + } + if (!provider.installed) { + issues.push({ + code: "provider_not_installed", + detail: "Provider executable is not installed.", + }); + } + if (provider.status === "error" || provider.status === "disabled") { + issues.push({ + code: "provider_not_ready", + detail: provider.message ?? `Provider status is ${provider.status}.`, + }); + } + if (provider.auth.status === "unauthenticated") { + issues.push({ + code: "provider_auth_required", + detail: "Provider is not authenticated.", + }); + } + return issues; +} + +export const providerConstraintMessages = ( + issues: ReadonlyArray, +): ReadonlyArray => issues.map((issue) => issue.detail); + +/** Skip checks without descriptors; reject duplicate IDs because consumers disagree on precedence. */ +export function providerOptionSelectionProblems( + selections: ReadonlyArray, + descriptors: ReadonlyArray | undefined, +): ReadonlyArray { + const problems: Array = []; + const seen = new Set(); + for (const selection of selections) { + if (seen.has(selection.id)) { + problems.push(`Option ${selection.id} was specified more than once.`); + continue; + } + seen.add(selection.id); + if (descriptors === undefined) continue; + const descriptor = descriptors.find((candidate) => candidate.id === selection.id); + if (descriptor === undefined) { + const known = descriptors.map((candidate) => candidate.id).join(", "); + problems.push(`Unknown option ${selection.id}; supported options: ${known || "none"}.`); + continue; + } + if (descriptor.type === "boolean" && typeof selection.value !== "boolean") { + problems.push(`Option ${selection.id} expects a boolean value.`); + continue; + } + if ( + descriptor.type === "select" && + !descriptor.options.some((choice) => choice.id === selection.value) + ) { + const choices = descriptor.options.map((choice) => choice.id).join(", "); + problems.push(`Option ${selection.id} must be one of: ${choices}.`); + } + } + return problems; +} diff --git a/apps/server/src/runtimeRouting/RuntimeRoutingEligibility.ts b/apps/server/src/runtimeRouting/RuntimeRoutingEligibility.ts new file mode 100644 index 000000000000..1c418142418b --- /dev/null +++ b/apps/server/src/runtimeRouting/RuntimeRoutingEligibility.ts @@ -0,0 +1,183 @@ +import { + type ProjectId, + type ProviderInstanceId, + type RuntimeRouteCandidate, + type RuntimeRouteRejectionReason, + type ServerProvider, + type ServerSettings, + resolveProjectProviderInstanceEnabled, +} from "@t3tools/contracts"; + +import { + providerEligibilityIssues, + providerOptionSelectionProblems, +} from "../provider/providerEligibility.ts"; + +export interface RuntimeRouteEligibilityContext { + readonly projectId: ProjectId; + readonly providers: ReadonlyArray; + readonly orchestrationCapableInstanceIds: ReadonlySet; + readonly settings: Pick; +} + +export type RuntimeRouteCandidateEvaluation = + | { + readonly eligible: true; + readonly providerInstanceId: ProviderInstanceId; + readonly driverKind: ServerProvider["driver"]; + } + | { + readonly eligible: false; + readonly reason: RuntimeRouteRejectionReason; + readonly detail?: string; + }; + +const ineligible = ( + reason: RuntimeRouteRejectionReason, + detail?: string, +): RuntimeRouteCandidateEvaluation => ({ + eligible: false, + reason, + ...(detail === undefined ? {} : { detail }), +}); + +const issueReason = ( + code: ReturnType[number]["code"], +): RuntimeRouteRejectionReason => { + switch (code) { + case "orchestration_unsupported": + return "provider_orchestration_unsupported"; + case "provider_unavailable": + return "provider_unavailable"; + case "provider_disabled": + return "provider_disabled"; + case "provider_not_installed": + return "provider_not_installed"; + case "provider_not_ready": + return "provider_not_ready"; + case "provider_auth_required": + return "provider_auth_required"; + } +}; + +function evaluateProvider( + candidate: RuntimeRouteCandidate, + provider: ServerProvider, + context: RuntimeRouteEligibilityContext, +): RuntimeRouteCandidateEvaluation { + if (candidate.driverKind !== undefined && provider.driver !== candidate.driverKind) { + return ineligible( + "provider_driver_mismatch", + `Provider instance ${provider.instanceId} uses driver ${provider.driver}, not ${candidate.driverKind}.`, + ); + } + const issue = providerEligibilityIssues(provider, true)[0]; + if (issue !== undefined) { + return ineligible(issueReason(issue.code), issue.detail); + } + if (!context.orchestrationCapableInstanceIds.has(provider.instanceId)) { + return ineligible( + "provider_orchestration_unsupported", + `No V2 provider adapter is registered for ${provider.instanceId}.`, + ); + } + if ( + !resolveProjectProviderInstanceEnabled(context.settings, context.projectId, provider.instanceId) + ) { + return ineligible( + "provider_instance_disabled_for_project", + `Provider instance ${provider.instanceId} is disabled for this project.`, + ); + } + if ( + provider.models.length > 0 && + !provider.models.some((model) => model.slug === candidate.model) + ) { + return ineligible( + "model_unavailable", + `Model ${candidate.model} is not advertised by provider ${provider.instanceId}.`, + ); + } + if (candidate.options !== undefined) { + const descriptors = provider.models.find((model) => model.slug === candidate.model) + ?.capabilities?.optionDescriptors; + const problems = providerOptionSelectionProblems(candidate.options, descriptors); + if (problems.length > 0) { + return ineligible("model_options_invalid", problems.join(" ")); + } + } + if ( + candidate.runtimeMode !== undefined && + provider.supportedRuntimeModes !== undefined && + provider.supportedRuntimeModes.length > 0 && + !provider.supportedRuntimeModes.includes(candidate.runtimeMode) + ) { + return ineligible( + "runtime_mode_unsupported", + `Provider instance ${provider.instanceId} does not support runtime mode ${candidate.runtimeMode}.`, + ); + } + if (candidate.interactionMode === "plan" && provider.showInteractionModeToggle === false) { + return ineligible( + "interaction_mode_unsupported", + `Provider instance ${provider.instanceId} does not offer plan interaction mode.`, + ); + } + return { + eligible: true, + providerInstanceId: provider.instanceId, + driverKind: provider.driver, + }; +} + +/** + * Resolution is a read of existing provider/project state. It never refreshes, + * installs, authenticates, or otherwise mutates a provider. + */ +export function evaluateRuntimeRouteCandidate( + candidate: RuntimeRouteCandidate, + context: RuntimeRouteEligibilityContext, +): RuntimeRouteCandidateEvaluation { + if (candidate.providerInstanceId !== undefined) { + const provider = context.providers.find( + (entry) => entry.instanceId === candidate.providerInstanceId, + ); + if (provider === undefined) { + return ineligible( + "provider_instance_missing", + `Provider instance ${candidate.providerInstanceId} is not registered.`, + ); + } + return evaluateProvider(candidate, provider, context); + } + if (candidate.driverKind === undefined) { + return ineligible( + "provider_instance_missing", + "The route names no provider instance or driver.", + ); + } + + const driverProviders = context.providers.filter( + (provider) => provider.driver === candidate.driverKind, + ); + if (driverProviders.length === 0) { + return ineligible( + "provider_instance_missing", + `No provider instance uses driver ${candidate.driverKind}.`, + ); + } + const rejected: Array> = []; + for (const provider of driverProviders) { + const evaluation = evaluateProvider(candidate, provider, context); + if (evaluation.eligible) return evaluation; + rejected.push(evaluation); + } + const reasons = new Set(rejected.map((evaluation) => evaluation.reason)); + const [first] = rejected; + return reasons.size === 1 && first !== undefined + ? ineligible(first.reason, first.detail) + : ineligible( + "no_eligible_provider_instance", + `No eligible instance of driver ${candidate.driverKind}. ${first?.detail ?? ""}`.trim(), + ); +} diff --git a/apps/server/src/runtimeRouting/RuntimeRoutingProviderView.ts b/apps/server/src/runtimeRouting/RuntimeRoutingProviderView.ts new file mode 100644 index 000000000000..1fcffcc93c41 --- /dev/null +++ b/apps/server/src/runtimeRouting/RuntimeRoutingProviderView.ts @@ -0,0 +1,54 @@ +import { + type ProviderInstanceId, + type ServerProvider, + type ServerSettings, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts"; +import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; +import * as ServerSettingsModule from "../serverSettings.ts"; + +/** A read-only view over existing provider state; Runtime does not keep a catalog. */ +export class RuntimeRoutingProviderView extends Context.Service< + RuntimeRoutingProviderView, + { + readonly read: Effect.Effect<{ + readonly providers: ReadonlyArray; + readonly orchestrationCapableInstanceIds: ReadonlySet; + readonly settings: ServerSettings; + }>; + } +>()("t3/runtimeRouting/RuntimeRoutingProviderView") {} + +export const layer = Layer.effect( + RuntimeRoutingProviderView, + Effect.gen(function* () { + const providers = yield* ProviderRegistry.ProviderRegistry; + const instances = yield* ProviderInstanceRegistry.ProviderInstanceRegistry; + const settings = yield* ServerSettingsModule.ServerSettingsService; + return RuntimeRoutingProviderView.of({ + read: Effect.gen(function* () { + // Every live instance carries a V2 orchestration adapter; unavailable + // instances are absent from this list, and provider snapshots report why. + const [providerList, liveInstances, currentSettings] = yield* Effect.all( + [ + providers.getProviders, + instances.listInstances, + settings.getSettings.pipe(Effect.orDie), + ], + { concurrency: "unbounded" }, + ); + return { + providers: providerList, + orchestrationCapableInstanceIds: new Set( + liveInstances.map((instance) => instance.instanceId), + ), + settings: currentSettings, + }; + }), + }); + }), +); diff --git a/apps/server/src/runtimeRouting/RuntimeRoutingResolver.test.ts b/apps/server/src/runtimeRouting/RuntimeRoutingResolver.test.ts new file mode 100644 index 000000000000..35cc1cb516e4 --- /dev/null +++ b/apps/server/src/runtimeRouting/RuntimeRoutingResolver.test.ts @@ -0,0 +1,500 @@ +import { + DEFAULT_SERVER_SETTINGS, + type DevelopmentProfileId as DevelopmentProfileIdType, + DevelopmentProfileId, + type ModelCapabilities, + type ProjectDevelopmentProfile, + ProjectId as ProjectIdSchema, + ProjectRuntimeTaskId, + ProviderDriverKind, + type ProviderInstanceId, + ProviderInstanceId as ProviderInstanceIdSchema, + type RuntimeProfileRoleRoute, + type RuntimeProfileRoutingPolicy, + type RuntimeRoleRoute, + type RuntimeRouteCandidate, + type RuntimeRoutingPolicy, + type ServerProvider, + type ServerProviderModel, + type ServerSettings, +} from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { type ResolveRuntimeRouteInput, resolveRuntimeRoute } from "./RuntimeRoutingResolver.ts"; + +const projectId = ProjectIdSchema.make("routing-project"); +const timestamp = "2026-10-27T00:00:00.000Z"; +const codex = ProviderInstanceIdSchema.make("codex"); +const claude = ProviderInstanceIdSchema.make("claudeAgent"); +const grok = ProviderInstanceIdSchema.make("grok"); +const codexAux = ProviderInstanceIdSchema.make("codex-aux"); + +const model = ( + slug: string, + capabilities: ModelCapabilities | null = null, +): ServerProviderModel => ({ + slug, + name: slug, + isCustom: false, + capabilities, +}); + +const provider = (input: { + readonly instanceId: ProviderInstanceId; + readonly driver: string; + readonly models?: ReadonlyArray; + readonly overrides?: Partial; +}): ServerProvider => ({ + instanceId: input.instanceId, + driver: ProviderDriverKind.make(input.driver), + enabled: true, + installed: true, + version: "1.0.0", + status: "ready", + auth: { status: "authenticated" }, + checkedAt: timestamp, + models: input.models ?? [model("gpt-6")], + slashCommands: [], + skills: [], + ...input.overrides, +}); + +const codexProvider = provider({ instanceId: codex, driver: "codex" }); +const codexAuxProvider = provider({ instanceId: codexAux, driver: "codex" }); +const claudeProvider = provider({ + instanceId: claude, + driver: "claudeAgent", + models: [model("claude-fable-5-1")], +}); +const grokProvider = provider({ + instanceId: grok, + driver: "grok", + models: [model("grok-build")], +}); +const providers = [codexProvider, codexAuxProvider, claudeProvider, grokProvider]; + +const candidate = (input: Partial = {}): RuntimeRouteCandidate => ({ + providerInstanceId: codex, + model: "gpt-6", + ...input, +}); + +const route = (input: Partial = {}): RuntimeRoleRoute => ({ + role: "implementation", + candidates: [candidate()], + fallback: "inherit", + ...input, +}); + +const profileRoute = (input: Partial = {}): RuntimeProfileRoleRoute => ({ + role: "implementation", + candidates: [candidate()], + fallback: "inherit", + ...input, +}); + +const profileRouting = ( + routes: RuntimeProfileRoutingPolicy["roleRoutes"], +): RuntimeProfileRoutingPolicy => ({ roleRoutes: routes }); + +const projectRouting = (routes: RuntimeRoutingPolicy["roleRoutes"]): RuntimeRoutingPolicy => ({ + roleRoutes: routes, +}); + +const profileState = (routing: RuntimeProfileRoutingPolicy) => ({ + profileId: DevelopmentProfileId.make("profile") as DevelopmentProfileIdType, + revision: 1, + routing, +}); + +const assignmentState = (): ProjectDevelopmentProfile => ({ + projectId, + profileId: DevelopmentProfileId.make("profile"), + revision: 1, + createdAt: timestamp, + updatedAt: timestamp, +}); + +const taskState = (routing: RuntimeRoleRoute) => ({ + taskId: ProjectRuntimeTaskId.make("task"), + revision: 4, + routing, +}); + +const settingsWithProjectDisable = (instanceId: ProviderInstanceId): ServerSettings => ({ + ...DEFAULT_SERVER_SETTINGS, + projectSettingsOverrides: { + [projectId]: { providerInstances: { [instanceId]: { enabled: false } } }, + }, +}); + +const resolve = ( + input: { + readonly task?: ResolveRuntimeRouteInput["task"]; + readonly projectRouting?: ResolveRuntimeRouteInput["projectRouting"]; + readonly profile?: ResolveRuntimeRouteInput["profile"]; + readonly assignment?: ResolveRuntimeRouteInput["assignment"]; + readonly role?: ResolveRuntimeRouteInput["role"]; + readonly override?: ResolveRuntimeRouteInput["override"]; + readonly providers?: ReadonlyArray; + readonly settings?: ServerSettings; + readonly orchestrationCapableInstanceIds?: ReadonlySet; + } = {}, +) => { + const activeProviders = input.providers ?? providers; + return resolveRuntimeRoute({ + projectId, + task: input.task ?? null, + projectRouting: input.projectRouting ?? { routing: null, revision: 0 }, + profile: input.profile ?? null, + assignment: input.assignment ?? null, + ...(input.role === undefined ? {} : { role: input.role }), + ...(input.override === undefined ? {} : { override: input.override }), + eligibility: { + projectId, + providers: activeProviders, + orchestrationCapableInstanceIds: + input.orchestrationCapableInstanceIds ?? + new Set(activeProviders.map((entry) => entry.instanceId)), + settings: input.settings ?? DEFAULT_SERVER_SETTINGS, + }, + }); +}; + +const reasons = (resolution: ReturnType) => + resolution.rejected.map((rejection) => rejection.reason); + +describe("runtime routing precedence", () => { + it("uses the profile when project and task have no routing", () => { + const resolution = resolve({ profile: profileState(profileRouting([profileRoute()])) }); + expect(resolution.status).toBe("resolved"); + expect(resolution.source).toBe("profile"); + expect(resolution.selected?.providerInstanceId).toBe(codex); + expect(resolution.revisions.profile?.revision).toBe(1); + }); + + it("lets a project override a profile route", () => { + const resolution = resolve({ + profile: profileState(profileRouting([profileRoute()])), + projectRouting: { + routing: projectRouting([ + route({ + candidates: [candidate({ providerInstanceId: claude, model: "claude-fable-5-1" })], + }), + ]), + revision: 2, + }, + assignment: assignmentState(), + }); + expect(resolution.source).toBe("project"); + expect(resolution.selected?.providerInstanceId).toBe(claude); + expect(resolution.revisions.projectRouting).toBe(2); + }); + + it("lets a task override project and profile routes", () => { + const resolution = resolve({ + task: taskState( + route({ + candidates: [candidate()], + }), + ), + projectRouting: { + routing: projectRouting([ + route({ + candidates: [candidate({ providerInstanceId: claude, model: "claude-fable-5-1" })], + }), + ]), + revision: 1, + }, + profile: profileState(profileRouting([profileRoute()])), + assignment: assignmentState(), + }); + expect(resolution.source).toBe("task"); + expect(resolution.selected?.providerInstanceId).toBe(codex); + expect(resolution.revisions.task).toBe(4); + }); + + it("uses a one-run override before every stored layer", () => { + const resolution = resolve({ + task: taskState(route()), + override: { + candidate: candidate({ providerInstanceId: claude, model: "claude-fable-5-1" }), + }, + }); + expect(resolution.status).toBe("resolved"); + expect(resolution.source).toBe("explicit"); + expect(resolution.selected?.providerInstanceId).toBe(claude); + }); + + it("returns to the profile after a project reset", () => { + const resolution = resolve({ + projectRouting: { routing: null, revision: 3 }, + profile: profileState(profileRouting([profileRoute()])), + assignment: assignmentState(), + }); + expect(resolution.status).toBe("resolved"); + expect(resolution.source).toBe("profile"); + }); + + it("uses the task role over a caller-supplied role", () => { + const resolution = resolve({ + role: "implementation", + task: taskState(route({ role: "review" })), + projectRouting: { + routing: projectRouting([ + route({ + role: "implementation", + candidates: [candidate({ providerInstanceId: claude, model: "claude-fable-5-1" })], + }), + ]), + revision: 1, + }, + }); + expect(resolution.role).toBe("review"); + expect(resolution.source).toBe("task"); + expect(resolution.selected?.providerInstanceId).toBe(codex); + }); + + it("resolves a driver-only candidate to the first eligible instance", () => { + const resolution = resolve({ + projectRouting: { + routing: projectRouting([ + route({ + candidates: [{ driverKind: ProviderDriverKind.make("codex"), model: "gpt-6" }], + }), + ]), + revision: 1, + }, + }); + expect(resolution.status).toBe("resolved"); + expect(resolution.selected?.providerInstanceId).toBe(codex); + }); + + it("fails closed when a one-run override is ineligible", () => { + const resolution = resolve({ + task: taskState(route()), + override: { + candidate: candidate({ providerInstanceId: ProviderInstanceIdSchema.make("missing") }), + }, + }); + expect(resolution.status).toBe("failed"); + expect(resolution.source).toBe("explicit"); + expect(resolution.selected).toBeNull(); + expect(resolution.rejected[0]?.reason).toBe("provider_instance_missing"); + }); + + it("reports ordinary inheritance when no layer has a route", () => { + const resolution = resolve(); + expect(resolution.status).toBe("inherited"); + expect(resolution.source).toBe("inherit"); + expect(resolution.selected).toBeNull(); + expect(resolution.inheritedFrom).toBeNull(); + expect(resolution.rejected).toEqual([]); + }); +}); + +describe("runtime routing fallback", () => { + it("selects a later candidate and keeps the earlier rejection", () => { + const resolution = resolve({ + task: taskState( + route({ + candidates: [ + candidate({ providerInstanceId: ProviderInstanceIdSchema.make("missing") }), + candidate(), + ], + fallback: "inherit", + }), + ), + }); + expect(resolution.status).toBe("resolved"); + expect(resolution.source).toBe("task"); + expect(resolution.selected?.candidateIndex).toBe(1); + expect(resolution.rejected).toHaveLength(1); + expect(resolution.rejected[0]?.reason).toBe("provider_instance_missing"); + expect(resolution.rejected[0]?.candidateIndex).toBe(0); + }); + + it("refuses with fail instead of silently inheriting", () => { + const resolution = resolve({ + task: taskState( + route({ + candidates: [candidate({ providerInstanceId: ProviderInstanceIdSchema.make("missing") })], + fallback: "fail", + }), + ), + profile: profileState(profileRouting([profileRoute()])), + assignment: assignmentState(), + }); + expect(resolution.status).toBe("failed"); + expect(resolution.source).toBe("task"); + expect(resolution.failure).toEqual({ source: "task", reason: "candidates_exhausted" }); + expect(resolution.selected).toBeNull(); + expect(resolution.inheritedFrom).toBeNull(); + }); + + it("continues to the next layer after the current layer is exhausted", () => { + const resolution = resolve({ + task: taskState( + route({ + candidates: [candidate({ providerInstanceId: ProviderInstanceIdSchema.make("missing") })], + fallback: "continue", + }), + ), + projectRouting: { + routing: projectRouting([route()]), + revision: 1, + }, + }); + expect(resolution.status).toBe("resolved"); + expect(resolution.source).toBe("project"); + expect(resolution.rejected[0]?.reason).toBe("provider_instance_missing"); + }); + + it("deliberately inherits without evaluating the profile", () => { + const resolution = resolve({ + projectRouting: { + routing: projectRouting([ + route({ + candidates: [ + candidate({ providerInstanceId: ProviderInstanceIdSchema.make("missing") }), + ], + fallback: "inherit", + }), + ]), + revision: 1, + }, + profile: profileState(profileRouting([profileRoute()])), + assignment: assignmentState(), + }); + expect(resolution.status).toBe("inherited"); + expect(resolution.source).toBe("inherit"); + expect(resolution.inheritedFrom).toBe("project"); + expect(resolution.rejected).toHaveLength(1); + expect(resolution.rejected[0]?.source).toBe("project"); + }); +}); + +describe("runtime routing provider eligibility", () => { + it("rejects a provider disabled for the project", () => { + const resolution = resolve({ + projectRouting: { + routing: projectRouting([route({ fallback: "fail" })]), + revision: 1, + }, + settings: settingsWithProjectDisable(codex), + }); + expect(resolution.status).toBe("failed"); + expect(reasons(resolution)).toContain("provider_instance_disabled_for_project"); + }); + + it("reports a temporarily unavailable provider without changing the route", () => { + const unavailable = provider({ + instanceId: codex, + driver: "codex", + overrides: { availability: "unavailable", unavailableReason: "Provider is offline." }, + }); + const savedRouting = projectRouting([route({ fallback: "fail" })]); + const resolution = resolve({ + projectRouting: { routing: savedRouting, revision: 4 }, + providers: [unavailable], + orchestrationCapableInstanceIds: new Set(), + }); + expect(resolution.status).toBe("failed"); + expect(reasons(resolution)).toContain("provider_unavailable"); + expect(resolution.rejected[0]?.detail).toBe("Provider is offline."); + expect(resolution.revisions.projectRouting).toBe(4); + }); + + it("reports a model that is no longer advertised", () => { + const resolution = resolve({ + projectRouting: { + routing: projectRouting([ + route({ candidates: [candidate({ model: "removed-model" })], fallback: "fail" }), + ]), + revision: 1, + }, + }); + expect(resolution.status).toBe("failed"); + expect(reasons(resolution)).toContain("model_unavailable"); + expect(resolution.selected).toBeNull(); + }); + + it("resolves an ordinary eligible provider without provider-specific branches", () => { + const resolution = resolve({ + projectRouting: { + routing: projectRouting([route({ fallback: "fail" })]), + revision: 1, + }, + }); + expect(resolution.status).toBe("resolved"); + expect(resolution.selected?.driverKind).toBe("codex"); + expect(resolution.selected?.eligibility).toBe("eligible-at-resolution"); + }); + + it("rejects an unsupported runtime mode and plan mode", () => { + const limited = provider({ + instanceId: codex, + driver: "codex", + overrides: { + supportedRuntimeModes: ["approval-required"], + showInteractionModeToggle: false, + }, + }); + const runtime = resolve({ + projectRouting: { + routing: projectRouting([ + route({ candidates: [candidate({ runtimeMode: "full-access" })], fallback: "fail" }), + ]), + revision: 1, + }, + providers: [limited], + }); + expect(reasons(runtime)).toContain("runtime_mode_unsupported"); + + const plan = resolve({ + projectRouting: { + routing: projectRouting([ + route({ candidates: [candidate({ interactionMode: "plan" })], fallback: "fail" }), + ]), + revision: 1, + }, + providers: [limited], + }); + expect(reasons(plan)).toContain("interaction_mode_unsupported"); + }); + + it("rejects model options the advertised model does not support", () => { + const capabilities: ModelCapabilities = { + optionDescriptors: [ + { + id: "reasoning", + label: "Reasoning", + type: "select", + options: [ + { id: "low", label: "Low" }, + { id: "high", label: "High" }, + ], + }, + ], + }; + const structured = provider({ + instanceId: codex, + driver: "codex", + models: [model("gpt-6", capabilities)], + }); + const resolution = resolve({ + projectRouting: { + routing: projectRouting([ + route({ + candidates: [candidate({ options: [{ id: "reasoning", value: "max" }] })], + fallback: "fail", + }), + ]), + revision: 1, + }, + providers: [structured], + }); + expect(resolution.status).toBe("failed"); + expect(reasons(resolution)).toContain("model_options_invalid"); + }); +}); diff --git a/apps/server/src/runtimeRouting/RuntimeRoutingResolver.ts b/apps/server/src/runtimeRouting/RuntimeRoutingResolver.ts new file mode 100644 index 000000000000..1b3753f1d5dd --- /dev/null +++ b/apps/server/src/runtimeRouting/RuntimeRoutingResolver.ts @@ -0,0 +1,264 @@ +import { + type DevelopmentProfile, + type ProjectDevelopmentProfile, + type ProjectId, + type ProjectRuntimeTask, + type RuntimeProfileRoleRoute, + type RuntimeResolvedRoute, + type RuntimeRoleRoute, + type RuntimeRouteCandidate, + type RuntimeRouteFailureReason, + type RuntimeRouteRejection, + type RuntimeRouteResolution, + type RuntimeRouteResolutionInput, + type RuntimeRouteRevisions, + type RuntimeRouteSource, + type RuntimeRoutingFallback, + type RuntimeRoutingPolicy, + type RuntimeWorkerRole, + RUNTIME_ROUTING_BOUNDS, +} from "@t3tools/contracts"; + +import { + evaluateRuntimeRouteCandidate, + type RuntimeRouteEligibilityContext, +} from "./RuntimeRoutingEligibility.ts"; + +export interface RuntimeRoutingTaskState { + readonly taskId: ProjectRuntimeTask["taskId"]; + readonly revision: ProjectRuntimeTask["revision"]; + readonly routing?: RuntimeRoleRoute; +} + +export interface RuntimeRoutingProfileState { + readonly profileId: DevelopmentProfile["profileId"]; + readonly revision: DevelopmentProfile["revision"]; + readonly routing: DevelopmentProfile["routing"]; +} + +export interface RuntimeRoutingLayerState { + readonly task: RuntimeRoutingTaskState | null; + readonly projectRouting: { + readonly routing: RuntimeRoutingPolicy | null; + readonly revision: number; + }; + readonly profile: RuntimeRoutingProfileState | null; + readonly assignment: ProjectDevelopmentProfile | null; +} + +export interface ResolveRuntimeRouteInput extends RuntimeRoutingLayerState { + readonly projectId: ProjectId; + readonly role?: RuntimeWorkerRole; + readonly override?: RuntimeRouteResolutionInput["override"]; + readonly eligibility: RuntimeRouteEligibilityContext; +} + +type RouteLayer = "explicit" | "task" | "project" | "profile"; + +const boundedDetail = (detail: string): string => + detail.length <= RUNTIME_ROUTING_BOUNDS.rejectionDetailMaxLength + ? detail + : detail.slice(0, RUNTIME_ROUTING_BOUNDS.rejectionDetailMaxLength); + +const findProjectRoute = ( + policy: RuntimeRoutingPolicy | null, + role: RuntimeWorkerRole, +): RuntimeRoleRoute | undefined => policy?.roleRoutes.find((route) => route.role === role); + +const findProfileRoute = ( + policy: { readonly roleRoutes: ReadonlyArray } | null, + role: RuntimeWorkerRole, +): RuntimeProfileRoleRoute | undefined => policy?.roleRoutes.find((route) => route.role === role); + +const selectedRoute = (input: { + readonly source: RouteLayer; + readonly candidateIndex: number; + readonly candidate: RuntimeRouteCandidate; + readonly evaluation: Extract< + ReturnType, + { eligible: true } + >; +}): RuntimeResolvedRoute => ({ + source: input.source, + candidateIndex: input.candidateIndex, + candidate: input.candidate, + providerInstanceId: input.evaluation.providerInstanceId, + driverKind: input.evaluation.driverKind, + model: input.candidate.model, + ...(input.candidate.options === undefined ? {} : { options: input.candidate.options }), + isolation: input.candidate.isolation ?? "shared", + ...(input.candidate.runtimeMode === undefined + ? {} + : { runtimeMode: input.candidate.runtimeMode }), + ...(input.candidate.interactionMode === undefined + ? {} + : { interactionMode: input.candidate.interactionMode }), + eligibility: "eligible-at-resolution", +}); + +type LayerEvaluation = + | { + readonly kind: "selected"; + readonly candidateIndex: number; + readonly candidate: RuntimeRouteCandidate; + readonly resolved: RuntimeResolvedRoute; + } + | { readonly kind: "exhausted" }; + +export function resolveRuntimeRoute(input: ResolveRuntimeRouteInput): RuntimeRouteResolution { + const role: RuntimeWorkerRole = + input.override?.role ?? input.task?.routing?.role ?? input.role ?? "implementation"; + const rejected: Array = []; + const revisions: RuntimeRouteRevisions = { + task: input.task?.revision ?? null, + projectRouting: input.projectRouting.revision, + profile: + input.profile === null + ? null + : { profileId: input.profile.profileId, revision: input.profile.revision }, + assignment: + input.assignment === null + ? null + : { + projectId: input.assignment.projectId, + profileId: input.assignment.profileId, + revision: input.assignment.revision, + }, + }; + const base = { + projectId: input.projectId, + taskId: input.task?.taskId ?? null, + role, + revisions, + rejected, + }; + + const evaluateLayer = ( + source: RouteLayer, + route: Pick | Pick, + ): LayerEvaluation => { + for (const [candidateIndex, candidate] of route.candidates.entries()) { + const evaluation = evaluateRuntimeRouteCandidate(candidate, input.eligibility); + if (evaluation.eligible) { + return { + kind: "selected", + candidateIndex, + candidate, + resolved: selectedRoute({ source, candidateIndex, candidate, evaluation }), + }; + } + rejected.push({ + source, + candidateIndex, + candidate, + reason: evaluation.reason, + ...(evaluation.detail === undefined ? {} : { detail: boundedDetail(evaluation.detail) }), + }); + } + return { kind: "exhausted" }; + }; + + const inherited = (inheritedFrom: RuntimeRouteSource | null): RuntimeRouteResolution => ({ + ...base, + status: "inherited", + source: "inherit", + selected: null, + inheritedFrom, + failure: null, + }); + + const failed = ( + source: RuntimeRouteSource, + reason: RuntimeRouteFailureReason, + ): RuntimeRouteResolution => ({ + ...base, + status: "failed", + source, + selected: null, + inheritedFrom: null, + failure: { source, reason }, + }); + + const resolved = (evaluation: Extract) => ({ + ...base, + status: "resolved" as const, + source: evaluation.resolved.source, + selected: evaluation.resolved, + inheritedFrom: null, + failure: null, + }); + + const continuation = ( + evaluation: LayerEvaluation, + source: RouteLayer, + fallback: RuntimeRoutingFallback, + ): RuntimeRouteResolution | null => { + if (evaluation.kind === "selected") return resolved(evaluation); + switch (fallback) { + case "continue": + return null; + case "inherit": + return inherited(source); + case "fail": + return failed(source, "candidates_exhausted"); + } + }; + + if (input.override !== undefined) { + const { candidate } = input.override; + const evaluation = evaluateRuntimeRouteCandidate(candidate, input.eligibility); + if (evaluation.eligible) { + return resolved({ + kind: "selected", + candidateIndex: 0, + candidate, + resolved: selectedRoute({ + source: "explicit", + candidateIndex: 0, + candidate, + evaluation, + }), + }); + } + rejected.push({ + source: "explicit", + candidateIndex: 0, + candidate, + reason: evaluation.reason, + ...(evaluation.detail === undefined ? {} : { detail: boundedDetail(evaluation.detail) }), + }); + return failed("explicit", "explicit_override_unavailable"); + } + + let lastMatched: RouteLayer | null = null; + + const taskRouting = input.task?.routing; + if (taskRouting !== undefined && taskRouting.role === role) { + lastMatched = "task"; + const outcome = continuation(evaluateLayer("task", taskRouting), "task", taskRouting.fallback); + if (outcome !== null) return outcome; + } + + const projectRoute = findProjectRoute(input.projectRouting.routing, role); + if (projectRoute !== undefined) { + lastMatched = "project"; + const outcome = continuation( + evaluateLayer("project", projectRoute), + "project", + projectRoute.fallback, + ); + if (outcome !== null) return outcome; + } + + const profileRoute = findProfileRoute(input.profile?.routing ?? null, role); + if (profileRoute !== undefined) { + lastMatched = "profile"; + const evaluation = evaluateLayer("profile", profileRoute); + if (evaluation.kind === "selected") return resolved(evaluation); + return profileRoute.fallback === "fail" + ? failed("profile", "candidates_exhausted") + : inherited("profile"); + } + + return inherited(lastMatched); +} diff --git a/apps/server/src/runtimeRouting/RuntimeRoutingService.test.ts b/apps/server/src/runtimeRouting/RuntimeRoutingService.test.ts new file mode 100644 index 000000000000..554cafcae5c1 --- /dev/null +++ b/apps/server/src/runtimeRouting/RuntimeRoutingService.test.ts @@ -0,0 +1,321 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { + DEFAULT_SERVER_SETTINGS, + ProjectId, + ProjectRuntimeRoutingConflictError, + ProviderDriverKind, + ProviderInstanceId, + ProjectRuntimeTaskId, + type RuntimeRoutingPolicy, + type ServerProvider, + type ServerProviderModel, + type ServerSettings, +} from "@t3tools/contracts"; +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Result from "effect/Result"; +import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/sql/SqlClient"; + +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import { RuntimeRoutingProviderView } from "./RuntimeRoutingProviderView.ts"; +import * as RuntimeRoutingService from "./RuntimeRoutingService.ts"; + +const projectA = ProjectId.make("routing-a"); +const projectB = ProjectId.make("routing-b"); +const codex = ProviderInstanceId.make("codex"); +const timestamp = "2026-10-27T00:00:00.000Z"; + +const model = (slug: string): ServerProviderModel => ({ + slug, + name: slug, + isCustom: false, + capabilities: null, +}); + +const provider = (overrides: Partial = {}): ServerProvider => ({ + instanceId: codex, + driver: ProviderDriverKind.make("codex"), + enabled: true, + installed: true, + version: "1.0.0", + status: "ready", + auth: { status: "authenticated" }, + checkedAt: timestamp, + models: [model("gpt-6")], + slashCommands: [], + skills: [], + ...overrides, +}); + +const candidate = { + providerInstanceId: codex, + model: "gpt-6", +}; + +const routing = (fallback: "continue" | "inherit" | "fail" = "inherit"): RuntimeRoutingPolicy => ({ + roleRoutes: [{ role: "implementation", candidates: [candidate], fallback }], +}); + +const seedProjects = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + for (const [projectId, title] of [ + [projectA, "Alpha"], + [projectB, "Beta"], + ] as const) { + yield* sql`INSERT INTO projection_projects (project_id, title, workspace_root, scripts_json, created_at, updated_at) + VALUES (${projectId}, ${title}, ${`/work/${projectId}`}, '[]', ${timestamp}, ${timestamp})`; + } +}); + +interface ViewState { + readonly providers: ReadonlyArray; + readonly settings: ServerSettings; + readonly orchestrationCapableInstanceIds: ReadonlySet; +} + +const layerFor = (state: ViewState) => + RuntimeRoutingService.layer.pipe( + Layer.provide( + Layer.succeed(RuntimeRoutingProviderView, { + read: Effect.succeed(state), + }), + ), + Layer.provideMerge(SqlitePersistence.layerMemory), + Layer.provide(NodeServices.layer), + ); + +const defaultState: ViewState = { + providers: [provider()], + settings: DEFAULT_SERVER_SETTINGS, + orchestrationCapableInstanceIds: new Set([codex]), +}; + +it.effect("saves, resets, and compare-and-sets project routing", () => + Effect.gen(function* () { + yield* seedProjects; + const service = yield* RuntimeRoutingService.RuntimeRoutingService; + + assert.isNull(yield* service.readProjectRouting(projectA)); + const saved = yield* service.saveProjectRouting(projectA, { + routing: routing(), + expectedRevision: 0, + }); + assert.equal(saved.revision, 1); + assert.deepEqual(yield* service.readProjectRouting(projectA), saved); + + const stale = yield* service + .saveProjectRouting(projectA, { routing: routing("fail"), expectedRevision: 0 }) + .pipe(Effect.flip); + assert.instanceOf(stale, ProjectRuntimeRoutingConflictError); + if (stale._tag === "ProjectRuntimeRoutingConflictError") { + assert.equal(stale.currentRevision, 1); + } + assert.deepEqual(yield* service.readProjectRouting(projectA), saved); + + const reset = yield* service.saveProjectRouting(projectA, { + routing: null, + expectedRevision: 1, + }); + assert.equal(reset.revision, 2); + assert.isNull(reset.routing); + assert.deepEqual(yield* service.readProjectRouting(projectA), reset); + + // The reset row stays, so a writer holding revision 1 cannot recreate the override. + const staleAfterReset = yield* service + .saveProjectRouting(projectA, { routing: routing(), expectedRevision: 1 }) + .pipe(Effect.flip); + assert.instanceOf(staleAfterReset, ProjectRuntimeRoutingConflictError); + assert.isNull((yield* service.readProjectRouting(projectA))?.routing); + }).pipe(Effect.provide(layerFor(defaultState))), +); + +it.effect("types the loser of two simultaneous initial writers as a conflict", () => + Effect.gen(function* () { + yield* seedProjects; + const service = yield* RuntimeRoutingService.RuntimeRoutingService; + const attempts = yield* Effect.forEach( + [ + service.saveProjectRouting(projectA, { routing: routing(), expectedRevision: 0 }), + service.saveProjectRouting(projectA, { routing: routing("fail"), expectedRevision: 0 }), + ], + (effect) => Effect.result(effect), + { concurrency: 2 }, + ); + assert.equal(attempts.filter(Result.isSuccess).length, 1); + const failure = attempts.find(Result.isFailure); + assert.isDefined(failure); + assert.instanceOf(failure!.failure, ProjectRuntimeRoutingConflictError); + assert.equal((yield* service.readProjectRouting(projectA))?.revision, 1); + }).pipe(Effect.provide(layerFor(defaultState))), +); + +it.effect("isolates project routing rows and lets only one stale writer win", () => + Effect.gen(function* () { + yield* seedProjects; + const service = yield* RuntimeRoutingService.RuntimeRoutingService; + yield* service.saveProjectRouting(projectA, { + routing: routing(), + expectedRevision: 0, + }); + yield* service.saveProjectRouting(projectB, { + routing: routing("fail"), + expectedRevision: 0, + }); + + const attempts = yield* Effect.forEach( + [ + service.saveProjectRouting(projectA, { routing: routing("fail"), expectedRevision: 1 }), + service.saveProjectRouting(projectA, { routing: routing("continue"), expectedRevision: 1 }), + ], + (effect) => Effect.result(effect), + { concurrency: 2 }, + ); + const successes = attempts.filter(Result.isSuccess); + assert.equal(successes.length, 1); + const current = yield* service.readProjectRouting(projectA); + assert.equal(current?.revision, 2); + assert.equal((yield* service.readProjectRouting(projectB))?.revision, 1); + }).pipe(Effect.provide(layerFor(defaultState))), +); + +it.effect("resolves profile routing read from durable state", () => + Effect.gen(function* () { + yield* seedProjects; + const sql = yield* SqlClient.SqlClient; + const profileId = "routing-profile"; + yield* sql`INSERT INTO development_profiles + (profile_id, name, instructions, routing_json, revision, created_at, updated_at, created_by, updated_by) + VALUES (${profileId}, 'Policy', 'Instructions', ${JSON.stringify(routing())}, 1, ${timestamp}, ${timestamp}, 'user:test', 'user:test')`; + yield* sql`INSERT INTO project_development_profiles + (project_id, profile_id, revision, created_at, updated_at) + VALUES (${projectA}, ${profileId}, 3, ${timestamp}, ${timestamp})`; + + const resolution = yield* (yield* RuntimeRoutingService.RuntimeRoutingService).resolveRoute({ + projectId: projectA, + }); + assert.equal(resolution.status, "resolved"); + assert.equal(resolution.source, "profile"); + assert.equal(resolution.selected?.providerInstanceId, codex); + assert.equal(resolution.revisions.profile?.revision, 1); + assert.equal(resolution.revisions.assignment?.revision, 3); + }).pipe(Effect.provide(layerFor(defaultState))), +); + +it.effect("resolves task routing without changing saved project policy", () => + Effect.gen(function* () { + yield* seedProjects; + const sql = yield* SqlClient.SqlClient; + const service = yield* RuntimeRoutingService.RuntimeRoutingService; + yield* sql`INSERT INTO project_runtime (project_id, enabled, revision, created_at, updated_at) + VALUES (${projectA}, 0, 1, ${timestamp}, ${timestamp})`; + yield* sql`INSERT INTO project_runtime_tasks + (task_id, project_id, status, revision, created_at, payload_json) + VALUES ('task-1', ${projectA}, 'ready', 3, ${timestamp}, ${JSON.stringify({ + taskId: "task-1", + projectId: projectA, + title: "Route the task", + scope: "Routing", + owner: "user:test", + acceptanceCriteria: [], + status: "ready", + blocker: null, + verification: { milestone: "none", evidence: [] }, + latestHandoffId: null, + routing: routing("fail").roleRoutes[0], + revision: 3, + createdAt: timestamp, + updatedAt: timestamp, + createdBy: "user:test", + updatedBy: "user:test", + })})`; + yield* service.saveProjectRouting(projectA, { + routing: routing("inherit"), + expectedRevision: 0, + }); + + const resolution = yield* service.resolveRoute({ + projectId: projectA, + taskId: ProjectRuntimeTaskId.make("task-1"), + }); + assert.equal(resolution.status, "resolved"); + assert.equal(resolution.source, "task"); + assert.equal(resolution.revisions.task, 3); + assert.equal((yield* service.readProjectRouting(projectA))?.revision, 1); + }).pipe(Effect.provide(layerFor(defaultState))), +); + +it.effect("keeps a saved route when its provider is temporarily unavailable", () => + Effect.gen(function* () { + yield* seedProjects; + const service = yield* RuntimeRoutingService.RuntimeRoutingService; + const saved = yield* service.saveProjectRouting(projectA, { + routing: routing("fail"), + expectedRevision: 0, + }); + + const resolution = yield* service.resolveRoute({ projectId: projectA }); + assert.equal(resolution.status, "failed"); + assert.equal(resolution.rejected[0]?.reason, "provider_unavailable"); + assert.deepEqual(yield* service.readProjectRouting(projectA), saved); + }).pipe( + Effect.provide( + layerFor({ + ...defaultState, + providers: [ + provider({ availability: "unavailable", unavailableReason: "Provider is offline." }), + ], + }), + ), + ), +); + +it.effect("reports a project-disabled provider without changing policy", () => + Effect.gen(function* () { + yield* seedProjects; + const service = yield* RuntimeRoutingService.RuntimeRoutingService; + const saved = yield* service.saveProjectRouting(projectA, { + routing: routing("fail"), + expectedRevision: 0, + }); + const resolution = yield* service.resolveRoute({ projectId: projectA }); + assert.equal(resolution.status, "failed"); + assert.equal(resolution.rejected[0]?.reason, "provider_instance_disabled_for_project"); + assert.deepEqual(yield* service.readProjectRouting(projectA), saved); + }).pipe( + Effect.provide( + layerFor({ + ...defaultState, + settings: { + ...DEFAULT_SERVER_SETTINGS, + projectSettingsOverrides: { + [projectA]: { providerInstances: { [codex]: { enabled: false } } }, + }, + }, + }), + ), + ), +); + +it.effect("reports a missing configured model without deleting the route", () => + Effect.gen(function* () { + yield* seedProjects; + const service = yield* RuntimeRoutingService.RuntimeRoutingService; + const saved = yield* service.saveProjectRouting(projectA, { + routing: { + roleRoutes: [ + { + role: "implementation", + candidates: [{ providerInstanceId: codex, model: "removed-model" }], + fallback: "fail", + }, + ], + }, + expectedRevision: 0, + }); + const resolution = yield* service.resolveRoute({ projectId: projectA }); + assert.equal(resolution.status, "failed"); + assert.equal(resolution.rejected[0]?.reason, "model_unavailable"); + assert.deepEqual(yield* service.readProjectRouting(projectA), saved); + }).pipe(Effect.provide(layerFor(defaultState))), +); diff --git a/apps/server/src/runtimeRouting/RuntimeRoutingService.ts b/apps/server/src/runtimeRouting/RuntimeRoutingService.ts new file mode 100644 index 000000000000..beec2880e304 --- /dev/null +++ b/apps/server/src/runtimeRouting/RuntimeRoutingService.ts @@ -0,0 +1,314 @@ +import { + DevelopmentProfile, + ProjectDevelopmentProfile, + ProjectId, + ProjectRuntimeNotFoundError, + ProjectRuntimeRouting, + ProjectRuntimeRoutingConflictError, + ProjectRuntimeRoutingSaveInput, + ProjectRuntimeTask, + RuntimeProfileRoutingPolicy, + RuntimeRouteResolution, + RuntimeRouteResolutionInput, + RuntimeRoutingPolicy, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; +import { type SqlError } from "effect/sql/SqlError"; + +import { PersistenceSqlError } from "../persistence/Errors.ts"; +import { ProjectNotFoundError } from "../project/ProjectService.ts"; +import { RuntimeRoutingProviderView } from "./RuntimeRoutingProviderView.ts"; +import { resolveRuntimeRoute } from "./RuntimeRoutingResolver.ts"; + +const RoutingJson = Schema.fromJsonString(RuntimeRoutingPolicy); +const ProfileRoutingJson = Schema.fromJsonString(RuntimeProfileRoutingPolicy); +const TaskJson = Schema.fromJsonString(ProjectRuntimeTask); +const decodeTask = Schema.decodeUnknownEffect(TaskJson); +const AssignmentJson = Schema.decodeUnknownEffect(ProjectDevelopmentProfile); +const ProfileJson = Schema.decodeUnknownEffect(DevelopmentProfile); +const decodeProjectId = Schema.decodeUnknownEffect(ProjectId); +const decodeRoutingSaveInput = Schema.decodeUnknownEffect(ProjectRuntimeRoutingSaveInput); +const decodeResolutionInput = Schema.decodeUnknownEffect(RuntimeRouteResolutionInput); +const encodeRouting = Schema.encodeEffect(RoutingJson); +const decodeRouting = Schema.decodeUnknownEffect(RoutingJson); +const decodeProfileRouting = Schema.decodeUnknownEffect(ProfileRoutingJson); +const now = DateTime.now.pipe(Effect.map(DateTime.formatIso)); + +type ServiceError = + | ProjectNotFoundError + | ProjectRuntimeNotFoundError + | ProjectRuntimeRoutingConflictError + | PersistenceSqlError + | Schema.SchemaError; +type Result = Effect.Effect; + +type RoutingRow = { + readonly project_id: string; + readonly routing_json: string | null; + readonly revision: number; + readonly created_at: string; + readonly updated_at: string; +}; + +const emptyProfileRouting = (): RuntimeProfileRoutingPolicy => ({ roleRoutes: [] }); + +export class RuntimeRoutingService extends Context.Service< + RuntimeRoutingService, + { + /** Null means the project has no routing row; a reset row has `routing: null`. */ + readonly readProjectRouting: (projectId: ProjectId) => Result; + readonly saveProjectRouting: ( + projectId: ProjectId, + input: ProjectRuntimeRoutingSaveInput, + ) => Result; + readonly resolveRoute: (input: RuntimeRouteResolutionInput) => Result; + } +>()("t3/runtimeRouting/RuntimeRoutingService") {} + +const make = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const providerView = yield* RuntimeRoutingProviderView; + const sqlErrors = (effect: Effect.Effect) => + effect.pipe( + Effect.catchTags({ + SqlError: (cause) => + Effect.fail(new PersistenceSqlError({ operation: "runtimeRouting", cause })), + }), + ); + + const requireProject = Effect.fn("RuntimeRoutingService.requireProject")(function* ( + projectId: ProjectId, + ) { + const rows = + yield* sql`SELECT project_id FROM projection_projects WHERE project_id = ${projectId} AND deleted_at IS NULL`; + if (rows.length === 0) { + return yield* new ProjectNotFoundError({ projectId }); + } + }); + + const readRoutingRow = Effect.fn("RuntimeRoutingService.readRoutingRow")(function* ( + projectId: ProjectId, + ) { + const rows = yield* sql`SELECT + project_id, routing_json, revision, created_at, updated_at + FROM project_runtime_routing WHERE project_id = ${projectId}`; + return rows[0] ?? null; + }); + + const toRouting = Effect.fn("RuntimeRoutingService.toRouting")(function* (row: RoutingRow) { + return { + projectId: ProjectId.make(row.project_id), + routing: row.routing_json === null ? null : yield* decodeRouting(row.routing_json), + revision: row.revision, + createdAt: row.created_at, + updatedAt: row.updated_at, + }; + }); + + const readProjectRouting: RuntimeRoutingService["Service"]["readProjectRouting"] = Effect.fn( + "RuntimeRoutingService.readProjectRouting", + )( + function* (projectId) { + const id = yield* decodeProjectId(projectId); + yield* requireProject(id); + const row = yield* readRoutingRow(id); + return row === null ? null : yield* toRouting(row); + }, + sql.withTransaction, + sqlErrors, + ); + + const saveProjectRouting: RuntimeRoutingService["Service"]["saveProjectRouting"] = Effect.fn( + "RuntimeRoutingService.saveProjectRouting", + )( + function* (projectId, input) { + const id = yield* decodeProjectId(projectId); + const data = yield* decodeRoutingSaveInput(input); + yield* requireProject(id); + const existing = yield* readRoutingRow(id); + const currentRevision = existing?.revision ?? 0; + if (data.expectedRevision !== currentRevision) { + return yield* new ProjectRuntimeRoutingConflictError({ + projectId: id, + expectedRevision: data.expectedRevision, + currentRevision, + }); + } + const timestamp = yield* now; + const routingJson = data.routing === null ? null : yield* encodeRouting(data.routing); + if (existing === null) { + const inserted = yield* sql`INSERT INTO project_runtime_routing + (project_id, routing_json, revision, created_at, updated_at) + VALUES (${id}, ${routingJson}, 1, ${timestamp}, ${timestamp}) + ON CONFLICT (project_id) DO NOTHING + RETURNING project_id`; + if (inserted.length !== 1) { + const current = yield* readRoutingRow(id); + return yield* new ProjectRuntimeRoutingConflictError({ + projectId: id, + expectedRevision: data.expectedRevision, + currentRevision: current?.revision ?? 0, + }); + } + return { + projectId: id, + routing: data.routing, + revision: 1, + createdAt: timestamp, + updatedAt: timestamp, + }; + } + const changed = yield* sql`UPDATE project_runtime_routing + SET routing_json = ${routingJson}, revision = revision + 1, updated_at = ${timestamp} + WHERE project_id = ${id} AND revision = ${data.expectedRevision} + RETURNING project_id`; + if (changed.length !== 1) { + const current = yield* readRoutingRow(id); + return yield* new ProjectRuntimeRoutingConflictError({ + projectId: id, + expectedRevision: data.expectedRevision, + currentRevision: current?.revision ?? 0, + }); + } + return { + projectId: id, + routing: data.routing, + revision: existing.revision + 1, + createdAt: existing.created_at, + updatedAt: timestamp, + }; + }, + sql.withTransaction, + sqlErrors, + ); + + const readTask = Effect.fn("RuntimeRoutingService.readTask")(function* ( + projectId: ProjectId, + taskId: NonNullable, + ) { + const rows = yield* sql<{ readonly payload_json: string }>`SELECT payload_json + FROM project_runtime_tasks WHERE project_id = ${projectId} AND task_id = ${taskId}`; + if (rows[0] === undefined) { + return yield* new ProjectRuntimeNotFoundError({ + projectId, + entity: "task", + entityId: taskId, + }); + } + return yield* decodeTask(rows[0].payload_json); + }); + + const readAssignment = Effect.fn("RuntimeRoutingService.readAssignment")(function* ( + projectId: ProjectId, + ) { + const rows = yield* sql<{ + readonly project_id: string; + readonly profile_id: string | null; + readonly revision: number; + readonly created_at: string; + readonly updated_at: string; + }>`SELECT project_id, profile_id, revision, created_at, updated_at + FROM project_development_profiles WHERE project_id = ${projectId}`; + const row = rows[0]; + return row === undefined + ? null + : yield* AssignmentJson({ + projectId: row.project_id, + profileId: row.profile_id, + revision: row.revision, + createdAt: row.created_at, + updatedAt: row.updated_at, + }); + }); + + const readProfile = Effect.fn("RuntimeRoutingService.readProfile")(function* (profileId: string) { + const rows = yield* sql<{ + readonly profile_id: string; + readonly name: string; + readonly instructions: string; + readonly routing_json: string | null; + readonly revision: number; + readonly created_at: string; + readonly updated_at: string; + readonly created_by: string; + readonly updated_by: string; + }>`SELECT profile_id, name, instructions, routing_json, revision, created_at, updated_at, + created_by, updated_by + FROM development_profiles WHERE profile_id = ${profileId}`; + if (rows[0] === undefined) return null; + const row = rows[0]; + const routing = + row.routing_json === null + ? emptyProfileRouting() + : yield* decodeProfileRouting(row.routing_json); + return yield* ProfileJson({ + profileId: row.profile_id, + name: row.name, + instructions: row.instructions, + routing, + revision: row.revision, + createdAt: row.created_at, + updatedAt: row.updated_at, + createdBy: row.created_by, + updatedBy: row.updated_by, + }); + }); + + const resolveRoute: RuntimeRoutingService["Service"]["resolveRoute"] = Effect.fn( + "RuntimeRoutingService.resolveRoute", + )( + function* (input) { + const data = yield* decodeResolutionInput(input); + const projectId = data.projectId; + yield* requireProject(projectId); + const routingRow = yield* readRoutingRow(projectId); + const projectRouting = + routingRow === null + ? { routing: null, revision: 0 } + : { + routing: + routingRow.routing_json === null + ? null + : yield* decodeRouting(routingRow.routing_json), + revision: routingRow.revision, + }; + const task = data.taskId === undefined ? null : yield* readTask(projectId, data.taskId); + const assignment = yield* readAssignment(projectId); + const profile = + assignment === null || assignment.profileId === null + ? null + : yield* readProfile(assignment.profileId); + const providerState = yield* providerView.read; + return resolveRuntimeRoute({ + projectId, + task, + projectRouting, + profile, + assignment, + ...(data.role === undefined ? {} : { role: data.role }), + ...(data.override === undefined ? {} : { override: data.override }), + eligibility: { + projectId, + providers: providerState.providers, + orchestrationCapableInstanceIds: providerState.orchestrationCapableInstanceIds, + settings: providerState.settings, + }, + }); + }, + sql.withTransaction, + sqlErrors, + ); + + return RuntimeRoutingService.of({ + readProjectRouting, + saveProjectRouting, + resolveRoute, + }); +}); + +export const layer = Layer.effect(RuntimeRoutingService, make); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 0ac85bc89225..1aa60f049799 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -102,6 +102,8 @@ import * as T3ProjectFileLoader from "./project/T3ProjectFileLoader.ts"; import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts"; import * as ProjectRuntimeService from "./projectRuntime/ProjectRuntimeService.ts"; import * as ProjectRuntimeSourceAccess from "./projectRuntime/ProjectRuntimeSourceAccess.ts"; +import * as RuntimeRoutingProviderView from "./runtimeRouting/RuntimeRoutingProviderView.ts"; +import * as RuntimeRoutingService from "./runtimeRouting/RuntimeRoutingService.ts"; import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts"; import * as KnownWorkspaces from "./workspace/KnownWorkspaces.ts"; import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts"; @@ -707,6 +709,9 @@ const layerCommandReadiness = HttpRouter.middleware( const layerProjectRuntime = ProjectRuntimeSourceAccess.layer.pipe( Layer.provideMerge(ProjectRuntimeService.layer), Layer.provideMerge(DevelopmentProfileService.layer), + Layer.provideMerge( + RuntimeRoutingService.layer.pipe(Layer.provide(RuntimeRoutingProviderView.layer)), + ), ); const layerMakeRoutes = Layer.mergeAll( diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index d1ebc332ee27..89b259b062be 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -1,6 +1,7 @@ import * as DevelopmentProfileService from "./developmentProfiles/DevelopmentProfileService.ts"; import * as ProjectRuntimeService from "./projectRuntime/ProjectRuntimeService.ts"; import * as ProjectRuntimeSourceAccess from "./projectRuntime/ProjectRuntimeSourceAccess.ts"; +import * as RuntimeRoutingService from "./runtimeRouting/RuntimeRoutingService.ts"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { @@ -399,6 +400,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(ProjectRuntimeService.ProjectRuntimeService)({}), Layer.mock(DevelopmentProfileService.DevelopmentProfileService)({}), Layer.mock(ProjectRuntimeSourceAccess.ProjectRuntimeSourceAccess)({}), + Layer.mock(RuntimeRoutingService.RuntimeRoutingService)({}), Layer.mock(DocumentText.DocumentText)({}), Layer.mock(ServerSecretStore.ServerSecretStore)({}), Layer.mock(WorkspacePaths.WorkspacePaths)({}), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 1740143c9c07..d5fa2bf571eb 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2,6 +2,7 @@ import * as DevelopmentProfileService from "./developmentProfiles/DevelopmentPro import * as DevelopmentProfileRpc from "./developmentProfiles/DevelopmentProfileRpc.ts"; import * as ProjectRuntimeService from "./projectRuntime/ProjectRuntimeService.ts"; import * as ProjectRuntimeSourceAccess from "./projectRuntime/ProjectRuntimeSourceAccess.ts"; +import * as RuntimeRoutingService from "./runtimeRouting/RuntimeRoutingService.ts"; import * as ProjectRuntimeRpc from "./projectRuntime/ProjectRuntimeRpc.ts"; import { OrchestrationDispatchCommandError } from "@t3tools/contracts"; import * as Context from "effect/Context"; @@ -3312,6 +3313,7 @@ export const layer = Layer.unwrap( const developmentProfiles = yield* DevelopmentProfileService.DevelopmentProfileService; const projectRuntime = yield* ProjectRuntimeService.ProjectRuntimeService; const runtimeSources = yield* ProjectRuntimeSourceAccess.ProjectRuntimeSourceAccess; + const runtimeRouting = yield* RuntimeRoutingService.RuntimeRoutingService; const previewAutomationBroker = yield* PreviewAutomationBroker.PreviewAutomationBroker; const serverBrowser = yield* ServerBrowser.ServerBrowser; const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate; @@ -3398,6 +3400,9 @@ export const layer = Layer.unwrap( Layer.provide( Layer.succeed(ProjectRuntimeService.ProjectRuntimeService, projectRuntime), ), + Layer.provide( + Layer.succeed(RuntimeRoutingService.RuntimeRoutingService, runtimeRouting), + ), Layer.provide( Layer.succeed( ProjectRuntimeSourceAccess.ProjectRuntimeSourceAccess, diff --git a/apps/web/src/components/forkHome/ForkHome.browser.test.tsx b/apps/web/src/components/forkHome/ForkHome.browser.test.tsx index 5dbb54c928a3..b10cc7ee0194 100644 --- a/apps/web/src/components/forkHome/ForkHome.browser.test.tsx +++ b/apps/web/src/components/forkHome/ForkHome.browser.test.tsx @@ -136,6 +136,7 @@ const effective: EffectiveProjectInstructions = { profileId: DevelopmentProfileId.make("profile"), name: "Shared engineering policy", instructions: "Use the shared policy.", + routing: { roleRoutes: [] }, revision: 1, createdAt: time, updatedAt: time, diff --git a/docs/internals/project-runtime.md b/docs/internals/project-runtime.md index 00a67869f7ea..20ae0e338112 100644 --- a/docs/internals/project-runtime.md +++ b/docs/internals/project-runtime.md @@ -25,7 +25,7 @@ provider, or worktree. | [Provider bootstrap](../../packages/provider-core/src/server/orchestrationInstructions.ts) | The shared, provider-neutral `Project Runtime` instruction section. | | [Turn context](../../packages/provider-core/src/server/turnContext.ts) | Authority, ordering, bounds, and chunking for turn-scoped context that never enters provider session identity. | | [Transport and UI](../../apps/server/src/projectRuntime/ProjectRuntimeRpc.ts) | WebSocket handlers; the web client lives under [settings](../../apps/web/src/components/settings/ProjectRuntimeSettings.tsx). | -| [Fork migrations](../../apps/server/src/persistence/ForkMigrations.ts) | The isolated fork ledger, historical reconciliation, and the three Runtime, Profile, and Task/Handoff migrations. | +| [Fork migrations](../../apps/server/src/persistence/ForkMigrations.ts) | The isolated fork ledger, historical reconciliation, and the four Runtime, Profile, Task/Handoff, and Routing migrations. | ## Persistence and deletion @@ -217,6 +217,15 @@ Claude's read-only T3 MCP allowlist remains a provider-specific seam; a future Runtime read tool must be added there and to its test. Write tools are not pre-approved. +## Routing + +Runtime tasks, projects, and Development Profiles can carry structured worker +routes. Routing is configuration and resolution only: it selects and rejects +candidates but launches no worker. Precedence, fallback, eligibility, +persistence ownership, and concurrency are documented in +[Runtime routing](./runtime-routing.md). Routing is deliberately absent from the +MCP bootstrap and `t3_project_context`, so the agent-context budget is unchanged. + ## Extension points A new Runtime capability normally needs the contract and RPC, a service method, an diff --git a/docs/internals/runtime-routing.md b/docs/internals/runtime-routing.md new file mode 100644 index 000000000000..9e47c80d4b61 --- /dev/null +++ b/docs/internals/runtime-routing.md @@ -0,0 +1,112 @@ +# Runtime Routing + +Runtime routing is durable configuration, not execution. It answers which +provider, model, isolation, and modes a Runtime task would use, and why, without +starting a worker, creating a thread, or calling `delegate_task`. The EventSink +hook and execution-attempt lifecycle belong to later work. + +The module is provider-neutral. It reuses the Orchestrator worker-role vocabulary +(`implementation`, `research`, `review`, `design`, `test`, `general`), upstream +provider instance/driver/model option types, and existing provider snapshots and +project settings. It does not keep a second provider catalog, poll provider +health, install anything, or authenticate anything. + +## Layers and precedence + +Routing resolves in this order: + +1. a one-run explicit override; +2. Runtime task routing; +3. project routing; +4. the assigned Development Profile's routing; +5. ordinary T3 inheritance. + +A layer participates only when it has an entry for the resolved worker role. A +one-run override role wins, then the task's routing role, then a caller-supplied +role, and the default is `implementation`. Project and profile routes are keyed +by role, so a layer with routes for other roles is skipped without affecting +resolution. + +Resolution reads durable routing even when Runtime is disabled; enablement is an +execution concern. RTE-040 must check it again before launching work. + +Each role entry is an ordered candidate list plus a fallback: + +| Fallback | When the candidates are exhausted | +| ---------- | --------------------------------------------------------------------------- | +| `continue` | Evaluate the next lower routing layer. | +| `inherit` | Stop and use ordinary T3 inheritance; do not evaluate lower routing layers. | +| `fail` | Refuse routing; never silently inherit. | + +The profile is the terminal routing layer, so its entries allow only `inherit` +and `fail`. Task and project entries allow all three. An empty candidate list is +meaningful: with `inherit` it deliberately disables routing for that role, and +with `fail` it requires a route that is not available. + +A one-run override is a single candidate. It is fail-closed: if it cannot run, +resolution fails instead of falling through to stored policy. RTE-020 exposes +that contract but does not consume it for execution. + +Candidate fields map to existing T3 concepts: provider instance or driver kind, +model, provider options, isolation, runtime mode, and interaction mode. A +driver-only candidate resolves to the first eligible instance in provider order, +so replacing an instance id does not require rewriting policy. + +## Eligibility is not authorization + +The resolver reuses the current provider snapshots, the live provider instance +registry, server settings with project overrides, and the same provider/model +option checks the Orchestrator already uses. It checks: + +- provider registration and driver match; +- a live orchestration-capable instance; +- project provider enablement, including project-specific disables; +- snapshot availability, enabled/installed state, status, and authentication; +- advertised model, model option selections, supported runtime modes, and plan + mode where the snapshot exposes those capabilities. + +A selected route is marked `eligible-at-resolution`. That is an observation, not +permission to launch. Settings, provider health, and authorization can change +before the Orchestrator starts work, so the launch path remains authoritative and +must recheck. The resolver deliberately performs no health probe, quota, price, +or account-identity check. + +Saved policy is never deleted or rewritten because a provider is temporarily +offline, a model is no longer advertised, or a project disabled an instance. +Resolution reports the rejection; the configuration remains for the next +resolution or for the user to repair. + +## Persistence and concurrency + +- **Profile routing** is a structured `routing` value in the profile record and + the profile's existing `revision` guards it. Instructions and routing change in + one compare-and-set write; omitting `routing` preserves the stored value. A + stale routing write cannot overwrite newer instructions. +- **Project routing** is one row per project with its own revision. Resetting the + override writes `null` and increments the revision instead of deleting the row, + so a stale writer cannot recreate an old override. Project routing is separate + from Project Instructions and does not depend on Runtime being enabled. +- **Task routing** is optional task state in the task payload. It uses the normal + task revision and update path, so routing changes are protected by the same + compare-and-set as every other task edit. + +Project and profile routing are settings, not agent context. They are never +injected into provider prompts or `t3_project_context`; the agent-context budget +is unchanged. Agent-facing Runtime task tools also omit the routing field in this +gate, because every field added to those schemas expands the tool prompt. Routing +is user/orchestrator configuration until execution exists. Profiles still apply +independently of Runtime enablement, and one profile still applies per project +with no inheritance chains. Agents cannot edit profiles through MCP. + +Fork migration `4_RuntimeRouting` adds the profile routing column and the +project-routing row with its soft-deletion trigger. Existing profiles and +projects read as "no routing"; task routing needs no migration because it is an +optional payload field. Fork history stays in the fork ledger, and upstream +migration ids are untouched. + +## Not executed here + +RTE-020 does not launch child threads, create execution attempts, write routing +receipts, cancel or restart work, expose execution MCP tools, or add Project Home +execution summaries. It does not add a scheduler, worktree ownership, cost/quota +routing, cross-environment routing, or automatic role classification. diff --git a/docs/user/development-profiles.md b/docs/user/development-profiles.md index 84577c7a2ce7..58bc855282b8 100644 --- a/docs/user/development-profiles.md +++ b/docs/user/development-profiles.md @@ -39,6 +39,6 @@ at the same repository starts without an assignment. V1 supports one profile per project and no profile inheritance chains. Profiles are user-managed settings: agents cannot create, edit, delete, assign, or remove -them through MCP. There is no automatic memory, provider-specific policy, or -synchronization between environments. Configuration is available on web and desktop; +them through MCP. There is no automatic memory or synchronization between +environments. Configuration is available on web and desktop; native mobile does not have a Development Profiles settings screen. diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index b80bd669800e..004c596695d0 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -28,6 +28,7 @@ export const CLIENT_GUARDED_RPC_SCOPES = { [PROJECT_RUNTIME_RPC_METHODS.removeSource]: AuthOrchestrationOperateScope, [PROJECT_RUNTIME_RPC_METHODS.createTask]: AuthOrchestrationOperateScope, [PROJECT_RUNTIME_RPC_METHODS.updateTask]: AuthOrchestrationOperateScope, + [PROJECT_RUNTIME_RPC_METHODS.saveRouting]: AuthOrchestrationOperateScope, [WS_METHODS.previewClose]: AuthPreviewOperateScope, [WS_METHODS.serverRunStorageCleanup]: AuthSettingsWriteScope, diff --git a/packages/contracts/src/developmentProfiles.ts b/packages/contracts/src/developmentProfiles.ts index 5b8c3c53ac21..8d28f7d48d58 100644 --- a/packages/contracts/src/developmentProfiles.ts +++ b/packages/contracts/src/developmentProfiles.ts @@ -8,6 +8,7 @@ import { TrimmedNonEmptyString, } from "./baseSchemas.ts"; import { ProjectRuntimeInstructions } from "./projectRuntime.ts"; +import { RuntimeProfileRoutingPolicy } from "./runtimeRouting.ts"; import { DEVELOPMENT_PROFILE_BOUNDS } from "./developmentProfileBounds.ts"; export { DEVELOPMENT_PROFILE_BOUNDS } from "./developmentProfileBounds.ts"; @@ -34,6 +35,8 @@ export const DevelopmentProfile = Schema.Struct({ profileId: DevelopmentProfileId, name: DevelopmentProfileName, instructions: DevelopmentProfileInstructions, + /** Structured role routing defaults; instructions never encode routing. */ + routing: RuntimeProfileRoutingPolicy, revision: PositiveInt, createdAt: IsoDateTime, updatedAt: IsoDateTime, @@ -45,6 +48,7 @@ export type DevelopmentProfile = typeof DevelopmentProfile.Type; export const DevelopmentProfileCreateInput = Schema.Struct({ name: DevelopmentProfileName, instructions: DevelopmentProfileInstructions, + routing: Schema.optionalKey(RuntimeProfileRoutingPolicy), }); export type DevelopmentProfileCreateInput = typeof DevelopmentProfileCreateInput.Type; @@ -52,6 +56,8 @@ export const DevelopmentProfileUpdateInput = Schema.Struct({ profileId: DevelopmentProfileId, name: DevelopmentProfileName, instructions: DevelopmentProfileInstructions, + /** Omitted preserves the stored routing; the same revision guards both fields. */ + routing: Schema.optionalKey(RuntimeProfileRoutingPolicy), expectedRevision: PositiveInt, }); export type DevelopmentProfileUpdateInput = typeof DevelopmentProfileUpdateInput.Type; diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index be9396b4ea24..6da04552c457 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -48,7 +48,9 @@ export * from "./threadTitle.ts"; export * from "./t3ProjectFile.ts"; export * from "./editor.ts"; export * from "./project.ts"; +export * from "./runtimeRouting.ts"; export * from "./projectRuntime.ts"; +export * from "./runtimeRoutingResolution.ts"; export * from "./developmentProfiles.ts"; export * from "./filesystem.ts"; export * from "./agentSessions.ts"; diff --git a/packages/contracts/src/projectRuntime.ts b/packages/contracts/src/projectRuntime.ts index 9386168aad37..534daa450ee5 100644 --- a/packages/contracts/src/projectRuntime.ts +++ b/packages/contracts/src/projectRuntime.ts @@ -12,6 +12,7 @@ import { } from "./baseSchemas.ts"; import { ProviderInstanceId } from "./providerInstance.ts"; import { ProjectContentMatchRange } from "./project.ts"; +import { RuntimeRoleRoute } from "./runtimeRouting.ts"; export const PROJECT_RUNTIME_VERSION = 1 as const; @@ -480,6 +481,8 @@ export const ProjectRuntimeTask = Schema.Struct({ verification: ProjectRuntimeTaskVerification, latestHandoffId: Schema.NullOr(ProjectRuntimeHandoffId), nextAction: Schema.optionalKey(TaskNextAction), + /** Explicit worker role plus optional ordered candidates and layer fallback. */ + routing: Schema.optionalKey(RuntimeRoleRoute), revision: PositiveInt, createdAt: IsoDateTime, updatedAt: IsoDateTime, @@ -524,6 +527,7 @@ export const ProjectRuntimeTaskCreateInput = Schema.Struct({ result: Schema.optionalKey(TaskResult), verification: Schema.optionalKey(ProjectRuntimeTaskVerification), nextAction: Schema.optionalKey(TaskNextAction), + routing: Schema.optionalKey(RuntimeRoleRoute), }); export type ProjectRuntimeTaskCreateInput = typeof ProjectRuntimeTaskCreateInput.Type; @@ -550,6 +554,8 @@ export const ProjectRuntimeTaskUpdateInput = Schema.Struct({ verification: Schema.optionalKey(Schema.NullOr(ProjectRuntimeTaskVerification)), // Null clears the optional metadata; an omitted key leaves it unchanged. nextAction: Schema.optionalKey(Schema.NullOr(TaskNextAction)), + // Null clears task routing; an omitted key leaves the stored routing unchanged. + routing: Schema.optionalKey(Schema.NullOr(RuntimeRoleRoute)), }); export type ProjectRuntimeTaskUpdateInput = typeof ProjectRuntimeTaskUpdateInput.Type; diff --git a/packages/contracts/src/projectRuntimeRpc.ts b/packages/contracts/src/projectRuntimeRpc.ts index 9dc1920adac6..71c08e3daed2 100644 --- a/packages/contracts/src/projectRuntimeRpc.ts +++ b/packages/contracts/src/projectRuntimeRpc.ts @@ -25,6 +25,12 @@ import { ProjectRuntimeTaskReadInput, ProjectRuntimeTaskUpdateInput, } from "./projectRuntime.ts"; +import { + ProjectRuntimeRouting, + ProjectRuntimeRoutingSaveInput, + RuntimeRoutingError, +} from "./runtimeRouting.ts"; +import { RuntimeRouteResolution, RuntimeRouteResolutionInput } from "./runtimeRoutingResolution.ts"; export const PROJECT_RUNTIME_RPC_METHODS = { status: "projectRuntime.status", @@ -41,6 +47,9 @@ export const PROJECT_RUNTIME_RPC_METHODS = { updateTask: "projectRuntime.updateTask", listHandoffs: "projectRuntime.listHandoffs", readHandoff: "projectRuntime.readHandoff", + readRouting: "projectRuntime.readRouting", + saveRouting: "projectRuntime.saveRouting", + resolveRoute: "projectRuntime.resolveRoute", } as const; export class ProjectRuntimeRequestError extends Schema.TaggedError()( @@ -57,6 +66,7 @@ export class ProjectRuntimeRequestError extends Schema.TaggedError { + it("accepts an instance route and a driver-only route", () => { + expect(decodeCandidate(baseCandidate)).toEqual(baseCandidate); + expect(decodeCandidate({ driverKind: "opencode", model: "deepseek-v4.1-flash" })).toEqual({ + driverKind: "opencode", + model: "deepseek-v4.1-flash", + }); + }); + + it("requires a provider instance or driver", () => { + expect(() => decodeCandidate({ model: "gpt-6" })).toThrow(); + }); + + it("bounds candidates and rejects duplicate roles", () => { + const candidates = Array.from( + { length: RUNTIME_ROUTING_BOUNDS.candidatesPerRoleMax + 1 }, + () => baseCandidate, + ); + expect(() => decodePolicy({ roleRoutes: [{ ...baseRoute, candidates }] })).toThrow(); + expect(() => + decodePolicy({ + roleRoutes: [baseRoute, { ...baseRoute, role: "review" }, baseRoute], + }), + ).toThrow(); + }); + + it("does not let the terminal profile layer continue", () => { + expect(() => + decodeProfilePolicy({ + roleRoutes: [{ ...baseRoute, fallback: "continue" }], + }), + ).toThrow(); + expect( + decodeProfilePolicy({ + roleRoutes: [{ ...baseRoute, fallback: "fail" }], + }), + ).toEqual({ roleRoutes: [{ ...baseRoute, fallback: "fail" }] }); + }); + + it("carries task routing as ordinary task state", () => { + const input = decodeTaskCreate({ + title: "Route this", + scope: "Routing", + acceptanceCriteria: [], + routing: baseRoute, + }); + expect(input.routing).toEqual(baseRoute); + }); +}); diff --git a/packages/contracts/src/runtimeRouting.ts b/packages/contracts/src/runtimeRouting.ts new file mode 100644 index 000000000000..49655a844d5e --- /dev/null +++ b/packages/contracts/src/runtimeRouting.ts @@ -0,0 +1,138 @@ +import * as Schema from "effect/Schema"; + +import { IsoDateTime, NonNegativeInt, ProjectId, TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { ProviderOptionSelections } from "./model.ts"; +import { OrchestratorMcpTaskRole } from "./orchestratorMcp.ts"; +import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts"; +import { ProviderInteractionMode, RuntimeMode } from "./providerPolicy.ts"; + +/** + * Worker roles reuse the Orchestrator vocabulary so a route and a delegated + * task cannot drift into two competing role names for the same work. + */ +export const RuntimeWorkerRole = OrchestratorMcpTaskRole; +export type RuntimeWorkerRole = typeof RuntimeWorkerRole.Type; + +export const RUNTIME_ROUTING_BOUNDS = { + modelMaxLength: 200, + candidatesPerRoleMax: 20, + roleRoutesMax: 6, + rejectionsMax: 64, + rejectionDetailMaxLength: 300, +} as const; + +const RouteModel = TrimmedNonEmptyString.check( + Schema.isMaxLength(RUNTIME_ROUTING_BOUNDS.modelMaxLength), +); + +export const RuntimeRouteIsolation = Schema.Literals(["shared", "worktree"]); +export type RuntimeRouteIsolation = typeof RuntimeRouteIsolation.Type; + +/** + * A candidate names an instance or a driver. A driver-only candidate resolves + * to the first eligible instance in provider order, so saved policy does not + * have to pin an instance id that may be replaced later. + */ +export const RuntimeRouteCandidate = Schema.Struct({ + providerInstanceId: Schema.optionalKey(ProviderInstanceId), + driverKind: Schema.optionalKey(ProviderDriverKind), + model: RouteModel, + options: Schema.optionalKey(ProviderOptionSelections), + isolation: Schema.optionalKey(RuntimeRouteIsolation), + runtimeMode: Schema.optionalKey(RuntimeMode), + interactionMode: Schema.optionalKey(ProviderInteractionMode), +}).check( + Schema.makeFilter( + (candidate) => candidate.providerInstanceId !== undefined || candidate.driverKind !== undefined, + { expected: "a provider instance id or a driver kind" }, + ), +); +export type RuntimeRouteCandidate = typeof RuntimeRouteCandidate.Type; + +export const RuntimeRoutingFallback = Schema.Literals(["continue", "inherit", "fail"]); +export type RuntimeRoutingFallback = typeof RuntimeRoutingFallback.Type; + +/** + * The profile is the last routing layer. There is no lower layer for + * `continue` to reach, so it may only deliberately inherit or refuse. + */ +export const RuntimeProfileRoutingFallback = Schema.Literals(["inherit", "fail"]); +export type RuntimeProfileRoutingFallback = typeof RuntimeProfileRoutingFallback.Type; + +const RuntimeRouteCandidates = Schema.Array(RuntimeRouteCandidate).check( + Schema.isMaxLength(RUNTIME_ROUTING_BOUNDS.candidatesPerRoleMax), +); + +const uniqueRoleRoutes = Schema.makeFilter( + (routes: ReadonlyArray<{ readonly role: RuntimeWorkerRole }>) => + new Set(routes.map((route) => route.role)).size === routes.length, + { expected: "at most one route per worker role" }, +); + +export const RuntimeRoleRoute = Schema.Struct({ + role: RuntimeWorkerRole, + candidates: RuntimeRouteCandidates, + fallback: RuntimeRoutingFallback, +}); +export type RuntimeRoleRoute = typeof RuntimeRoleRoute.Type; + +export const RuntimeProfileRoleRoute = Schema.Struct({ + role: RuntimeWorkerRole, + candidates: RuntimeRouteCandidates, + fallback: RuntimeProfileRoutingFallback, +}); +export type RuntimeProfileRoleRoute = typeof RuntimeProfileRoleRoute.Type; + +/** Project and task routing may continue to a lower routing layer. */ +export const RuntimeRoutingPolicy = Schema.Struct({ + roleRoutes: Schema.Array(RuntimeRoleRoute).check( + Schema.isMaxLength(RUNTIME_ROUTING_BOUNDS.roleRoutesMax), + uniqueRoleRoutes, + ), +}); +export type RuntimeRoutingPolicy = typeof RuntimeRoutingPolicy.Type; + +/** Development Profile routing is the terminal routing layer. */ +export const RuntimeProfileRoutingPolicy = Schema.Struct({ + roleRoutes: Schema.Array(RuntimeProfileRoleRoute).check( + Schema.isMaxLength(RUNTIME_ROUTING_BOUNDS.roleRoutesMax), + uniqueRoleRoutes, + ), +}); +export type RuntimeProfileRoutingPolicy = typeof RuntimeProfileRoutingPolicy.Type; + +/** + * One row per project, kept after a reset so a stale writer cannot recreate an + * override from an old revision. A null routing value means inherit the profile. + */ +export const ProjectRuntimeRouting = Schema.Struct({ + projectId: ProjectId, + routing: Schema.NullOr(RuntimeRoutingPolicy), + revision: NonNegativeInt, + createdAt: IsoDateTime, + updatedAt: IsoDateTime, +}); +export type ProjectRuntimeRouting = typeof ProjectRuntimeRouting.Type; + +export const ProjectRuntimeRoutingSaveInput = Schema.Struct({ + routing: Schema.NullOr(RuntimeRoutingPolicy), + /** Zero means the project has no routing row yet. */ + expectedRevision: NonNegativeInt, +}); +export type ProjectRuntimeRoutingSaveInput = typeof ProjectRuntimeRoutingSaveInput.Type; + +export class ProjectRuntimeRoutingConflictError extends Schema.TaggedError()( + "ProjectRuntimeRoutingConflictError", + { + projectId: ProjectId, + expectedRevision: NonNegativeInt, + currentRevision: NonNegativeInt, + }, +) { + override get message(): string { + return `Project routing for ${this.projectId} is at revision ${this.currentRevision}, not the expected revision ${this.expectedRevision}.`; + } +} + +export const RuntimeRoutingError = Schema.Union([ProjectRuntimeRoutingConflictError]); +export type RuntimeRoutingError = typeof RuntimeRoutingError.Type; diff --git a/packages/contracts/src/runtimeRoutingResolution.ts b/packages/contracts/src/runtimeRoutingResolution.ts new file mode 100644 index 000000000000..dfd3b1ecbace --- /dev/null +++ b/packages/contracts/src/runtimeRoutingResolution.ts @@ -0,0 +1,138 @@ +import * as Schema from "effect/Schema"; + +import { NonNegativeInt, PositiveInt, ProjectId } from "./baseSchemas.ts"; +import { DevelopmentProfileId } from "./developmentProfiles.ts"; +import { ProviderOptionSelections } from "./model.ts"; +import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts"; +import { ProviderInteractionMode, RuntimeMode } from "./providerPolicy.ts"; +import { ProjectRuntimeTaskId } from "./projectRuntime.ts"; +import { + RuntimeRouteCandidate, + RuntimeRouteIsolation, + RuntimeWorkerRole, + RUNTIME_ROUTING_BOUNDS, +} from "./runtimeRouting.ts"; + +/** One-run routing intent. It is never persisted by this gate. */ +export const RuntimeRouteOverride = Schema.Struct({ + role: Schema.optionalKey(RuntimeWorkerRole), + candidate: RuntimeRouteCandidate, +}); +export type RuntimeRouteOverride = typeof RuntimeRouteOverride.Type; + +export const RuntimeRouteResolutionInput = Schema.Struct({ + projectId: ProjectId, + taskId: Schema.optionalKey(ProjectRuntimeTaskId), + /** A one-run role override used to look up project and profile routing. */ + role: Schema.optionalKey(RuntimeWorkerRole), + override: Schema.optionalKey(RuntimeRouteOverride), +}); +export type RuntimeRouteResolutionInput = typeof RuntimeRouteResolutionInput.Type; + +export const RuntimeRouteSource = Schema.Literals([ + "explicit", + "task", + "project", + "profile", + "inherit", +]); +export type RuntimeRouteSource = typeof RuntimeRouteSource.Type; + +export const RuntimeRouteResolutionStatus = Schema.Literals(["resolved", "inherited", "failed"]); +export type RuntimeRouteResolutionStatus = typeof RuntimeRouteResolutionStatus.Type; + +export const RuntimeRouteRejectionReason = Schema.Literals([ + "provider_instance_missing", + "provider_driver_mismatch", + "provider_instance_disabled_for_project", + "provider_orchestration_unsupported", + "provider_unavailable", + "provider_disabled", + "provider_not_installed", + "provider_not_ready", + "provider_auth_required", + "no_eligible_provider_instance", + "model_unavailable", + "model_options_invalid", + "runtime_mode_unsupported", + "interaction_mode_unsupported", +]); +export type RuntimeRouteRejectionReason = typeof RuntimeRouteRejectionReason.Type; + +export const RuntimeRouteRejection = Schema.Struct({ + source: RuntimeRouteSource, + candidateIndex: NonNegativeInt, + candidate: RuntimeRouteCandidate, + reason: RuntimeRouteRejectionReason, + detail: Schema.optionalKey( + Schema.String.check(Schema.isMaxLength(RUNTIME_ROUTING_BOUNDS.rejectionDetailMaxLength)), + ), +}); +export type RuntimeRouteRejection = typeof RuntimeRouteRejection.Type; + +export const RuntimeRouteFailureReason = Schema.Literals([ + "candidates_exhausted", + "explicit_override_unavailable", +]); +export type RuntimeRouteFailureReason = typeof RuntimeRouteFailureReason.Type; + +export const RuntimeRouteFailure = Schema.Struct({ + source: RuntimeRouteSource, + reason: RuntimeRouteFailureReason, +}); +export type RuntimeRouteFailure = typeof RuntimeRouteFailure.Type; + +/** + * `eligibility` is a resolution-time observation. It is deliberately not an + * authorization for a future launch; the Orchestrator rechecks settings and + * provider state when work actually starts. + */ +export const RuntimeResolvedRoute = Schema.Struct({ + source: RuntimeRouteSource, + candidateIndex: NonNegativeInt, + candidate: RuntimeRouteCandidate, + providerInstanceId: ProviderInstanceId, + driverKind: ProviderDriverKind, + model: Schema.String, + options: Schema.optionalKey(ProviderOptionSelections), + isolation: RuntimeRouteIsolation, + runtimeMode: Schema.optionalKey(RuntimeMode), + interactionMode: Schema.optionalKey(ProviderInteractionMode), + eligibility: Schema.Literal("eligible-at-resolution"), +}); +export type RuntimeResolvedRoute = typeof RuntimeResolvedRoute.Type; + +export const RuntimeRouteRevisions = Schema.Struct({ + task: Schema.NullOr(PositiveInt), + projectRouting: NonNegativeInt, + profile: Schema.NullOr( + Schema.Struct({ + profileId: DevelopmentProfileId, + revision: PositiveInt, + }), + ), + assignment: Schema.NullOr( + Schema.Struct({ + projectId: ProjectId, + profileId: Schema.NullOr(DevelopmentProfileId), + revision: PositiveInt, + }), + ), +}); +export type RuntimeRouteRevisions = typeof RuntimeRouteRevisions.Type; + +export const RuntimeRouteResolution = Schema.Struct({ + projectId: ProjectId, + taskId: Schema.NullOr(ProjectRuntimeTaskId), + role: RuntimeWorkerRole, + status: RuntimeRouteResolutionStatus, + source: RuntimeRouteSource, + selected: Schema.NullOr(RuntimeResolvedRoute), + inheritedFrom: Schema.NullOr(RuntimeRouteSource), + rejected: Schema.Array(RuntimeRouteRejection).check( + Schema.isMaxLength(RUNTIME_ROUTING_BOUNDS.rejectionsMax), + ), + failure: Schema.NullOr(RuntimeRouteFailure), + revisions: RuntimeRouteRevisions, +}); +export type RuntimeRouteResolution = typeof RuntimeRouteResolution.Type;