Skip to content

armgit / orca

Public Imported from GitHub
0

Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

10.4 KB
Raw Blame
/** Scope hosts inside the answering IPC/RPC authority, never a caller-selected authority. Omitted selectors retain the full legacy list. Keep automations for old readers and qualify rows by ID in items without duplicating payloads. */

import type { Automation } from './automations-types'
import type { AutomationUsageSummary } from './automation-usage-summary'
import type { FolderWorkspaceHost } from './folder-workspace-execution-host'
import { getAutomationRunRepoId } from './automation-run-identity'
import { parseExecutionHostId } from './execution-host'
import { sanitizeSshTargetGeneration } from './ssh-target-generation'
import { isWorkspaceSshPinRepinned } from './automation-workspace-repin'

export type AutomationListScopeSelector =
  | { kind: 'self' }
  | { kind: 'ssh'; targetId: string; expectedTargetGeneration: number }
  | { kind: 'orphan' }

export type AutomationListParams = {
  /** Omitted, like `null` or `{}`, requests the authority's complete list. */
  selector?: AutomationListScopeSelector
}

export type AutomationListItemSelector =
  | { kind: 'self' }
  | { kind: 'ssh'; targetId: string; targetGeneration: number }
  | { kind: 'orphan'; issue: string }

export type AutomationListItem = {
  automationId: string
  selector: AutomationListItemSelector
  usageSummary?: AutomationUsageSummary | null
}

export type AutomationListResult = {
  automations: Automation[]
  items: AutomationListItem[]
  /** Optional authority-wide orphan count; preserve absence because zero would settle an uncounted bucket. */
  orphanCount?: number
}

/** What a host with no scoped list support returns, and all an old client reads. */
export type LegacyAutomationListResult = { automations: Automation[] }

export const AUTOMATION_ORPHAN_ISSUES = {
  targetMissing: 'Its SSH host is no longer registered.',
  targetReplaced: 'Its SSH host was removed and re-added, so it must be re-adopted.',
  scheduledElsewhere: 'It is stored here but scheduled against a remote runtime.',
  projectMissing: 'Its project no longer exists, so its host cannot be resolved.',
  projectUnverified: 'Its project could not be checked from here, so its host is unconfirmed.',
  workspaceHostAmbiguous: 'Its workspace spans more than one host, so it has no single owner.',
  malformed: 'Its stored host record is incomplete.'
} as const

/** Where a record's workspace executes; `unpinned` leaves the repo to decide. */
export type AutomationWorkspaceHost =
  | { kind: 'unpinned' }
  | Exclude<FolderWorkspaceHost, { kind: 'missing' }>

export type AutomationProjectionContext = {
  /** The process that owns this store; runtime scheduling markers are local only on a runtime. */
  storageAuthority?: 'desktop' | 'runtime'
  /** Current registration generation of a saved SSH target; undefined once it is gone. */
  sshTargetGeneration: (targetId: string) => number | undefined
  /** `undefined` = the repo is gone; `null` = a local repo; a string = its SSH connection. */
  repoConnectionId: (repoId: string) => string | null | undefined
  /** Host the record's workspace pins it to; omitted means no side knows of a pin. */
  workspaceHost?: (automation: Automation) => AutomationWorkspaceHost
  /** Registration a generation was allocated to; omitted leaves a re-pin unproven. */
  sshTargetIdForGeneration?: (generation: number) => string | undefined
  usageSummary?: (automationId: string) => AutomationUsageSummary | null
}

function orphan(issue: string): AutomationListItemSelector {
  return { kind: 'orphan', issue }
}

function sshSelector(
  automation: Automation,
  context: AutomationProjectionContext
): AutomationListItemSelector {
  const targetId = automation.executionTargetId?.trim()
  if (!targetId) {
    return orphan(AUTOMATION_ORPHAN_ISSUES.malformed)
  }
  return sshTargetSelector(targetId, automation.executionTargetGeneration, context)
}

function sshTargetSelector(
  targetId: string,
  capturedGeneration: number | undefined,
  context: AutomationProjectionContext
): AutomationListItemSelector {
  const current = context.sshTargetGeneration(targetId)
  if (current === undefined) {
    return orphan(AUTOMATION_ORPHAN_ISSUES.targetMissing)
  }
  const captured = sanitizeSshTargetGeneration(capturedGeneration)
  if (captured !== undefined && captured !== current) {
    return orphan(AUTOMATION_ORPHAN_ISSUES.targetReplaced)
  }
  return { kind: 'ssh', targetId, targetGeneration: captured ?? current }
}

/** Pins decide hosts; captures prove registration incarnation. A different live carrier proves an older pin, so discard that capture instead of treating it as a mismatch. */
function workspacePinSelector(
  automation: Automation,
  targetId: string,
  context: AutomationProjectionContext
): AutomationListItemSelector {
  const repinned = isWorkspaceSshPinRepinned({
    capturedGeneration: automation.executionTargetGeneration,
    pin: { targetId, generation: context.sshTargetGeneration(targetId) },
    sshTargetIdForGeneration: context.sshTargetIdForGeneration
  })
  return sshTargetSelector(
    targetId,
    repinned ? undefined : automation.executionTargetGeneration,
    context
  )
}

