Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.
TypeScript
fix(agents): fail closed on host resolution (#166)
OKNOTOK86cad5b928f6
diff --git a/docs/decisions/0002-fail-closed-agent-execution-placement.md b/docs/decisions/0002-fail-closed-agent-execution-placement.mdnew file mode 100644index 0000000..eea1787--- /dev/null+++ b/docs/decisions/0002-fail-closed-agent-execution-placement.md@@ -0,0 +1,59 @@+# ADR 0002: Fail-closed Agent execution placement++- Status: Accepted+- Date: 2026-09-03++## Context++An Agent can run either on a paired BYOA Computer (`local` or `vps`) or on a+managed Cumora Cloud Pod. An unassigned paid Agent is intentionally eligible+for managed execution, so `computer_id = NULL` is a valid placement state.++The scheduler previously converted every host-resolution exception into the+same nullable shape. A transient PostgreSQL failure could therefore look like+an unassigned Agent, omit the company tier check, and create a managed Pod for+an Agent that was actually assigned to BYOA. The scheduler's earlier lookup was+also the only policy check, leaving a race before `ensurePod` applied the+Kubernetes manifest.++## Decision++- Host resolution is a discriminated result: `found`, `missing`, or `error`.+ A found result always includes a valid tenant and its tier; only an explicit+ `computer_id = NULL` produces an unassigned host.+- Dangling, cross-tenant, revoked, or unknown Computer assignments are invalid+ placement errors. They never fall back to cloud execution.+- The scheduler fails closed on errors. Transient lookup failures enter a+ dedicated wake retry class that is safe for durable message wakes because no+ execution location was selected or started.+- Managed-message triage and host selection live in the same retryable wake+ operation, so a retry cannot bypass the managed-runtime gate.+- `ensurePod` independently verifies that the Agent is active, is not assigned+ to BYOA, and belongs to a paid tenant. It checks at entry and again immediately+ before the first Kubernetes write; the loaded persona must match the same+ tenant.+- `ensurePod` failures carry machine-readable codes. Placement lookup failures+ can be retried without treating ordinary Pod failures as safe message replays.++## Consequences++- A database outage delays a wake instead of changing its execution location.+- Assignment corruption is visible through an alert and cannot cross a tenant,+ credential, or billing boundary.+- Host and tier resolution uses one database snapshot and adds a small cold-path+ query at the final Pod boundary. `ensurePod` is already limited to resting+ managed Agents, so the extra check is preferable to caching mutable policy.+- A BYOA reassignment or free-tier downgrade that races with Pod preparation is+ observed before PVC or Pod creation. Existing Pods are not implicitly deleted;+ lifecycle cleanup remains the assignment controller's responsibility.++## Alternatives considered++- **Catch lookup failures and assume cloud:** rejected because availability+ cannot override execution-location authorization.+- **Trust only the scheduler check:** rejected because callers can invoke+ `ensurePod` directly and placement can change before Kubernetes apply.+- **Cache host/tier decisions:** rejected because per-replica stale placement is+ exactly the unsafe state this boundary is intended to prevent.+- **Hold a database lock across Kubernetes calls:** rejected because external+ control-plane latency would create long transactions and lock contention.diff --git a/server/src/__integration__/agent-host-placement.test.ts b/server/src/__integration__/agent-host-placement.test.tsnew file mode 100644index 0000000..169e2bb--- /dev/null+++ b/server/src/__integration__/agent-host-placement.test.ts@@ -0,0 +1,85 @@+import { after, before, beforeEach, test } from 'node:test'+import assert from 'node:assert/strict'+import { pool } from '../db/pool.js'+import { resolveAgentHost } from '../agents/computer/registry.js'+import { verifyManagedPodPlacement } from '../agents/runtime/orchestrator.js'+import { ensureSchemaOnce, resetAllTables, teardownAll } from './_helpers.js'++before(async () => { await ensureSchemaOnce() })+beforeEach(async () => { await resetAllTables() })+after(async () => { await teardownAll() })++async function seedPlacementFixture(): Promise<void> {+ await pool.query(+ `INSERT INTO users (id, email, display_name, tier) VALUES+ ('owner-pro', '[email protected]', 'Pro Owner', 'pro'),+ ('owner-free', '[email protected]', 'Free Owner', 'free')`,+ )+ await pool.query(+ `INSERT INTO companies (id, name, slug, owner_user_id) VALUES+ ('co-pro', 'Pro Co', 'pro-co', 'owner-pro'),+ ('co-free', 'Free Co', 'free-co', 'owner-free')`,+ )+ await pool.query(+ `INSERT INTO computers+ (id, company_id, name, kind, available_engines, status, revoked_at)+ VALUES+ ('cloud-pro', 'co-pro', 'Cumora Cloud', 'cloud', '["managed"]', 'online', NULL),+ ('local-pro', 'co-pro', 'Laptop', 'local', '["codex"]', 'offline', NULL),+ ('revoked-pro', 'co-pro', 'Old laptop', 'local', '["codex"]', 'offline', NOW()),+ ('other-cloud', 'co-free', 'Other Cloud', 'cloud', '["managed"]', 'online', NULL)`,+ )+ await pool.query(+ `INSERT INTO participants+ (id, company_id, kind, name, initial, avatar_bg, status, computer_id)+ VALUES+ ('agent-cloud', 'co-pro', 'agent', 'Cloud', 'C', '#111111', 'resting', 'cloud-pro'),+ ('agent-local', 'co-pro', 'agent', 'Local', 'L', '#222222', 'resting', 'local-pro'),+ ('agent-free', 'co-free', 'agent', 'Free', 'F', '#333333', 'resting', NULL),+ ('agent-revoked', 'co-pro', 'agent', 'Revoked', 'R', '#444444', 'resting', 'revoked-pro'),+ ('agent-cross', 'co-pro', 'agent', 'Cross', 'X', '#555555', 'resting', 'other-cloud')`,+ )+}++test('[integration] managed placement resolves host and tier from one tenant snapshot', async () => {+ await seedPlacementFixture()++ const cloud = await resolveAgentHost('agent-cloud')+ assert.deepEqual(cloud, {+ status: 'found',+ kind: 'cloud',+ computerId: 'cloud-pro',+ companyId: 'co-pro',+ tier: 'pro',+ })+ assert.deepEqual(await verifyManagedPodPlacement('agent-cloud'), {+ ok: true,+ companyId: 'co-pro',+ computerId: 'cloud-pro',+ })++ const byoa = await verifyManagedPodPlacement('agent-local')+ assert.equal(byoa.ok, false)+ if (!byoa.ok) assert.equal(byoa.code, 'placement_denied')++ const free = await verifyManagedPodPlacement('agent-free')+ assert.deepEqual(free, {+ ok: false,+ code: 'placement_denied',+ reason: 'managed pod denied: free tier is BYOA-only',+ })+})++test('[integration] invalid soft Computer references fail closed', async () => {+ await seedPlacementFixture()++ for (const agentId of ['agent-revoked', 'agent-cross']) {+ const host = await resolveAgentHost(agentId)+ assert.equal(host.status, 'error')+ if (host.status === 'error') assert.equal(host.code, 'invalid_assignment')++ const placement = await verifyManagedPodPlacement(agentId)+ assert.equal(placement.ok, false)+ if (!placement.ok) assert.equal(placement.code, 'placement_denied')+ }+})diff --git a/server/src/__tests__/agents-host-resolution.test.ts b/server/src/__tests__/agents-host-resolution.test.tsnew file mode 100644index 0000000..3baacc9--- /dev/null+++ b/server/src/__tests__/agents-host-resolution.test.ts@@ -0,0 +1,115 @@+import { after, test } from 'node:test'+import assert from 'node:assert/strict'+import { pool } from '../db/pool.js'+import {+ managedPodPlacement,+ resolveAgentHost,+ type AgentHostResolution,+} from '../agents/computer/registry.js'+import { verifyManagedPodPlacement } from '../agents/runtime/orchestrator.js'++type HostDb = NonNullable<Parameters<typeof resolveAgentHost>[1]>++function fakeDb(rows: Record<string, unknown>[]): HostDb {+ return {+ query: async <T extends object>() => ({ rows: rows as T[] }),+ }+}++const paidCloudRow = {+ company_id: 'co-1',+ computer_id: 'cloud-co-1',+ resolved_computer_id: 'cloud-co-1',+ computer_company_id: 'co-1',+ kind: 'cloud',+ revoked_at: null,+ resolved_company_id: 'co-1',+ tier: 'pro',+}++after(async () => {+ try { await pool.end() } catch { /* ignore */ }+ try {+ const { redis, sub } = await import('../redis.js')+ redis.disconnect()+ sub.disconnect()+ } catch { /* ignore */ }+})++test('resolveAgentHost distinguishes a missing agent from an unassigned paid agent', async () => {+ assert.deepEqual(await resolveAgentHost('missing', fakeDb([])), { status: 'missing' })++ const unassigned = await resolveAgentHost('agent-1', fakeDb([{+ ...paidCloudRow,+ computer_id: null,+ resolved_computer_id: null,+ computer_company_id: null,+ kind: null,+ }]))+ assert.deepEqual(unassigned, {+ status: 'found',+ kind: null,+ computerId: null,+ companyId: 'co-1',+ tier: 'pro',+ })+})++test('resolveAgentHost reports database failure instead of synthesizing cloud placement', async () => {+ const db: HostDb = {+ query: async () => { throw new Error('database unavailable') },+ }+ const result = await resolveAgentHost('agent-1', db)+ assert.equal(result.status, 'error')+ if (result.status !== 'error') return+ assert.equal(result.code, 'lookup_failed')+ assert.match(result.reason, /host lookup failed/)+ assert.match(result.cause instanceof Error ? result.cause.message : '', /database unavailable/)+})++test('soft-reference corruption never falls back to managed cloud', async () => {+ const invalidRows = [+ { ...paidCloudRow, resolved_computer_id: null, kind: null },+ { ...paidCloudRow, computer_company_id: 'co-other' },+ { ...paidCloudRow, revoked_at: new Date() },+ { ...paidCloudRow, resolved_company_id: null },+ ]+ for (const row of invalidRows) {+ const result = await resolveAgentHost('agent-1', fakeDb([row]))+ assert.equal(result.status, 'error')+ if (result.status === 'error') assert.equal(result.code, 'invalid_assignment')+ }+})++test('managedPodPlacement permits only paid managed or explicit unassigned hosts', () => {+ const found = (overrides: Partial<Extract<AgentHostResolution, { status: 'found' }>> = {}) => ({+ status: 'found' as const,+ kind: 'cloud' as const,+ computerId: 'cloud-co-1',+ companyId: 'co-1',+ tier: 'pro' as const,+ ...overrides,+ })++ assert.deepEqual(managedPodPlacement(found()), {+ status: 'allowed', companyId: 'co-1', computerId: 'cloud-co-1',+ })+ assert.deepEqual(managedPodPlacement(found({ kind: null, computerId: null })), {+ status: 'allowed', companyId: 'co-1', computerId: null,+ })+ assert.equal(managedPodPlacement(found({ kind: 'local' })).status, 'denied')+ assert.equal(managedPodPlacement(found({ kind: 'vps' })).status, 'denied')+ assert.equal(managedPodPlacement(found({ tier: 'free' })).status, 'denied')+ assert.equal(managedPodPlacement({ status: 'missing' }).status, 'denied')+})++test('ensurePod placement guard converts resolver throws into a fail-closed retry code', async () => {+ const denied = await verifyManagedPodPlacement('agent-1', async () => {+ throw new Error('transient connection reset')+ })+ assert.deepEqual(denied, {+ ok: false,+ code: 'placement_lookup_failed',+ reason: 'host lookup failed for agent agent-1',+ })+})diff --git a/server/src/__tests__/scheduler-low-pri-budget.test.ts b/server/src/__tests__/scheduler-low-pri-budget.test.tsindex 73c341c..6b9d9a4 100644--- a/server/src/__tests__/scheduler-low-pri-budget.test.ts+++ b/server/src/__tests__/scheduler-low-pri-budget.test.ts@@ -12,6 +12,7 @@ import {_consumeLowPriorityWakeBudget,_resetLowPriorityWakeBudgetForTests,_shouldRetryEnsurePodFailure,+ _shouldRetryWakeFailure,_wakeRetryDelayMs,shouldDeliverToMutedAgent,} from '../agents/scheduler.js'@@ -93,6 +94,23 @@ test('ensurePod retry is only for manual wakes — message.new is durable via DBassert.equal(_shouldRetryEnsurePodFailure('background_scan', 'cluster fuse saturated'), false)})+test('host-resolution failure retries before any execution location was selected', () => {+ assert.equal(+ _shouldRetryWakeFailure('message.new', 'host lookup failed', 'host_resolution'),+ true,+ )+ assert.equal(+ _shouldRetryWakeFailure('idle', 'host lookup failed', 'host_resolution'),+ true,+ )+ // The existing duplicate-turn protection remains intact for ordinary pod+ // failures after placement was successfully resolved.+ assert.equal(+ _shouldRetryWakeFailure('message.new', 'pod apply failed', 'ensure_pod'),+ false,+ )+})+test('muted agent delivery only allows direct, exact mention, or quote reply', () => {const base = { agentId: 'nova-12', conversationKind: 'group', body: 'ordinary room chatter', quotedAuthorId: null }assert.equal(shouldDeliverToMutedAgent(base), false)diff --git a/server/src/agents/computer/registry.ts b/server/src/agents/computer/registry.tsindex 7b0f79f..fa0d6d8 100644--- a/server/src/agents/computer/registry.ts+++ b/server/src/agents/computer/registry.ts@@ -17,6 +17,7 @@import { createHash, randomBytes, randomUUID } from 'node:crypto'import { pool } from '../../db/pool.js'import { CH_STATUS, publish } from '../../redis.js'+import { normalizeTier, type Tier } from '../../tier.js'import { signAgentToken } from '../runtime/jwt.js'export type ComputerKind = 'cloud' | 'local' | 'vps'@@ -639,28 +640,182 @@ export async function listComputers(companyId: string): Promise<ComputerWithUpgr}))}-export interface AgentHost {- /** kind of computer the agent runs on, or null if unassigned (treat as cloud). */+export interface ResolvedAgentHost {+ status: 'found'+ /** kind of computer the agent runs on, or null only when truly unassigned. */kind: ComputerKind | null- /** the agent's company — lets the scheduler check the company's tier. */- companyId: string | null+ /** Exact assigned computer. Null is the explicit unassigned state. */+ computerId: string | null+ /** Active agent tenant. A found result never carries an empty tenant. */+ companyId: string+ /** Tenant tier read in the same database snapshot as the host assignment. */+ tier: Tier+}++export interface MissingAgentHost {+ status: 'missing'+}++export interface FailedAgentHostResolution {+ status: 'error'+ code: 'lookup_failed' | 'invalid_assignment'+ reason: string+ cause?: unknown+}++/** A database failure is deliberately different from a valid unassigned Agent. */+export type AgentHostResolution =+ | ResolvedAgentHost+ | MissingAgentHost+ | FailedAgentHostResolution++export type ManagedPodPlacement =+ | { status: 'allowed'; companyId: string; computerId: string | null }+ | {+ status: 'denied'+ code: 'agent_not_found' | 'placement_lookup_failed' | 'placement_denied'+ reason: string+ }++function isComputerKind(value: unknown): value is ComputerKind {+ return value === 'cloud' || value === 'local' || value === 'vps'}/** Resolve where an agent runs + its company. Not cached: this sits on the* scheduler's cold path (wakeOne only calls it for a resting agent with no* live subscriber), and it's a single indexed lookup — a PK probe on- * participants + a PK LEFT JOIN on computers. An in-process cache here would+ * participants + PK joins on computers/company ownership. An in-process cache here would* be both pointless (cold path) and unsafe (each replica caches independently,* so reassignments/tier changes go stale per-pod). LEFT JOIN so an unassigned- * agent (computer_id NULL) still returns its companyId with a null kind. */-export async function resolveAgentHost(agentId: string): Promise<AgentHost> {- const { rows } = await pool.query<{ kind: ComputerKind | null; company_id: string | null }>(- `SELECT c.kind, p.company_id FROM participants p- LEFT JOIN computers c ON c.id = p.computer_id- WHERE p.id = $1 AND p.kind = 'agent' LIMIT 1`,- [agentId],- )- return { kind: rows[0]?.kind ?? null, companyId: rows[0]?.company_id ?? null }+ * agent (computer_id NULL) still returns its companyId with a null kind.+ *+ * Do not throw lookup failures into the same shape as "missing": callers route+ * execution from this result, so every state is explicit and exhaustively+ * handled. Soft-reference corruption (missing/cross-tenant Computer) is also+ * an error, never an implicit cloud assignment. */+export async function resolveAgentHost(+ agentId: string,+ db: Queryable = pool,+): Promise<AgentHostResolution> {+ try {+ const { rows } = await db.query<{+ company_id: string | null+ computer_id: string | null+ resolved_computer_id: string | null+ computer_company_id: string | null+ kind: string | null+ revoked_at: Date | null+ resolved_company_id: string | null+ tier: string | null+ }>(+ `SELECT p.company_id,+ p.computer_id,+ c.id AS resolved_computer_id,+ c.company_id AS computer_company_id,+ c.kind,+ c.revoked_at,+ company.id AS resolved_company_id,+ COALESCE(owner_user.tier, owner_member.tier, 'free') AS tier+ FROM participants p+ LEFT JOIN computers c ON c.id = p.computer_id+ LEFT JOIN companies company ON company.id = p.company_id+ LEFT JOIN users owner_user ON owner_user.id = company.owner_user_id+ LEFT JOIN LATERAL (+ SELECT u.tier+ FROM company_members cm+ JOIN users u ON u.id = cm.user_id+ WHERE cm.company_id = company.id AND cm.role = 'owner'+ ORDER BY cm.joined_at ASC+ LIMIT 1+ ) owner_member ON TRUE+ WHERE p.id = $1+ AND p.kind = 'agent'+ AND p.departed_at IS NULL+ LIMIT 1`,+ [agentId],+ )+ const row = rows[0]+ if (!row) return { status: 'missing' }+ if (!row.company_id || !row.resolved_company_id) {+ return {+ status: 'error',+ code: 'invalid_assignment',+ reason: `agent ${agentId} has no valid company assignment`,+ }+ }+ if (row.computer_id !== null) {+ if (!row.resolved_computer_id || !isComputerKind(row.kind)) {+ return {+ status: 'error',+ code: 'invalid_assignment',+ reason: `agent ${agentId} references an unavailable computer`,+ }+ }+ if (row.computer_company_id !== row.company_id) {+ return {+ status: 'error',+ code: 'invalid_assignment',+ reason: `agent ${agentId} computer assignment crosses company boundaries`,+ }+ }+ if (row.revoked_at !== null) {+ return {+ status: 'error',+ code: 'invalid_assignment',+ reason: `agent ${agentId} is assigned to a revoked computer`,+ }+ }+ }+ return {+ status: 'found',+ kind: row.computer_id === null ? null : row.kind as ComputerKind,+ computerId: row.computer_id,+ companyId: row.company_id,+ tier: normalizeTier(row.tier),+ }+ } catch (cause) {+ return {+ status: 'error',+ code: 'lookup_failed',+ reason: `host lookup failed for agent ${agentId}`,+ cause,+ }+ }+}++/** Final managed-runtime policy used at the `ensurePod` boundary. */+export function managedPodPlacement(+ resolution: AgentHostResolution,+): ManagedPodPlacement {+ if (resolution.status === 'missing') {+ return { status: 'denied', code: 'agent_not_found', reason: 'no such agent' }+ }+ if (resolution.status === 'error') {+ return {+ status: 'denied',+ code: resolution.code === 'lookup_failed' ? 'placement_lookup_failed' : 'placement_denied',+ reason: resolution.reason,+ }+ }+ if (isByoaKind(resolution.kind)) {+ return {+ status: 'denied',+ code: 'placement_denied',+ reason: `managed pod denied: agent is assigned to a ${resolution.kind} computer`,+ }+ }+ if (resolution.tier === 'free') {+ return {+ status: 'denied',+ code: 'placement_denied',+ reason: 'managed pod denied: free tier is BYOA-only',+ }+ }+ return {+ status: 'allowed',+ companyId: resolution.companyId,+ computerId: resolution.computerId,+ }}/** A BYOA host (user-paired) runs a daemon, not a server-managed pod. */diff --git a/server/src/agents/runtime/orchestrator.ts b/server/src/agents/runtime/orchestrator.tsindex 87739d3..a6b537b 100644--- a/server/src/agents/runtime/orchestrator.ts+++ b/server/src/agents/runtime/orchestrator.ts@@ -29,6 +29,11 @@ import { inprocClient } from './inproc-client.js'import { signAgentToken } from './jwt.js'import { notifyAlert } from '../../alerting.js'import { Semaphore } from '../../concurrency.js'+import {+ managedPodPlacement,+ resolveAgentHost,+ type AgentHostResolution,+} from '../computer/registry.js'const KUBECTL = process.env.CUMORA_KUBECTL ?? 'kubectl'/** kubectl context to target. In dev we pin to OrbStack so a stray@@ -621,7 +626,56 @@ export function stuckPendingReason(h: PodHealth): string | null {export type EnsurePodResult =| { created: true; ok: true; reason: string }| { created: false; ok: true; reason: string }- | { created: false; ok: false; reason: string }+ | {+ created: false+ ok: false+ reason: string+ code:+ | 'watchdog_timeout'+ | 'pod_reap_failed'+ | 'capacity_denied'+ | 'agent_not_found'+ | 'placement_lookup_failed'+ | 'placement_denied'+ | 'pod_apply_failed'+ }++export type ManagedPodPlacementVerification =+ | { ok: true; companyId: string; computerId: string | null }+ | {+ ok: false+ code: 'agent_not_found' | 'placement_lookup_failed' | 'placement_denied'+ reason: string+ }++/** Resolve the policy at the managed-runtime boundary. The resolver is+ * injectable only so fault-path unit tests can prove that lookup exceptions+ * and invalid assignments fail closed without invoking kubectl. */+export async function verifyManagedPodPlacement(+ agentId: string,+ resolver: (id: string) => Promise<AgentHostResolution> = resolveAgentHost,+): Promise<ManagedPodPlacementVerification> {+ let resolution: AgentHostResolution+ try {+ resolution = await resolver(agentId)+ } catch (cause) {+ resolution = {+ status: 'error',+ code: 'lookup_failed',+ reason: `host lookup failed for agent ${agentId}`,+ cause,+ }+ }+ const decision = managedPodPlacement(resolution)+ if (decision.status === 'denied') {+ return { ok: false, code: decision.code, reason: decision.reason }+ }+ return {+ ok: true,+ companyId: decision.companyId,+ computerId: decision.computerId,+ }+}/** In-flight `ensurePod` deduplication. Without this a thundering* herd (e.g. 50 wakes for one resting agent within 1s) calls@@ -663,6 +717,7 @@ export async function ensurePod(agentId: string): Promise<EnsurePodResult> {resolve({created: false,ok: false,+ code: 'watchdog_timeout',reason: `ensurePod watchdog: implementation did not return within ${ENSURE_POD_WATCHDOG_MS}ms`,})}, ENSURE_POD_WATCHDOG_MS).unref?.(),@@ -690,13 +745,39 @@ export async function ensurePod(agentId: string): Promise<EnsurePodResult> {async function ensurePodImpl(agentId: string): Promise<EnsurePodResult> {const startedAt = Date.now()+ // This is the final authorization boundary for managed execution. Scheduler+ // lookups are advisory only: assignment/tier can change between a wake and+ // this call, and other callers may invoke ensurePod directly.+ const initialPlacement = await verifyManagedPodPlacement(agentId)+ if (!initialPlacement.ok) {+ return { created: false, ...initialPlacement }+ }+ const recheckPlacement = async (): Promise<EnsurePodResult | null> => {+ const current = await verifyManagedPodPlacement(agentId)+ if (!current.ok) return { created: false, ...current }+ if (current.companyId !== initialPlacement.companyId) {+ return {+ created: false,+ ok: false,+ code: 'placement_denied',+ reason: 'managed pod denied: agent company changed during placement',+ }+ }+ return null+ }const h = await podHealth(agentId)if (h.phase === 'Running') {+ const denied = await recheckPlacement()+ if (denied) return deniedreturn { created: false, ok: true, reason: 'already running' }}if (h.phase === 'Pending') {const stuck = stuckPendingReason(h)- if (!stuck) return { created: false, ok: true, reason: 'already pending' }+ if (!stuck) {+ const denied = await recheckPlacement()+ if (denied) return denied+ return { created: false, ok: true, reason: 'already pending' }+ }// Fall through to the stuck-Pending reap path below. Don't admission-// gate this: reaping is a cleanup that frees a slot, not a fresh// demand on cluster capacity.@@ -718,6 +799,8 @@ async function ensurePodImpl(agentId: string): Promise<EnsurePodResult> {// `--timeout=30s` on the kubectl side AND our wrapper timeout —// belt-and-braces. A pod with stuck finalizers shouldn't block// the orchestrator's main loop indefinitely.+ const denied = await recheckPlacement()+ if (denied) return deniedconst reap = await kubectlWithRetry(['delete', 'pod', podName(agentId), '--ignore-not-found=true', '--wait=true', '--timeout=30s'],{ timeoutMs: 40_000 },@@ -728,7 +811,7 @@ async function ensurePodImpl(agentId: string): Promise<EnsurePodResult> {// Surface a precise error rather than letting the apply step// try and produce a misleading "already exists" message.return {- created: false, ok: false,+ created: false, ok: false, code: 'pod_reap_failed',reason: `pod reap failed (was stuck=${stuck}): ${(reap.err || reap.out).trim()}`,}}@@ -751,6 +834,8 @@ async function ensurePodImpl(agentId: string): Promise<EnsurePodResult> {} else if (h.phase === 'Unknown') {console.warn(`[orchestrator] ${agentId} previous pod was in Unknown phase (node lost?); reaping`)}+ const denied = await recheckPlacement()+ if (denied) return deniedawait kubectlWithRetry(['delete', 'pod', podName(agentId), '--ignore-not-found=true', '--wait=true', '--timeout=30s'],{ timeoutMs: 40_000 },@@ -768,13 +853,23 @@ async function ensurePodImpl(agentId: string): Promise<EnsurePodResult> {const fuse = await getClusterFuseUtilization()if (fuse.cap > 0 && fuse.ratio >= FUSE_ADMISSION_THRESHOLD) {return {- created: false, ok: false,+ created: false, ok: false, code: 'capacity_denied',reason: `cluster fuse saturated: ${fuse.used}/${fuse.cap} (${Math.round(fuse.ratio * 100)}% ≥ ${Math.round(FUSE_ADMISSION_THRESHOLD * 100)}% threshold)`,}}const persona = await inprocClient.loadPersona(agentId).catch(() => null)- if (!persona) return { created: false, ok: false, reason: 'no such agent' }+ if (!persona) {+ return { created: false, ok: false, code: 'agent_not_found', reason: 'no such agent' }+ }+ if (persona.companyId !== initialPlacement.companyId) {+ return {+ created: false,+ ok: false,+ code: 'placement_denied',+ reason: 'managed pod denied: persona tenant does not match host assignment',+ }+ }const token = signAgentToken({agentId,@@ -809,6 +904,13 @@ async function ensurePodImpl(agentId: string): Promise<EnsurePodResult> {}}+ // Re-read immediately before the first Kubernetes mutation. This closes the+ // scheduler-to-orchestrator and preparation-time race: moving the Agent to a+ // BYOA Computer or downgrading the tenant while pod health/key resolution is+ // in flight cannot still result in a managed PVC/Pod apply.+ const finalPlacementDenied = await recheckPlacement()+ if (finalPlacementDenied) return finalPlacementDenied+// Apply the per-agent chrome-profile PVC BEFORE the pod. kubectl// apply is idempotent — if the PVC already exists this is a no-op.// The PVC outlives the pod, so an idle-exit / restart / re-spawn@@ -853,7 +955,12 @@ async function ensurePodImpl(agentId: string): Promise<EnsurePodResult> {error: new Error(`kubectl apply failed for ${agentId}: ${errText}`),extras: { agentId, elapsedMs: Date.now() - startedAt, timedOut: podApply.timedOut },})- return { created: false, ok: false, reason: `pod apply failed: ${errText}` }+ return {+ created: false,+ ok: false,+ code: 'pod_apply_failed',+ reason: `pod apply failed: ${errText}`,+ }}bumpFuseUtilUsedOnSpawn()console.log(`[orchestrator] ${agentId} pod spun up in ${Date.now() - startedAt}ms`)diff --git a/server/src/agents/scheduler.ts b/server/src/agents/scheduler.tsindex 6a5b637..2e3be57 100644--- a/server/src/agents/scheduler.ts+++ b/server/src/agents/scheduler.ts@@ -25,8 +25,11 @@ import { env } from '../env.js'import { CH_MESSAGE_NEW, CH_POLLS, CH_TYPING, publish, redis, sub, type MessageNewEvent, type PollUpdatedEvent } from '../redis.js'import { notifyAlert } from '../alerting.js'import { ensurePod } from './runtime/orchestrator.js'-import { resolveAgentHost, isByoaKind } from './computer/registry.js'-import { companyTier } from '../tier.js'+import {+ resolveAgentHost,+ isByoaKind,+ type ResolvedAgentHost,+} from './computer/registry.js'import { deliver as deliverWake, deliverSteer, type PollWakeBrief } from './runtime/wake-bus.js'import { inprocClient, isAgentBusy } from './runtime/inproc-client.js'import { classifyInboxTriage, type InboxTriageVerdict } from './inbox-triage.js'@@ -56,7 +59,13 @@ export interface SteerWakePayload {}type WakeReason = 'message.new' | 'idle' | 'manual' | 'background_scan' | 'poll.updated'-type WakeOptions = Pick<AgentTurnOptions, 'idleReason' | 'backgroundBrief' | 'pollBrief' | 'triageNote'>+type WakeOptions = Pick<AgentTurnOptions, 'idleReason' | 'backgroundBrief' | 'pollBrief' | 'triageNote'> & {+ /** Exact durable notice to acknowledge before managed-runtime triage. */+ triageTarget?: { conversationId: string; messageId: string }+ /** Message fan-out must resolve placement before delivering to a live runtime. */+ placementTriage?: boolean+}+type WakeFailureClass = 'ensure_pod' | 'host_resolution'interface WakeRetryJob {id: string@@ -100,6 +109,18 @@ export function _shouldRetryEnsurePodFailure(reason: WakeReason, ensureReason: sreturn true}+/** Host lookup failed before any runtime was selected or started, so replay is+ * safe even for a durable message wake. This is deliberately separate from+ * ordinary ensurePod retries, whose message replay can duplicate a turn. */+export function _shouldRetryWakeFailure(+ reason: WakeReason,+ failureReason: string,+ failureClass: WakeFailureClass,+): boolean {+ if (failureClass === 'host_resolution') return true+ return _shouldRetryEnsurePodFailure(reason, failureReason)+}+function wakeRetryId(agentId: string, reason: WakeReason, conversationId: string | null): string {return `${agentId}:${reason}:${conversationId ?? '-'}`}@@ -112,8 +133,9 @@ async function scheduleWakeRetry(options: WakeOptions,attempt: number,failureReason: string,+ failureClass: WakeFailureClass = 'ensure_pod',): Promise<void> {- if (!_shouldRetryEnsurePodFailure(reason, failureReason)) return+ if (!_shouldRetryWakeFailure(reason, failureReason, failureClass)) returnconst id = wakeRetryId(agentId, reason, conversationId)if (attempt > WAKE_RETRY_MAX_ATTEMPTS) {await redis.hdel(WAKE_RETRY_JOB_KEY, id).catch(() => { /* ignore */ })@@ -132,7 +154,7 @@ async function scheduleWakeRetry(}await redis.hset(WAKE_RETRY_JOB_KEY, id, JSON.stringify(job))await redis.zadd(WAKE_RETRY_DUE_KEY, dueAt, id)- console.warn(`[scheduler] ${agentId} ${reason} wake retry scheduled in ${Math.round((dueAt - Date.now()) / 1000)}s after ensurePod failure: ${failureReason}`)+ console.warn(`[scheduler] ${agentId} ${reason} wake retry scheduled in ${Math.round((dueAt - Date.now()) / 1000)}s after ${failureClass}: ${failureReason}`)}async function pollWakeRetriesOnce(): Promise<void> {@@ -319,6 +341,59 @@ async function wakeOne(console.warn(`[scheduler] ${agentId} ${reason} wake dropped: budget ${LOW_PRIORITY_WAKE_BUDGET_PER_MIN}/min exceeded`)return}++ // Execution placement is an authorization decision, not a nullable hint.+ // A connected runtime can receive a direct wake without starting anything;+ // placement becomes mandatory for managed-message triage and whenever zero+ // subscribers would send us toward ensurePod.+ const resolveHostForWake = async (): Promise<ResolvedAgentHost | null> => {+ const hostResult = await resolveAgentHost(agentId)+ if (hostResult.status === 'missing') {+ console.warn(`[scheduler] ${agentId} wake ignored: no active agent row`)+ return null+ }+ if (hostResult.status === 'error') {+ const cause = hostResult.cause instanceof Error+ ? `: ${hostResult.cause.message}`+ : ''+ console.error(`[scheduler] ${hostResult.reason}${cause}`)+ if (hostResult.code === 'lookup_failed') {+ await scheduleWakeRetry(+ agentId,+ reason,+ conversationId,+ steerPayload,+ options,+ retryAttempt + 1,+ hostResult.reason,+ 'host_resolution',+ )+ } else {+ void notifyAlert({+ label: 'scheduler.invalid_agent_host_assignment',+ error: new Error(hostResult.reason),+ extras: { agentId, reason, conversationId },+ })+ }+ return null+ }+ return hostResult+ }++ let host: ResolvedAgentHost | null = null+ if (options.placementTriage) {+ host = await resolveHostForWake()+ if (!host) return+ // BYOA daemons triage locally. Managed Agents are gated before a live-pod+ // wake or a new Pod; the flag is serialized into retries so recovery cannot+ // bypass the same placement + triage contract.+ if (!isByoaKind(host.kind) && reason === 'message.new' && !options.triageNote) {+ const verdict = await triageWakeRecipient(agentId, options.triageTarget ?? null)+ if (!verdict) return+ options = { ...options, ...verdict }+ }+ }+const wakePayload = {kind: 'wake' as const,reason,@@ -389,13 +464,17 @@ async function wakeOne(if (delivered > 0) return+ if (!host) {+ host = await resolveHostForWake()+ if (!host) return+ }+// BYOA agents run on a user-paired Computer (the `cumora agent computer`// daemon), never a server-managed pod. If delivered === 0 the daemon// simply isn't subscribed right now (host offline / asleep) — there's// nothing to spin up. The wake is durable via the inbox, so the daemon// catches up on its next reconnect drain, same as a cold pod would.// Skip the pod path entirely; do NOT ensurePod / wake-retry kubectl.- const host = await resolveAgentHost(agentId).catch(() => ({ kind: null, companyId: null }))if (isByoaKind(host.kind)) {console.log(`[scheduler] ${agentId} is BYOA (${host.kind}); daemon offline — wake deferred to reconnect`)return@@ -409,7 +488,7 @@ async function wakeOne(// which silently ran thousands of free agents on managed cloud — a real cost// leak; the polluted legacy data (cloud computers + managed engines) was cleaned// up separately. The wake stays durable in the inbox for whenever they pair.- if (host.companyId && (await companyTier(host.companyId)) === 'free') {+ if (host.tier === 'free') {console.log(`[scheduler] ${agentId} is free-tier (BYOA-only); no managed pod — wake deferred until paired`)return}@@ -430,7 +509,16 @@ async function wakeOne(await scheduleWakeRetry(agentId, reason, conversationId, steerPayload, options, Math.max(1, retryAttempt + 1), 'post-spawn health check')} else if (!r.ok) {console.error(`[scheduler] ${agentId} ensurePod failed: ${r.reason}`)- await scheduleWakeRetry(agentId, reason, conversationId, steerPayload, options, retryAttempt + 1, r.reason)+ await scheduleWakeRetry(+ agentId,+ reason,+ conversationId,+ steerPayload,+ options,+ retryAttempt + 1,+ r.reason,+ r.code === 'placement_lookup_failed' ? 'host_resolution' : 'ensure_pod',+ )return} else if (r.reason === 'already pending' || r.reason === 'already running') {await scheduleWakeRetry(agentId, reason, conversationId, steerPayload, options, retryAttempt + 1, r.reason)@@ -847,29 +935,20 @@ export async function fanOutWake(// One recipient failing (triage throw, kubectl flake) must not stop// the others or escape into the Redis on-message handler.try {- // BYOA agents run an always-on daemon that triages locally (via- // /inbox-triage) before spending their engine, and are cheap to- // wake — there is no resting pod to gate, and the daemon ignores a- // server-side triageNote and re-triages anyway. So deliver the- // wake immediately and let the daemon decide. Only cloud/managed- // hosts pay the pre-wake triage, where it correctly avoids- // spinning up a pod for irrelevant chatter.- const host = await resolveAgentHost(m).catch(() => ({ kind: null, companyId: null }))- let triageOptions: WakeOptions | undefined- if (!isByoaKind(host.kind)) {- const verdict = await triageWakeRecipient(- m,- durableDelivery?.recipientId === m- ? { conversationId, messageId: durableDelivery.messageId }- : null,- )- if (!verdict) return // cloud triage said "not relevant" → no wake- triageOptions = verdict- }- // Await INSIDE the slot so it's held across ensurePod (kubectl)- // too — that's what bounds the child-process + pod-admission- // pressure, not just the triage DB reads.- await wakeOne(m, 'message.new', conversationId, steerPayload, triageOptions)+ // wakeOne owns the single placement decision and managed triage. Keeping+ // both inside the retryable operation prevents an earlier lookup failure+ // from being reinterpreted as cloud and preserves the durable departure+ // target across a retry.+ const options: WakeOptions = durableDelivery?.recipientId === m+ ? {+ placementTriage: true,+ triageTarget: { conversationId, messageId: durableDelivery.messageId },+ }+ : { placementTriage: true }+ // Await INSIDE the slot so it's held across host resolution, triage and+ // ensurePod (kubectl). That's what bounds DB, model and child-process+ // pressure together.+ await wakeOne(m, 'message.new', conversationId, steerPayload, options)} catch (err) {console.error(`[scheduler] wakeOne(${m}) failed:`, err instanceof Error ? err.message : err)}