feat(orchestration): bundled improvements — check-wait, stale-base, preamble+ask, QoL (#1403)

* feat(orchestration): transport keepalive + delivered_at split for check --wait

Implements the four §3 fixes from the check-wait design doc:

- §3.1 Transport keepalive: long-poll RPCs (orchestration.check --wait) emit
  `{"_keepalive":true}` frames every 10s so neither server nor client tears
  the socket down on idle. A `longPoll` admission counter capped at 16 fails
  fast with `runtime_busy` when saturated; an AbortController wired through
  the RPC dispatcher cancels the inner waiter the moment the socket closes.
- §3.2 delivered_at split: push-on-idle now stamps `delivered_at` instead of
  flipping `read`, so the check caller remains the sole consumer of its
  queue. Adds a synchronous idempotent schema migration that hard-fails on
  error.
- §3.3 inbox/check parity: `orchestration inbox --terminal <handle>` and
  `orchestration check --all` agree on the same rows (sequence DESC, no
  mark-read). `check --unread=false` kept for one release as a compat shim.
- §3.4 CLI heartbeat: `orca orchestration check --wait` emits JSON heartbeat
  lines to stderr every 15s so Claude Code's Bash tool sees continuous
  output and doesn't auto-background the subprocess.

Tests: extends runtime-rpc, orca-runtime, envelope-schema, orchestration
method, and formatter suites; adds a subprocess test that spawns the built
CLI and verifies stderr line-flushing, heartbeat cadence, and stdout
cleanliness end-to-end.

Co-authored-by: Orca <help@stably.ai>

* feat(orchestration): preamble rules + heartbeat schema

- Preamble (#7, #15, #9): worker_done body ("3-sentence summary" + reportPath),
  BEHAVIOR RULE #1 forbidding AskUserQuestion, heartbeat every 5 minutes with
  taskId+dispatchId payload, AFTER YOU SEND grace window.
- Schema v2 migration: adds 'heartbeat' to messages.type CHECK, adds
  dispatch_contexts.last_heartbeat_at, gated by user_version PRAGMA with
  transactional rebuild + explicit CREATE INDEX to avoid silent perf regress.
- DB helpers: recordHeartbeat (dispatched-only), getStaleDispatches,
  getThreadMessagesFor (thread+handle scoped for ask).

Co-authored-by: Orca <help@stably.ai>

* feat(orchestration): coordinator heartbeat + stale detector

Handle incoming 'heartbeat' messages by calling recordHeartbeat keyed on
payload.dispatchId (strict — log-and-skip if missing, no taskId fallback so
a straggler heartbeat from a previously-failed dispatch cannot mask a hung
retry per §5.3.4). On every tick after the 10-minute threshold, emit one
log per stale dispatched row — no auto-fail.

Also threads dispatchId through buildDispatchPreamble so workers can
attribute their heartbeats back to the correct dispatch context.

Co-authored-by: Orca <help@stably.ai>

* feat(orchestration): orca orchestration ask verb

Adds a CLI verb that sends a decision_gate message and blocks on the
coordinator's reply, scoped to the outbound message's thread. Group
addresses (@all, @idle, …) are rejected — fan-out questions must use
send --type decision_gate explicitly.

--json emits bare single-line JSON (bypassing printResult) so workers can
pipe `orca orchestration ask … --json | jq -r .answer` without unwrapping
an RPC envelope; human mode prints just the answer. On timeout the verb
exits 1 and returns {answer: null, timedOut: true}.

This is the CLI surface BEHAVIOR RULE #1 in the dispatch preamble points
workers at instead of AskUserQuestion.

Co-authored-by: Orca <help@stably.ai>

* feat(orchestration): QoL bundle — preamble visibility, status enum, dispatch cross-ref, inbox --full

Addresses four items from ORCHESTRATOR_FEEDBACK:

- #5 preamble visibility: `dispatch-show --preamble` regenerates the preamble
  text for a task; `dispatch --inject --dry-run` previews without mutating
  state; `dispatch --return-preamble` echoes the injected preamble in the JSON
  response so coordinators can audit what a worker received.
- #6 status enum validation: CLI rejects unknown `task-update --status` values
  with `invalid status '<x>', expected one of: pending, ready, dispatched,
  completed, failed, blocked` before the RPC's generic Zod message. Valid
  statuses are listed under Notes in `task-update --help`.
- #13 task-list dispatch cross-ref: `task-list --json` now includes
  `assignee_handle` and `dispatch_id` for tasks in status=dispatched via a
  read-only LEFT JOIN on dispatch_contexts. Non-dispatched rows keep their
  legacy shape so existing consumers are unaffected.
- #14 inbox body visibility: `inbox --full` prints body + payload verbatim;
  default output is unchanged (id/from/to/subject only).

No DB migrations; join-only change on dispatch_contexts so the sibling
preamble PR's `last_heartbeat_at` column addition will not conflict.

Co-authored-by: Orca <help@stably.ai>

* fix(worktree): prevent stale-base worktree creation and dispatch

Addresses feedback #16 per DESIGN_DOC_STALE_BASE_FIX.md §0. Four v1
components coordinated by a single shared fetch cache on the runtime:

1. Concurrent-fetch-with-gate in UI create path: `createLocalWorktree`
   fires `git fetch` BEFORE the suffix loop / PR probe / path
   resolution, then awaits right before `addWorktree` so the new branch
   always spawns from a fresh remote tip. Renderer sees a two-phase
   spinner via the new `createWorktree:progress` IPC event. The cache
   is a `Map<repoPath::remote, Promise<void>>` + 30s success-only
   timestamp on `OrcaRuntimeService` (§7.1 — shared with dispatch).
2. Dispatch pre-flight drift guard in `Coordinator.dispatchTask`:
   probes `rev-list --left-right --count` against the target worktree
   and silently returns (preserves `ready`, no circuit-breaker burn)
   when `behind > 20` unless the task spec carries
   `allow-stale-base: true`. Parsing strips the flag so it never leaks
   into the worker's `--- TASK ---` block.
3. Preamble drift section: populated only when dispatch detected drift.
   Workers see `--- BASE DRIFT ---` with the N-most-recent subjects
   they don't have, so they can pull them in before running.
4. §3.3 Lifecycle: `.finally()` evicts Map entries on BOTH success and
   rejection; timestamp is written ONLY on success. Prevents a single
   DNS hiccup from wedging every future create on the repo until
   restart, and keeps the freshness window honest.

Defers the DB `allow_stale_base` column (§0.2) and the create-time
warn toast; both can layer in later without migration.

Tests: 35 new/updated unit tests covering drift preamble, dispatch
refusal, spec-text flag parsing, fetch Map eviction after rejection,
freshness-window short-circuit, and concurrent-caller serialization.

Co-authored-by: Orca <help@stably.ai>

* test(orchestration): seed v2 DB in migration hard-fail test

After consolidating the schema bump, fresh DBs are initialized directly at
v3 via createTables(), so the v2→v3 ALTER TABLE is skipped on new installs
and the prior test's stub never fired. Seed a v2-shape file on disk so the
guarded ALTER actually runs and the "simulated migration failure" stub
propagates as intended.

Co-authored-by: Orca <help@stably.ai>

---------

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Jinwoo Hong
2026-05-04 12:10:53 -07:00
committed by GitHub
co-authored by Orca
parent aad70f46b8
commit ea8ea08116
31 changed files with 3569 additions and 265 deletions
+213 -34
View File
@@ -1,3 +1,4 @@
/* eslint-disable max-lines -- Why: orchestration CLI handlers share flag-parsing helpers and dispatch/preamble logic; splitting by verb would fragment the RuntimeClient call shape without reducing complexity. */
import type { CommandHandler } from '../dispatch'
import { printResult } from '../format'
import {
@@ -5,14 +6,70 @@ import {
getOptionalStringFlag,
getRequiredStringFlag
} from '../flags'
import { RuntimeClientError } from '../runtime-client'
import { getTerminalHandle } from '../selectors'
// Why: 15 s is well under Claude Code's empirical ~2 min Bash-tool silence
// budget and generates only ~40 lines per 10 min wait — enough to assure the
// parent process the subprocess is alive without flooding logs. See design
// doc §3.4.
const DEFAULT_HEARTBEAT_INTERVAL_MS = 15_000
// Why: test-only escape hatch so subprocess tests can verify the feature in
// under 10 s rather than needing a full 15 s silence window. Production users
// should never set this — there is no surface documentation. A bogus value
// falls back to the default rather than disabling the heartbeat.
function resolveHeartbeatIntervalMs(): number {
const raw = process.env.ORCA_HEARTBEAT_INTERVAL_MS
if (!raw) {
return DEFAULT_HEARTBEAT_INTERVAL_MS
}
const parsed = Number(raw)
if (!Number.isFinite(parsed) || parsed <= 0) {
return DEFAULT_HEARTBEAT_INTERVAL_MS
}
return parsed
}
function startCheckHeartbeat(deadlineMs: number | undefined): () => void {
const startedAt = Date.now()
const interval = setInterval(() => {
const payload = {
_heartbeat: true,
elapsedMs: Date.now() - startedAt,
deadlineMs: deadlineMs ?? null
}
// Why: `process.stderr.write` is line-flushed per-call in Node, whereas a
// fully-buffered writer would hold all heartbeat lines until exit and
// silently defeat the whole point of the ping. Subprocess test asserts
// this by reading stderr incrementally. See §3.4.
process.stderr.write(`${JSON.stringify(payload)}\n`)
}, resolveHeartbeatIntervalMs())
if (typeof interval.unref === 'function') {
interval.unref()
}
return () => clearInterval(interval)
}
// Why: mirrors TaskStatus (orchestration/types.ts) so the CLI can surface a
// clear enum-aware error before the generic RPC Zod "Missing --status" message.
const TASK_STATUS_VALUES = [
'pending',
'ready',
'dispatched',
'completed',
'failed',
'blocked'
] as const
type MessageSummary = {
id: string
from_handle: string
to_handle?: string
subject: string
type?: string
body?: string
payload?: string | null
}
async function resolveOrchestrationTerminalHandle(
@@ -62,18 +119,36 @@ export const ORCHESTRATION_HANDLERS: Record<string, CommandHandler> = {
'orchestration check': async ({ flags, client, cwd, json }) => {
const terminal = await resolveOrchestrationTerminalHandle(flags, cwd, client, 'terminal')
const result = await client.call<{
const wait = flags.has('wait')
const timeoutMs = flags.has('timeout-ms') ? Number(flags.get('timeout-ms')) : undefined
// Why: Claude Code's Bash tool auto-backgrounds subprocesses that produce
// no output for ~2 min (shorter on the non-interactive path). Emit a
// heartbeat line to stderr every HEARTBEAT_INTERVAL_MS while the wait is
// active so the parent process can see the subprocess is still alive.
// Stderr rather than stdout so stdout stays a single final JSON payload,
// and JSON-shaped rather than `# …` so `2>&1 | jq` pipelines still work
// (jq refuses `#`-prefixed lines). See design doc §3.4.
const stopHeartbeat = wait ? startCheckHeartbeat(timeoutMs) : null
type CheckResult = {
messages: MessageSummary[]
count: number
formatted?: string
}>('orchestration.check', {
terminal,
unread: flags.has('unread') ? true : undefined,
types: getOptionalStringFlag(flags, 'types'),
inject: flags.has('inject') ? true : undefined,
wait: flags.has('wait') ? true : undefined,
timeoutMs: flags.has('timeout-ms') ? Number(flags.get('timeout-ms')) : undefined
})
}
let result: Awaited<ReturnType<typeof client.call<CheckResult>>>
try {
result = await client.call<CheckResult>('orchestration.check', {
terminal,
unread: flags.has('unread') ? true : undefined,
all: flags.has('all') ? true : undefined,
types: getOptionalStringFlag(flags, 'types'),
inject: flags.has('inject') ? true : undefined,
wait: wait ? true : undefined,
timeoutMs
})
} finally {
stopHeartbeat?.()
}
printResult(result, json, (r) => {
if (r.formatted) {
return r.formatted
@@ -98,19 +173,36 @@ export const ORCHESTRATION_HANDLERS: Record<string, CommandHandler> = {
},
'orchestration inbox': async ({ flags, client, json }) => {
const full = flags.has('full')
const result = await client.call<{
messages: MessageSummary[]
count: number
}>('orchestration.inbox', {
limit: getOptionalPositiveIntegerFlag(flags, 'limit')
limit: getOptionalPositiveIntegerFlag(flags, 'limit'),
terminal: getOptionalStringFlag(flags, 'terminal')
})
printResult(result, json, (r) => {
if (r.count === 0) {
return 'No messages.'
}
// Why: default output omits body/payload for at-a-glance sweeps; --full
// prints them verbatim so callers can audit without parsing --json.
return r.messages
.map((m) => `${m.id} ${m.from_handle} -> ${m.to_handle ?? '?'}: "${m.subject}"`)
.join('\n')
.map((m) => {
const head = `${m.id} ${m.from_handle} -> ${m.to_handle ?? '?'}: "${m.subject}"`
if (!full) {
return head
}
const parts = [head]
if (m.body && m.body.length > 0) {
parts.push(m.body)
}
if (m.payload) {
parts.push(`[payload] ${m.payload}`)
}
return parts.join('\n')
})
.join(full ? '\n\n' : '\n')
})
},
@@ -128,7 +220,13 @@ export const ORCHESTRATION_HANDLERS: Record<string, CommandHandler> = {
'orchestration task-list': async ({ flags, client, json }) => {
const result = await client.call<{
tasks: { id: string; spec: string; status: string }[]
tasks: {
id: string
spec: string
status: string
assignee_handle?: string | null
dispatch_id?: string | null
}[]
count: number
}>('orchestration.taskList', {
status: getOptionalStringFlag(flags, 'status'),
@@ -138,16 +236,31 @@ export const ORCHESTRATION_HANDLERS: Record<string, CommandHandler> = {
if (r.count === 0) {
return 'No tasks.'
}
return r.tasks.map((t) => `${t.id} [${t.status}] ${t.spec.slice(0, 60)}`).join('\n')
return r.tasks
.map((t) => {
const head = `${t.id} [${t.status}] ${t.spec.slice(0, 60)}`
if (t.status === 'dispatched' && t.assignee_handle) {
return `${head} -> ${t.assignee_handle} (${t.dispatch_id ?? '?'})`
}
return head
})
.join('\n')
})
},
'orchestration task-update': async ({ flags, client, json }) => {
const status = getRequiredStringFlag(flags, 'status')
if (!TASK_STATUS_VALUES.includes(status as (typeof TASK_STATUS_VALUES)[number])) {
throw new RuntimeClientError(
'invalid_argument',
`invalid status '${status}', expected one of: ${TASK_STATUS_VALUES.join(', ')}`
)
}
const result = await client.call<{ task: { id: string; status: string } }>(
'orchestration.taskUpdate',
{
id: getRequiredStringFlag(flags, 'id'),
status: getRequiredStringFlag(flags, 'status'),
status,
result: getOptionalStringFlag(flags, 'result')
}
)
@@ -156,29 +269,95 @@ export const ORCHESTRATION_HANDLERS: Record<string, CommandHandler> = {
'orchestration dispatch': async ({ flags, client, cwd, json }) => {
const from = await resolveOrchestrationTerminalHandle(flags, cwd, client, 'from')
const result = await client.call<{
dispatch: { id: string; task_id: string; status: string }
}>('orchestration.dispatch', {
task: getRequiredStringFlag(flags, 'task'),
to: getRequiredStringFlag(flags, 'to'),
from,
inject: flags.has('inject') ? true : undefined,
devMode: isDevCliInvocation()
})
printResult(
result,
json,
(r) => `Dispatched ${r.dispatch.task_id} -> ${r.dispatch.id} [${r.dispatch.status}]`
)
},
'orchestration dispatch-show': async ({ flags, client, json }) => {
const dryRun = flags.has('dry-run') ? true : undefined
const returnPreamble = flags.has('return-preamble') ? true : undefined
// Why: --to is only required for non-dry-run; the RPC handler re-enforces.
const to = dryRun ? getOptionalStringFlag(flags, 'to') : getRequiredStringFlag(flags, 'to')
const result = await client.call<{
dispatch: { id: string; task_id: string; status: string } | null
}>('orchestration.dispatchShow', {
task: getRequiredStringFlag(flags, 'task')
injected?: boolean
dryRun?: boolean
preamble?: string
}>('orchestration.dispatch', {
task: getRequiredStringFlag(flags, 'task'),
to,
from,
inject: flags.has('inject') ? true : undefined,
dryRun,
returnPreamble,
devMode: isDevCliInvocation()
})
printResult(result, json, (r) => {
if (r.dryRun) {
return r.preamble ?? ''
}
const base = `Dispatched ${r.dispatch?.task_id} -> ${r.dispatch?.id} [${r.dispatch?.status}]`
return r.preamble ? `${base}\n\n--- Preamble ---\n${r.preamble}` : base
})
},
'orchestration ask': async ({ flags, client, cwd, json }) => {
const from = await resolveOrchestrationTerminalHandle(flags, cwd, client, 'from')
const timeoutMs = flags.has('timeout-ms') ? Number(flags.get('timeout-ms')) : 600_000
const result = await client.call<{
answer: string | null
messageId: string | null
threadId: string
timedOut: boolean
}>(
'orchestration.ask',
{
to: getRequiredStringFlag(flags, 'to'),
question: getRequiredStringFlag(flags, 'question'),
options: getOptionalStringFlag(flags, 'options'),
timeoutMs: flags.has('timeout-ms') ? Number(flags.get('timeout-ms')) : undefined,
from
},
// Why: the runtime's `waitForMessage` can block up to `timeoutMs`, but
// the RPC transport has its own 60s default timeout that would fire
// first. Extend the per-call timeout by a small grace window so the
// RPC doesn't abort before the runtime's internal timeout resolves.
{ timeoutMs: timeoutMs + 5_000 }
)
// Why: deliberate bypass of `printResult`. `--json` on `ask` emits a
// single-line bare JSON object (no RPC envelope, no multi-line pretty-
// print) so workers can pipe `orca orchestration ask … --json | jq -r
// .answer` without reaching into a `result` envelope. This diverges from
// every other orchestration verb; called out in the commit message and
// guarded by a unit test in orchestration.test.ts.
if (json) {
console.log(JSON.stringify(result.result))
} else if (result.result.answer !== null) {
console.log(result.result.answer)
}
if (result.result.timedOut) {
if (!json) {
console.error(`ask timeout after ${timeoutMs}ms (thread ${result.result.threadId})`)
}
process.exitCode = 1
}
},
'orchestration dispatch-show': async ({ flags, client, cwd, json }) => {
const showPreamble = flags.has('preamble') ? true : undefined
// Why: resolve --from when previewing so the preamble embeds a real
// coordinator handle, matching what an actual dispatch would produce.
const from = showPreamble
? await resolveOrchestrationTerminalHandle(flags, cwd, client, 'from')
: undefined
const result = await client.call<{
dispatch: { id: string; task_id: string; status: string } | null
preamble?: string
}>('orchestration.dispatchShow', {
task: getRequiredStringFlag(flags, 'task'),
preamble: showPreamble,
from,
devMode: isDevCliInvocation()
})
printResult(result, json, (r) => {
if (r.preamble && showPreamble) {
return r.preamble
}
if (!r.dispatch) {
return 'No dispatch context found.'
}
+25
View File
@@ -197,6 +197,31 @@ describe('orca cli worktree awareness', () => {
expect(logSpy).toHaveBeenCalledWith('Sent 2 messages to 2 recipients')
})
it('rejects unknown task-update status with an enum-aware error', async () => {
process.env.ORCA_TERMINAL_HANDLE = 'term_coord'
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
const priorExitCode = process.exitCode
await main(
['orchestration', 'task-update', '--id', 'task_x', '--status', 'complete'],
'/tmp/repo'
)
const output = [...errSpy.mock.calls, ...logSpy.mock.calls]
.flat()
.map((v) => (typeof v === 'string' ? v : JSON.stringify(v)))
.join('\n')
expect(output).toContain("invalid status 'complete'")
expect(output).toContain('pending, ready, dispatched, completed, failed, blocked')
expect(callMock).not.toHaveBeenCalled()
expect(process.exitCode).toBe(1)
// Reset exitCode so subsequent tests don't inherit the failure.
process.exitCode = priorExitCode
errSpy.mockRestore()
})
it('passes dev mode to injected orchestration dispatches', async () => {
process.env.ORCA_TERMINAL_HANDLE = 'term_sender'
process.env.ORCA_USER_DATA_PATH = '/tmp/orca-dev'
+158
View File
@@ -0,0 +1,158 @@
// Why: subprocess-level test for the CLI heartbeat behavior described in
// design doc §3.4. Spawns the real compiled CLI with no TTY, points it at a
// real in-process runtime via ORCA_USER_DATA_PATH, and asserts:
// - the first heartbeat line appears on stderr well under Claude Code's
// ~2 min Bash-tool silence budget (we verify with a shortened interval;
// production uses 15 s via the same code path)
// - ≥3 heartbeats arrive during the wait window
// - stderr is line-flushed (we observe each heartbeat as a separate chunk
// before the process exits — not in one burst at the end)
// - stdout stays a single clean JSON payload (no heartbeats leak to stdout)
// - a `jq "select(._heartbeat|not)"` filter on the merged stream would
// yield exactly the final result
//
// This test is skipped if the CLI hasn't been built yet (out/cli/index.js
// missing) so `pnpm test` works on a fresh checkout without requiring a prior
// `pnpm run build:cli`. The verification gate explicitly builds the CLI
// before running this file.
import { spawn } from 'child_process'
import { existsSync, mkdtempSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { describe, expect, it } from 'vitest'
import { OrcaRuntimeService } from '../main/runtime/orca-runtime'
import { OrchestrationDb } from '../main/runtime/orchestration/db'
import { OrcaRuntimeRpcServer } from '../main/runtime/runtime-rpc'
// Why: Vitest runs tests with `process.cwd()` pinned to the repo root, so
// join against it to locate the compiled CLI regardless of where this test
// file itself lives.
const CLI_PATH = join(process.cwd(), 'out', 'cli', 'index.js')
const describeIfBuilt = existsSync(CLI_PATH) ? describe : describe.skip
describeIfBuilt('orca orchestration check --wait subprocess (§3.4)', () => {
it('emits newline-flushed JSON heartbeats to stderr while waiting', async () => {
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-cli-sub-'))
const runtime = new OrcaRuntimeService()
const db = new OrchestrationDb(':memory:')
runtime.setOrchestrationDb(db)
const server = new OrcaRuntimeRpcServer({ runtime, userDataPath })
await server.start()
try {
// Why: use the ORCA_HEARTBEAT_INTERVAL_MS escape hatch to shrink the
// test to ~1 s wall time. Production callers never set this; the
// production default (15 s) is exercised by §3.4's own unit tests
// and by the fact that this same code path runs with the real
// constant when the env var is absent.
const heartbeatMs = 200
const waitTimeoutMs = 1200
const child = spawn(
process.execPath,
[
CLI_PATH,
'orchestration',
'check',
'--wait',
'--timeout-ms',
String(waitTimeoutMs),
'--json'
],
{
env: {
...process.env,
ORCA_USER_DATA_PATH: userDataPath,
ORCA_TERMINAL_HANDLE: 'term_nobody',
ORCA_HEARTBEAT_INTERVAL_MS: String(heartbeatMs)
},
// Why: explicit pipe for all three fds so we can watch stderr
// in real time; no TTY attached (Bash-tool parity).
stdio: ['ignore', 'pipe', 'pipe']
}
)
const stderrChunks: { at: number; data: string }[] = []
const stdoutChunks: { at: number; data: string }[] = []
const startedAt = Date.now()
child.stderr.setEncoding('utf8')
child.stdout.setEncoding('utf8')
child.stderr.on('data', (d) => stderrChunks.push({ at: Date.now() - startedAt, data: d }))
child.stdout.on('data', (d) => stdoutChunks.push({ at: Date.now() - startedAt, data: d }))
const exitCode = await new Promise<number>((resolveExit, rejectExit) => {
child.once('exit', (code) => resolveExit(code ?? 1))
child.once('error', rejectExit)
})
expect(exitCode).toBe(0)
const stderr = stderrChunks.map((c) => c.data).join('')
const stdout = stdoutChunks.map((c) => c.data).join('')
const heartbeatLines = stderr
.split('\n')
.filter((line) => line.trim().length > 0)
.map((line) => {
try {
return JSON.parse(line) as Record<string, unknown>
} catch {
return null
}
})
.filter((p): p is Record<string, unknown> => p !== null && p._heartbeat === true)
// ≥3 heartbeats in a 1.2s window with a 200ms interval
expect(heartbeatLines.length).toBeGreaterThanOrEqual(3)
expect(heartbeatLines[0]).toHaveProperty('elapsedMs')
expect(heartbeatLines[0]).toHaveProperty('deadlineMs', waitTimeoutMs)
// Why: first heartbeat must arrive within one interval + scheduler
// slack (300ms is generous); if the stream were fully buffered we'd
// see everything only after exit.
const firstHeartbeatChunk = stderrChunks.find((c) => c.data.includes('_heartbeat'))
expect(firstHeartbeatChunk).toBeDefined()
expect(firstHeartbeatChunk!.at).toBeLessThan(heartbeatMs + 300)
// Why: line-flushing proof — the *first* heartbeat chunk must arrive
// strictly before the exit chunk; i.e. we got at least two separate
// stderr data events (heartbeat + final). A single-chunk delivery
// would indicate stderr was buffered until exit.
const lastStderrAt = stderrChunks.at(-1)?.at ?? 0
const firstStderrAt = stderrChunks.at(0)?.at ?? 0
expect(lastStderrAt).toBeGreaterThan(firstStderrAt)
// Stdout: exactly one JSON payload, the terminal result. No heartbeats
// leak, and the content parses as valid JSON.
const stdoutTrimmed = stdout.trim()
const stdoutPayload = JSON.parse(stdoutTrimmed) as Record<string, unknown>
expect(stdoutPayload).not.toHaveProperty('_heartbeat')
expect(stdoutTrimmed).not.toContain('_heartbeat')
// Why: result should be an RPC success envelope with the expected
// shape. `count: 0` and `messages: []` because the wait timed out
// with no message for term_nobody.
expect(stdoutPayload).toMatchObject({ ok: true })
// Why: the heartbeats-on-stderr design is meant to pair with shell
// filters like `2>&1 | jq "select(._heartbeat|not)"`. jq is
// line-oriented by default, but also accepts pretty-printed JSON
// across multiple lines. What matters here is that every
// heartbeat line on stderr is a standalone JSON object (so jq can
// match it) and doesn't span multiple lines — assert that each
// heartbeat is a single-line JSON with no embedded newlines.
for (const line of stderr.split('\n')) {
if (line.trim().length === 0) {
continue
}
if (line.includes('_heartbeat')) {
expect(() => JSON.parse(line)).not.toThrow()
expect(line).not.toContain('\n')
}
}
} finally {
db.close()
await server.stop()
}
}, 30_000)
})
+35 -6
View File
@@ -5,6 +5,14 @@ import { getCliStatus } from './status'
import { sendRequest } from './transport'
import { RuntimeClientError, RuntimeRpcFailureError, type RuntimeRpcSuccess } from './types'
// Why: for `orchestration.check --wait` the caller's method-level
// `params.timeoutMs` is the inner waiter budget; we extend the client-side
// socket timeout to `timeoutMs + GRACE_MS` so the client's own idle timer
// never fires before the server-side waiter has had a chance to resolve and
// emit its terminal frame. The 10 s grace absorbs round-trip + one final
// keepalive window. See design doc §3.1.
const LONG_POLL_CLIENT_GRACE_MS = 10_000
export class RuntimeClient {
private readonly userDataPath: string
private readonly requestTimeoutMs: number
@@ -25,18 +33,30 @@ export class RuntimeClient {
}
): Promise<RuntimeRpcSuccess<TResult>> {
const metadata = readMetadata(this.userDataPath)
const response = await sendRequest<TResult>(
metadata,
method,
params,
options?.timeoutMs ?? this.requestTimeoutMs
)
const effectiveTimeoutMs = options?.timeoutMs ?? this.resolveMethodTimeoutMs(method, params)
const response = await sendRequest<TResult>(metadata, method, params, effectiveTimeoutMs)
if (!response.ok) {
throw new RuntimeRpcFailureError(response)
}
return response
}
// Why: centralises the per-method timeout policy. `orchestration.check` with
// `wait: true` is the only long-poll today, and its inner waiter budget
// lives in `params.timeoutMs`. We widen the client-side socket timeout to
// `timeoutMs + grace` so it doesn't fire before the server has a chance to
// resolve. Without this, a 5 min wait would still die at the 60 s default.
// See design doc §3.1.
private resolveMethodTimeoutMs(method: string, params?: unknown): number {
if (method === 'orchestration.check' && isWaitingCheck(params)) {
const inner = Number((params as { timeoutMs?: unknown }).timeoutMs)
if (Number.isFinite(inner) && inner > 0) {
return Math.max(inner + LONG_POLL_CLIENT_GRACE_MS, this.requestTimeoutMs)
}
}
return this.requestTimeoutMs
}
async getCliStatus(): Promise<RuntimeRpcSuccess<CliStatusResult>> {
return getCliStatus(this.userDataPath)
}
@@ -67,3 +87,12 @@ export class RuntimeClient {
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
function isWaitingCheck(params: unknown): boolean {
return (
typeof params === 'object' &&
params !== null &&
'wait' in params &&
(params as { wait: unknown }).wait === true
)
}
+34 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
import { RuntimeRpcEnvelopeSchema } from './envelope-schema'
import { RuntimeRpcEnvelopeSchema, isKeepaliveFrame } from './envelope-schema'
describe('RuntimeRpcEnvelopeSchema', () => {
it('accepts a well-formed success envelope', () => {
@@ -57,4 +57,37 @@ describe('RuntimeRpcEnvelopeSchema', () => {
const parsed = RuntimeRpcEnvelopeSchema.safeParse({ hello: 'world' })
expect(parsed.success).toBe(false)
})
it('accepts a keepalive frame', () => {
const parsed = RuntimeRpcEnvelopeSchema.safeParse({ _keepalive: true })
expect(parsed.success).toBe(true)
})
it('rejects a keepalive frame with _keepalive !== true', () => {
const parsed = RuntimeRpcEnvelopeSchema.safeParse({ _keepalive: false })
expect(parsed.success).toBe(false)
})
})
describe('isKeepaliveFrame', () => {
it('returns true for a well-formed keepalive', () => {
expect(isKeepaliveFrame({ _keepalive: true })).toBe(true)
})
it('returns false for a success envelope', () => {
expect(isKeepaliveFrame({ id: 'x', ok: true, result: {}, _meta: { runtimeId: 'r' } })).toBe(
false
)
})
it('returns false for non-object inputs', () => {
expect(isKeepaliveFrame(null)).toBe(false)
expect(isKeepaliveFrame(undefined)).toBe(false)
expect(isKeepaliveFrame('keepalive')).toBe(false)
})
it('returns false when _keepalive is not strictly true', () => {
expect(isKeepaliveFrame({ _keepalive: 1 })).toBe(false)
expect(isKeepaliveFrame({ _keepalive: 'true' })).toBe(false)
})
})
+24 -1
View File
@@ -36,4 +36,27 @@ const Failure = z.object({
_meta: MetaFailure
})
export const RuntimeRpcEnvelopeSchema = z.discriminatedUnion('ok', [Success, Failure])
// Why: transport-layer keepalive frame (server→client only). Not a terminal
// frame — the client reads past it and keeps waiting for the real
// success/failure. `id` and `_meta` are deliberately absent: keepalives carry
// no method-level semantics and aren't tied to a particular request (one
// connection handles one request today). See design doc §3.1.
const Keepalive = z.object({
_keepalive: z.literal(true)
})
// Why: switched from z.discriminatedUnion('ok', …) to z.union because
// keepalives have no `ok` field. Client code must branch on
// `'_keepalive' in frame` before treating the frame as Success/Failure.
export const RuntimeRpcEnvelopeSchema = z.union([Success, Failure, Keepalive])
export type RuntimeRpcKeepaliveFrame = z.infer<typeof Keepalive>
export function isKeepaliveFrame(frame: unknown): frame is RuntimeRpcKeepaliveFrame {
return (
typeof frame === 'object' &&
frame !== null &&
'_keepalive' in frame &&
(frame as { _keepalive: unknown })._keepalive === true
)
}
+100 -45
View File
@@ -1,7 +1,7 @@
import { createConnection } from 'net'
import { randomUUID } from 'crypto'
import type { RuntimeMetadata, RuntimeTransportMetadata } from '../../shared/runtime-bootstrap'
import { RuntimeRpcEnvelopeSchema } from './envelope-schema'
import { isKeepaliveFrame, RuntimeRpcEnvelopeSchema } from './envelope-schema'
import { RuntimeClientError, type RuntimeRpcResponse } from './types'
export async function sendRequest<TResult>(
@@ -13,9 +13,14 @@ export async function sendRequest<TResult>(
return await new Promise((resolve, reject) => {
const socket = createConnection(getTransportEndpoint(metadata.transport!))
let buffer = ''
let settled = false
const requestId = randomUUID()
const timeout = setTimeout(() => {
if (settled) {
return
}
settled = true
socket.destroy()
reject(
new RuntimeClientError(
@@ -25,28 +30,72 @@ export async function sendRequest<TResult>(
)
}, timeoutMs)
const finish = (
result: { ok: true; response: RuntimeRpcResponse<TResult> } | { ok: false; error: Error }
): void => {
if (settled) {
return
}
settled = true
clearTimeout(timeout)
socket.end()
if (result.ok) {
resolve(result.response)
} else {
reject(result.error)
}
}
socket.setEncoding('utf8')
socket.once('error', () => {
clearTimeout(timeout)
reject(
new RuntimeClientError(
finish({
ok: false,
error: new RuntimeClientError(
'runtime_unavailable',
'Could not connect to the running Orca app. Restart Orca and try again.'
)
)
})
})
socket.on('data', (chunk) => {
buffer += chunk
const newlineIndex = buffer.indexOf('\n')
if (newlineIndex === -1) {
return
}
const message = buffer.slice(0, newlineIndex)
socket.end()
clearTimeout(timeout)
let response: RuntimeRpcResponse<TResult>
try {
const raw: unknown = JSON.parse(message)
// Why: the server may interleave `{"_keepalive":true}\n` frames with the
// final success/failure frame to keep both idle timers alive during a
// long-poll (see design doc §3.1). Read frames in a loop until we see a
// terminal frame. Each keepalive refreshes the client-side timer so a
// 10 min wait doesn't trip the 60 s default ceiling.
let newlineIndex = buffer.indexOf('\n')
while (newlineIndex !== -1 && !settled) {
const line = buffer.slice(0, newlineIndex)
buffer = buffer.slice(newlineIndex + 1)
if (line.trim().length === 0) {
newlineIndex = buffer.indexOf('\n')
continue
}
let raw: unknown
try {
raw = JSON.parse(line)
} catch {
finish({
ok: false,
error: new RuntimeClientError(
'invalid_runtime_response',
'The Orca runtime returned an invalid response frame.'
)
})
return
}
// Fast-path: ignore keepalives without running the full schema.
// setTimeout().refresh() is stable since Node 10 (Orca ships on
// Node 20+ via Electron and the standalone CLI targets the same
// major). See §7 risk #9.
if (isKeepaliveFrame(raw)) {
timeout.refresh()
newlineIndex = buffer.indexOf('\n')
continue
}
// Why: validate the envelope shape (id, ok, result/error, _meta) at
// the decode boundary so version skew between the CLI and the Orca
// main runtime surfaces as a single invalid_runtime_response instead
@@ -54,43 +103,49 @@ export async function sendRequest<TResult>(
// unknown — the TResult generic is the caller's responsibility.
const parsed = RuntimeRpcEnvelopeSchema.safeParse(raw)
if (!parsed.success) {
reject(
new RuntimeClientError(
finish({
ok: false,
error: new RuntimeClientError(
'invalid_runtime_response',
'The Orca runtime returned an invalid response frame.'
)
)
})
return
}
response = parsed.data as RuntimeRpcResponse<TResult>
} catch {
reject(
new RuntimeClientError(
'invalid_runtime_response',
'The Orca runtime returned an invalid response frame.'
)
)
// Narrow out keepalive (already filtered above) so TS can see a
// Success|Failure shape here.
const frame = parsed.data
if ('_keepalive' in frame) {
timeout.refresh()
newlineIndex = buffer.indexOf('\n')
continue
}
const response = frame as RuntimeRpcResponse<TResult>
if (response.id !== requestId) {
finish({
ok: false,
error: new RuntimeClientError(
'invalid_runtime_response',
'The Orca runtime returned a mismatched response id.'
)
})
return
}
if (response._meta?.runtimeId && response._meta.runtimeId !== metadata.runtimeId) {
finish({
ok: false,
error: new RuntimeClientError(
'runtime_unavailable',
'The Orca runtime changed while the request was in flight. Retry the command.'
)
})
return
}
finish({ ok: true, response })
return
}
if (response.id !== requestId) {
reject(
new RuntimeClientError(
'invalid_runtime_response',
'The Orca runtime returned a mismatched response id.'
)
)
return
}
if (response._meta?.runtimeId && response._meta.runtimeId !== metadata.runtimeId) {
reject(
new RuntimeClientError(
'runtime_unavailable',
'The Orca runtime changed while the request was in flight. Retry the command.'
)
)
return
}
resolve(response)
})
socket.on('connect', () => {
socket.write(
+34 -10
View File
@@ -23,8 +23,23 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [
path: ['orchestration', 'check'],
summary: 'Check messages for a terminal',
usage:
'orca orchestration check [--terminal <handle>] [--unread] [--types <type,...>] [--inject] [--wait] [--timeout-ms <n>] [--json]',
allowedFlags: [...GLOBAL_FLAGS, 'terminal', 'unread', 'types', 'inject', 'wait', 'timeout-ms']
'orca orchestration check [--terminal <handle>] [--unread | --all] [--types <type,...>] [--inject] [--wait] [--timeout-ms <n>] [--json]\n' +
' --unread (default): return only unread messages and mark them read.\n' +
' --all: return every message for the handle; does not mark read.\n' +
' --wait: block until a matching message arrives or --timeout-ms expires.\n' +
' Emits JSON heartbeat lines to stderr every 15s so the caller can\n' +
' tell the process is alive. Filter with `grep -v _heartbeat` or\n' +
' `jq "select(._heartbeat|not)"` when merging streams with 2>&1.',
allowedFlags: [
...GLOBAL_FLAGS,
'terminal',
'unread',
'all',
'types',
'inject',
'wait',
'timeout-ms'
]
},
{
path: ['orchestration', 'reply'],
@@ -34,9 +49,9 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [
},
{
path: ['orchestration', 'inbox'],
summary: 'Show all messages across recipients',
usage: 'orca orchestration inbox [--limit <n>] [--json]',
allowedFlags: [...GLOBAL_FLAGS, 'limit']
summary: 'Show messages across (or for) recipients',
usage: 'orca orchestration inbox [--limit <n>] [--terminal <handle>] [--full] [--json]',
allowedFlags: [...GLOBAL_FLAGS, 'limit', 'terminal', 'full']
},
{
path: ['orchestration', 'task-create'],
@@ -56,20 +71,29 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [
summary: 'Update a task status',
usage:
'orca orchestration task-update --id <task_id> --status <status> [--result <json>] [--json]',
allowedFlags: [...GLOBAL_FLAGS, 'id', 'status', 'result']
allowedFlags: [...GLOBAL_FLAGS, 'id', 'status', 'result'],
notes: ['Valid --status values: pending, ready, dispatched, completed, failed, blocked.']
},
{
path: ['orchestration', 'dispatch'],
summary: 'Dispatch a task to a terminal',
usage:
'orca orchestration dispatch --task <task_id> --to <handle> [--from <handle>] [--inject] [--json]',
allowedFlags: [...GLOBAL_FLAGS, 'task', 'to', 'from', 'inject']
'orca orchestration dispatch --task <task_id> --to <handle> [--from <handle>] [--inject] [--dry-run] [--return-preamble] [--json]',
allowedFlags: [...GLOBAL_FLAGS, 'task', 'to', 'from', 'inject', 'dry-run', 'return-preamble']
},
{
path: ['orchestration', 'dispatch-show'],
summary: 'Show dispatch context for a task',
usage: 'orca orchestration dispatch-show --task <task_id> [--json]',
allowedFlags: [...GLOBAL_FLAGS, 'task']
usage:
'orca orchestration dispatch-show --task <task_id> [--preamble] [--from <handle>] [--json]',
allowedFlags: [...GLOBAL_FLAGS, 'task', 'preamble', 'from']
},
{
path: ['orchestration', 'ask'],
summary: 'Ask the coordinator a question and block until answered',
usage:
'orca orchestration ask --to <handle> --question <text> [--options <csv>] [--timeout-ms <n>] [--from <handle>] [--json]',
allowedFlags: [...GLOBAL_FLAGS, 'to', 'question', 'options', 'timeout-ms', 'from']
},
{
path: ['orchestration', 'run'],