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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions src/cli/lab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
* Read commands use the local SQLite projection. Automation mutations and manual runs are
* explicit operator actions; read commands never start probes or scheduler ticks.
*/
import { getConfigDir, readConfigDiagnostics } from "../config";
import { getConfigDir, readConfigDiagnostics, saveConfigPreservingClaudeCode } from "../config";
import type { OcxConfig } from "../types";
import {
ARTIFACT_CLASSES,
EVIDENCE_LAYERS,
Expand Down Expand Up @@ -63,6 +64,7 @@ import { planManualLabRun } from "../lab/automation/planner";
import { listLabAutomationRuns } from "../lab/automation/runs-query";
import { LabAutomationError, type LabAutomationLayer } from "../lab/automation/types";
import { createProductionLabRouteExecutor } from "../lib/lab-live-route-production";
import { ensureLabAutomationRuntime } from "../server/lab-automation-runtime";

const USAGE = `Usage:
ocx lab status [--json]
Expand All @@ -87,6 +89,8 @@ type ArtifactStatus = (typeof ARTIFACT_STATUSES)[number];

export interface LabCliDeps {
configDir?: string;
loadConfig?: () => OcxConfig;
saveConfig?: (config: OcxConfig) => void;
}

class LabStateError extends RuntimeApiError {
Expand All @@ -104,6 +108,19 @@ function labErrorMessage(err: unknown): string {
return "lab read failed";
}

function loadCliConfig(deps: LabCliDeps): OcxConfig {
return deps.loadConfig?.() ?? readConfigDiagnostics().config;
}

function persistLabIntegrationOptIn(deps: LabCliDeps): void {
const config = loadCliConfig(deps);
if (config.labIntegrationEnabled === true) return;
(deps.saveConfig ?? saveConfigPreservingClaudeCode)({
...config,
labIntegrationEnabled: true,
});
}

function takeEnumOption<T extends string>(
args: string[],
flag: string,
Expand Down Expand Up @@ -394,8 +411,12 @@ export async function handleLabCommand(argv: string[], deps: LabCliDeps = {}): P
},
taskEffectivenessBackgroundEnabled: false,
};
// `automation enable` is the explicit operator opt-in. Persist the
// core runtime gate too so server restart cannot silently disable it.
persistLabIntegrationOptIn(deps);
saveLabAutomationPolicyConfig(policy, configDir);
reconcileLabAutomationQueue(configDir);
ensureLabAutomationRuntime(loadCliConfig(deps), configDir);
startLabAutomationScheduler(configDir);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
const status = buildLabAutomationStatus(configDir);
printData(automationCliStatus(status), wantsJson, automationStatusLines(status));
Expand Down Expand Up @@ -435,7 +456,7 @@ export async function handleLabCommand(argv: string[], deps: LabCliDeps = {}): P
const modelId = takeOption(rest, "--model");
rejectArgs(rest, USAGE);
if (!layer || !scenarioId) throw new CliUsageError("--layer and --scenario are required", USAGE);
const configSnapshot = readConfigDiagnostics().config;
const configSnapshot = loadCliConfig(deps);
if (layer === "live_route_compatibility") {
const loadConfig = () => configSnapshot;
setLabAutomationDispatchDeps({
Expand Down
3 changes: 3 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1251,6 +1251,9 @@ const configSchema = z.object({
providerContextCaps: z.record(z.string(), z.number().int().positive()).optional(),
contextCapValue: z.number().int().positive().optional(),
multiAgentGuidanceEnabled: z.boolean().optional(),
// Compatibility Lab integration with the ordinary server runtime is explicit
// opt-in. A bad hand edit degrades to OFF instead of invalidating providers.
labIntegrationEnabled: z.boolean().optional().catch(false),
// Invalid optional recovery config must not discard unrelated provider/account state.
agentTaskRecovery: agentTaskRecoverySchema.optional().catch(undefined),
// These selections pre-date schema validation and used to pass through as
Expand Down
6 changes: 5 additions & 1 deletion src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ import {
} from "./routing/trace";
import { getRoutingProfile, resolvePolicyProfileId } from "./routing/profile";
import { evaluatePolicyProfile, type PolicyRequestEvidence } from "./routing/evaluator";
import { assemblePolicyCandidateEvidence } from "./routing/compatibility/assemble";

export class NoEligiblePolicyCandidateError extends Error {
/** Evaluation trace (with per-candidate exclusions) when nothing qualified. */
Expand Down Expand Up @@ -518,6 +517,11 @@ function routeModelInternal(
const policyId = !bypassCombos ? resolvePolicyProfileId(config, modelId) : null;
const profile = policyId ? getRoutingProfile(config, policyId) : undefined;
if (profile && policyId) {
// Compatibility evidence is needed only for an explicit policy route.
// Keep its Lab-backed implementation out of the normal concrete route path.
const { assemblePolicyCandidateEvidence } = require(
"./routing/compatibility/assemble",
) as typeof import("./routing/compatibility/assemble");
// One clock read per decision keeps candidate evidence, exclusions, and
// scores mutually consistent and reproducible.
const now = Date.now();
Expand Down
52 changes: 34 additions & 18 deletions src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,6 @@ import {
registerDefaultAppOwnedObservedBuffers,
} from "../lib/app-owned-memory-stores";
import { acquireServerBackgroundLifecycle } from "./background-lifecycle";
import {
setLabAutomationDispatchDeps,
startLabAutomationScheduler,
} from "../lab/automation/orchestrator";
import { loadLabAutomationPolicy } from "../lab/automation/persistence";
import { createProductionLabRouteExecutor } from "../lib/lab-live-route-production";
import { runOpenAiTierStartupMigration } from "../providers/openai-tier-startup";
import { runAlibabaRegionStartupMigration } from "../providers/alibaba-region-startup";
import { runModelRenameStartupMigration } from "../providers/model-rename-startup";
Expand Down Expand Up @@ -81,6 +75,7 @@ import {
isDraining,
registerTurn,
runListenerShutdown,
setLabAutomationShutdownHook,
setServerRef,
trackStreamLifetime,
tryAdmitTurn,
Expand Down Expand Up @@ -1735,18 +1730,39 @@ export function startServer(port?: number, deps: StartServerDeps = {}): Server<W
// Opt-in storage policy (default OFF). Never blocks listen; cancellable on shutdown.
backgroundLifecycle.scheduleStartupRun();

const labConfigDir = getConfigDir();
const productionLabRouteExecutor = createProductionLabRouteExecutor({
configDir: labConfigDir,
loadConfig: () => config,
});
setLabAutomationDispatchDeps({
configDir: labConfigDir,
loadConfig: () => config,
routeExecutor: productionLabRouteExecutor,
});
if (loadLabAutomationPolicy(labConfigDir).enabled) {
startLabAutomationScheduler(labConfigDir);
// Compatibility Lab runtime integration is explicit opt-in. Keep all Lab
// automation modules outside the ordinary server startup graph while
// preserving startServer's synchronous API.
if (config.labIntegrationEnabled === true) {
const {
requestLabAutomationShutdown,
setLabAutomationDispatchDeps,
startLabAutomationScheduler,
stopLabAutomationScheduler,
} = require("../lab/automation/orchestrator") as typeof import("../lab/automation/orchestrator");
const { loadLabAutomationPolicy } = require(
"../lab/automation/persistence",
) as typeof import("../lab/automation/persistence");
const { createProductionLabRouteExecutor } = require(
"../lib/lab-live-route-production",
) as typeof import("../lib/lab-live-route-production");
const labConfigDir = getConfigDir();
const productionLabRouteExecutor = createProductionLabRouteExecutor({
configDir: labConfigDir,
loadConfig: () => config,
});
setLabAutomationDispatchDeps({
configDir: labConfigDir,
loadConfig: () => config,
routeExecutor: productionLabRouteExecutor,
});
setLabAutomationShutdownHook(() => {
requestLabAutomationShutdown();
stopLabAutomationScheduler();
});
if (loadLabAutomationPolicy(labConfigDir).enabled) {
startLabAutomationScheduler(labConfigDir);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}

return server;
Expand Down
68 changes: 68 additions & 0 deletions src/server/lab-automation-runtime.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { readConfigDiagnostics } from "../config";
import type { OcxConfig } from "../types";
import { setLabAutomationShutdownHook } from "./lifecycle";

type RuntimeOwner = {
release: () => void;
};

const runtimeOwners = new Map<string, RuntimeOwner>();

function configKey(configDir?: string): string {
return configDir ?? "";
}

function loadLatestConfig(fallback: OcxConfig): OcxConfig {
try {
return readConfigDiagnostics().config;
} catch {
return fallback;
}
}

function installShutdownHook(): void {
setLabAutomationShutdownHook(() => {
const {
requestLabAutomationShutdown,
stopLabAutomationScheduler,
} = require("../lab/automation/orchestrator") as typeof import("../lab/automation/orchestrator");
requestLabAutomationShutdown();
for (const [key, owner] of runtimeOwners) {
stopLabAutomationScheduler(key || undefined);
owner.release();
}
runtimeOwners.clear();
});
}

/**
* Lazily install the host-owned dispatch authority required by explicit Lab
* automation requests. Importing this module alone does not load Lab runtime
* code; the Lab graph is entered only when an explicit caller invokes this.
*/
export function ensureLabAutomationRuntime(config: OcxConfig, configDir?: string): void {
const key = configKey(configDir);
if (runtimeOwners.has(key)) return;

const { setLabAutomationDispatchDeps } = require(
"../lab/automation/orchestrator",
) as typeof import("../lab/automation/orchestrator");
const { createProductionLabRouteExecutor } = require(
"../lib/lab-live-route-production",
) as typeof import("../lib/lab-live-route-production");
const loadConfig = () => loadLatestConfig(config);
const release = setLabAutomationDispatchDeps({
configDir,
loadConfig,
routeExecutor: createProductionLabRouteExecutor({ configDir, loadConfig }),
});
runtimeOwners.set(key, { release });
installShutdownHook();
}

/** Test-only reset for direct management-route tests that do not own a server lifecycle. */
export function resetLabAutomationRuntimeForTests(): void {
for (const owner of runtimeOwners.values()) owner.release();
runtimeOwners.clear();
setLabAutomationShutdownHook(null);
}
16 changes: 13 additions & 3 deletions src/server/lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import {
} from "../storage/policy-job";
import { abortRestoreTrashJobAsync } from "../storage/restore-job";
import { stopStorageCleanupScheduler } from "../storage/policy-scheduler";
import { stopLabAutomationScheduler, requestLabAutomationShutdown } from "../lab/automation/orchestrator";
import { stopStateStoreSweeper } from "../lib/state-store-sweeper";
import {
cancelQueuedStorageWorkerSpawns,
Expand Down Expand Up @@ -52,6 +51,17 @@ let _serverRef: ReturnType<typeof Bun.serve> | undefined;
let serverStopFlights = new WeakMap<ReturnType<typeof Bun.serve>, Promise<void>>();
let serverStartupReleaseFlights = new WeakMap<ReturnType<typeof Bun.serve>, Promise<void>>();
let releaseServerStartupLifecycleImpl: typeof releaseNativeMainStartupLifecycle = releaseNativeMainStartupLifecycle;
let labAutomationShutdownHook: (() => void) | null = null;

export function setLabAutomationShutdownHook(hook: (() => void) | null): void {
labAutomationShutdownHook = hook;
}

function runLabAutomationShutdownHook(): void {
const hook = labAutomationShutdownHook;
labAutomationShutdownHook = null;
hook?.();
}

export function setServerRef(server: ReturnType<typeof Bun.serve> | undefined): void { _serverRef = server; }
/**
Expand Down Expand Up @@ -156,6 +166,7 @@ export function resetLifecycleDrainStateForTests(): void {
serverStopFlights = new WeakMap<ReturnType<typeof Bun.serve>, Promise<void>>();
serverStartupReleaseFlights = new WeakMap<ReturnType<typeof Bun.serve>, Promise<void>>();
releaseServerStartupLifecycleImpl = releaseNativeMainStartupLifecycle;
labAutomationShutdownHook = null;
}
export function tryAdmitTurn(): ActiveTurnLease | null {
if (isDraining()) return null;
Expand Down Expand Up @@ -452,8 +463,7 @@ export async function drainAndShutdown(
// Abort each job independently so one wedged join cannot skip the other,
// then drain leftovers; failures must not prevent `server.stop`.
stopStorageCleanupScheduler();
requestLabAutomationShutdown();
stopLabAutomationScheduler();
runLabAutomationShutdownHook();
stopStateStoreSweeper();
// The overlay reconciler is owner-scoped: the startServer stop override
// releases THIS server's lease through runListenerShutdown →
Expand Down
28 changes: 22 additions & 6 deletions src/server/management-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,15 +61,12 @@ import { handleConfigRoutes } from "./management/config-routes";
import { handleLogsUsageRoutes } from "./management/logs-usage-routes";
import { handleRequestHistoryRoutes } from "./management/request-history-routes";
import { handleRoutingAnalyticsRoutes } from "./management/routing-analytics-routes";
import { handleRoutingProfileRoutes } from "./management/routing-profile-routes";
import { handleProviderRoutes } from "./management/provider-routes";
import { handleModelRoutes } from "./management/model-routes";
import { handleAgentSettingsRoutes } from "./management/agent-settings-routes";
import { handleOauthAccountRoutes } from "./management/oauth-account-routes";
import { handleComboRoutes } from "./management/combo-routes";
import { handleSystemRoutes } from "./management/system-routes";
import { handleLabRoutes } from "./management/lab-routes";
import { handleLabAutomationRoutes } from "./management/lab-automation-routes";
import { handleSidebarRoutes } from "./management/sidebar-routes";
import { handleIntegrationRoutes } from "./management/integration-routes";
import { handleNativeIntegrationRoutes } from "./management/native-integration-routes";
Expand All @@ -91,6 +88,26 @@ export const VERSION = (() => {
}
})();

function pathInManagementNamespace(pathname: string, prefix: string): boolean {
return pathname === prefix || pathname.startsWith(`${prefix}/`);
}

async function handleRoutingProfileRoutesOnDemand(ctx: ManagementContext): Promise<Response | null> {
if (!pathInManagementNamespace(ctx.url.pathname, "/api/routing-profiles")) return null;
const { handleRoutingProfileRoutes } = await import("./management/routing-profile-routes");
return handleRoutingProfileRoutes(ctx);
}

async function handleLabRoutesOnDemand(ctx: ManagementContext): Promise<Response | null> {
if (!pathInManagementNamespace(ctx.url.pathname, "/api/lab")) return null;
if (pathInManagementNamespace(ctx.url.pathname, "/api/lab/automation")) {
const { handleLabAutomationRoutes } = await import("./management/lab-automation-routes");
return handleLabAutomationRoutes(ctx);
}
const { handleLabRoutes } = await import("./management/lab-routes");
return handleLabRoutes(ctx);
}

const managementConvergenceBindings = new WeakMap<object, Readonly<{
factory: (config: Readonly<OcxConfig>) => ConvergeCodex;
converge: ConvergeCodex;
Expand Down Expand Up @@ -180,7 +197,7 @@ export async function handleManagementAPI(
?? (await handleLogsUsageRoutes(ctx))
?? (await handleRequestHistoryRoutes(ctx))
?? (await handleRoutingAnalyticsRoutes(ctx))
?? (await handleRoutingProfileRoutes(ctx))
?? (await handleRoutingProfileRoutesOnDemand(ctx))
?? (await handleProviderRoutes(ctx))
?? (await handleModelRoutes(ctx))
?? (await handleIntegrationRoutes(ctx))
Expand All @@ -189,8 +206,7 @@ export async function handleManagementAPI(
?? (await handleOauthAccountRoutes(ctx))
?? (await handleComboRoutes(ctx))
?? (await handleSystemRoutes(ctx))
?? (await handleLabAutomationRoutes(ctx))
?? (await handleLabRoutes(ctx))
?? (await handleLabRoutesOnDemand(ctx))
?? (await handleSidebarRoutes(ctx));
} catch (error) {
const tooLarge = managementBodyTooLargeResponse(error, req, config);
Expand Down
Loading
Loading