/** Runtime-only scheduling markers belong to runtime storage; local proves Self only with a resolved local project. */
export function projectAutomationSelector(
  automation: Automation,
  context: AutomationProjectionContext
): AutomationListItemSelector {
  if (
    context.storageAuthority !== 'runtime' &&
    (automation.schedulerOwner === 'remote_host_service' ||
      parseExecutionHostId(automation.runContext?.hostId)?.kind === 'runtime')
  ) {
    return orphan(AUTOMATION_ORPHAN_ISSUES.scheduledElsewhere)
  }
  if (automation.executionTargetType === 'ssh') {
    return sshSelector(automation, context)
  }
  if (automation.executionTargetType !== 'local') {
    return orphan(AUTOMATION_ORPHAN_ISSUES.malformed)
  }
  const workspaceHost = context.workspaceHost?.(automation) ?? { kind: 'unpinned' }
  if (workspaceHost.kind === 'ambiguous') {
    return orphan(AUTOMATION_ORPHAN_ISSUES.workspaceHostAmbiguous)
  }
  if (workspaceHost.kind === 'runtime') {
    return orphan(AUTOMATION_ORPHAN_ISSUES.scheduledElsewhere)
  }
  // A pinned workspace is where the run actually goes, so the row belongs to that host, not Self.
  if (workspaceHost.kind === 'ssh') {
    return workspacePinSelector(automation, workspaceHost.targetId, context)
  }
  const connectionId = context.repoConnectionId(getAutomationRunRepoId(automation))
  if (connectionId === undefined) {
    return orphan(AUTOMATION_ORPHAN_ISSUES.projectMissing)
  }
  // A local record whose project points at an SSH connection contradicts itself.
  return connectionId ? orphan(AUTOMATION_ORPHAN_ISSUES.malformed) : { kind: 'self' }
}

/** The orphan diagnoses that answer "does this record still have one usable host?" */
export type AutomationCapturedHostIssue =
  | typeof AUTOMATION_ORPHAN_ISSUES.targetMissing
  | typeof AUTOMATION_ORPHAN_ISSUES.targetReplaced
  | typeof AUTOMATION_ORPHAN_ISSUES.workspaceHostAmbiguous

// Key by the diagnosis union so every new host issue must also reach dispatch at compile time.
const CAPTURED_HOST_ISSUES: Record<AutomationCapturedHostIssue, true> = {
  [AUTOMATION_ORPHAN_ISSUES.targetMissing]: true,
  [AUTOMATION_ORPHAN_ISSUES.targetReplaced]: true,
  // No single owner is as unrunnable as no owner: dispatching would pick a host the user never chose.
  [AUTOMATION_ORPHAN_ISSUES.workspaceHostAmbiguous]: true
}

function isCapturedHostIssue(issue: string): issue is AutomationCapturedHostIssue {
  return Object.hasOwn(CAPTURED_HOST_ISSUES, issue)
}

/** Dispatch shares list owner diagnoses, preserving gone versus replaced hosts and refusal coalescing text. Other orphan reasons remain separate; scheduledElsewhere is work for the remote scheduler. */
export function automationCapturedHostIssue(
  automation: Automation,
  context: AutomationProjectionContext
): AutomationCapturedHostIssue | null {
  const selector = projectAutomationSelector(automation, context)
  if (selector.kind !== 'orphan') {
    return null
  }
  return isCapturedHostIssue(selector.issue) ? selector.issue : null
}

export function automationSelectorMatchesScope(
  selector: AutomationListItemSelector,
  scope: AutomationListScopeSelector
): boolean {
  if (scope.kind === 'ssh') {
    return (
      selector.kind === 'ssh' &&
      selector.targetId === scope.targetId &&
      selector.targetGeneration === scope.expectedTargetGeneration
    )
  }
  return selector.kind === scope.kind
}

/** Projects every stored automation, then narrows to the requested scope. */
export function projectAutomationList(
  automations: readonly Automation[],
  context: AutomationProjectionContext,
  scope?: AutomationListScopeSelector
): AutomationListResult {
  const scopedAutomations: Automation[] = []
  const items: AutomationListItem[] = []
  let orphanCount = 0
  for (const automation of automations) {
    const selector = projectAutomationSelector(automation, context)
    if (selector.kind === 'orphan') {
      orphanCount += 1
    }
    if (scope && !automationSelectorMatchesScope(selector, scope)) {
      continue
    }
    scopedAutomations.push(automation)
    items.push({
      automationId: automation.id,
      selector
    })
  }
  // Keep usage lookups after projection, matching the previous staged pipeline's ordering.
  if (context.usageSummary) {
    for (const item of items) {
      item.usageSummary = context.usageSummary(item.automationId)
    }
  }
  return {
    automations: scopedAutomations,
    items,
    orphanCount
  }
}

/** What a scoped `automationsChanged` event names; carries no incarnation, only the stable host. */
export type AutomationChangeSelector =
  | { kind: 'self' }
  | { kind: 'ssh'; targetId: string }
  | { kind: 'orphan' }

export function toAutomationChangeSelector(
  selector: AutomationListItemSelector
): AutomationChangeSelector {
  return selector.kind === 'ssh'
    ? { kind: 'ssh', targetId: selector.targetId }
    : { kind: selector.kind }
}

/** Publish both moved-from/to selectors. If either cannot be recovered, publish one unscoped authority event so no subscriber retains a vanished row. */
export function automationChangePublications(
  before: AutomationChangeSelector | null,
  after: AutomationChangeSelector | null
): (AutomationChangeSelector | undefined)[] {
  if (!before || !after) {
    return [undefined]
  }
  const sameHost =
    before.kind === after.kind &&
    (before.kind !== 'ssh' || after.kind !== 'ssh' || before.targetId === after.targetId)
  return sameHost ? [after] : [before, after]
}