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:
@@ -7,7 +7,7 @@ import {
|
||||
isShellProcess
|
||||
} from '../../shared/agent-detection'
|
||||
import type { AgentStatus } from '../../shared/agent-detection'
|
||||
import { gitExecFileAsync, gitExecFileSync } from '../git/runner'
|
||||
import { gitExecFileAsync } from '../git/runner'
|
||||
import { isWslPath, parseWslPath, getWslHome } from '../wsl'
|
||||
import { randomUUID } from 'crypto'
|
||||
import { join } from 'path'
|
||||
@@ -84,7 +84,9 @@ import {
|
||||
getBranchConflictKind,
|
||||
isGitRepo,
|
||||
getRepoName,
|
||||
searchBaseRefs
|
||||
searchBaseRefs,
|
||||
getRemoteDrift,
|
||||
getRecentDriftSubjects
|
||||
} from '../git/repo'
|
||||
import { listWorktrees, addWorktree, removeWorktree } from '../git/worktree'
|
||||
import { createSetupRunnerScript, getEffectiveHooks, runHook } from '../hooks'
|
||||
@@ -242,6 +244,23 @@ export class OrcaRuntimeService {
|
||||
private agentDetector: AgentDetector | null = null
|
||||
private _orchestrationDb: OrchestrationDb | null = null
|
||||
private messageWaitersByHandle = new Map<string, Set<MessageWaiter>>()
|
||||
// Why (§3.3 + §7.1): the renderer-create path and coordinator
|
||||
// `probeWorktreeDrift` share this cache so a create that already fetched
|
||||
// `origin` within the last 30s does not re-fetch during dispatch, and
|
||||
// vice-versa. Keyed by `<repoPath>::<remote>` so multi-remote repos (even
|
||||
// though v1 only uses `origin`) don't cross-contaminate. The in-flight Map
|
||||
// also provides serialization — two concurrent callers share a single
|
||||
// underlying `git fetch`. Lifecycle rules are enforced in
|
||||
// `fetchRemoteWithCache` and MUST NOT be duplicated elsewhere:
|
||||
// - entry inserted BEFORE await,
|
||||
// - `.finally()` removes the entry on BOTH success and rejection,
|
||||
// - timestamp written ONLY on success (rejection must not make the
|
||||
// 30s freshness cache lie).
|
||||
// A literal "insert before await / read-back after await" without these
|
||||
// three rules wedges all future creates on the same repo after a single
|
||||
// DNS hiccup until process restart (see §3.3 Lifecycle).
|
||||
private fetchInflight = new Map<string, Promise<void>>()
|
||||
private fetchLastCompletedAt = new Map<string, number>()
|
||||
private readonly getLocalProviderFn: (() => IPtyProvider) | null
|
||||
|
||||
constructor(
|
||||
@@ -1022,10 +1041,18 @@ export class OrcaRuntimeService {
|
||||
}
|
||||
|
||||
const remote = baseBranch.includes('/') ? baseBranch.split('/')[0] : 'origin'
|
||||
// Why (§3.3 Lifecycle): route through the shared fetch cache so back-to-back
|
||||
// CLI creates on the same repo don't each pay the round-trip, and so a
|
||||
// subsequent dispatch probe within the 30s window reuses this result. The
|
||||
// helper swallows rejection (log-and-proceed) so a DNS hiccup never wedges
|
||||
// future creates and CLI creation stays usable offline — same intent as
|
||||
// the previous try/catch around gitExecFileSync.
|
||||
try {
|
||||
gitExecFileSync(['fetch', remote], { cwd: repo.path })
|
||||
await this.fetchRemoteWithCache(repo.path, remote)
|
||||
} catch {
|
||||
// Why: matching the editor behavior keeps CLI creation usable offline.
|
||||
// Why: belt-and-suspenders. fetchRemoteWithCache already logs and does
|
||||
// not throw; the outer try/catch guarantees create-path tolerance even
|
||||
// if future refactors change that contract.
|
||||
}
|
||||
|
||||
await addWorktree(
|
||||
@@ -1105,6 +1132,96 @@ export class OrcaRuntimeService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch `remote` in `repoPath`, sharing the 30s freshness window + in-flight
|
||||
* serialization with all other callers (renderer-create path, CLI create,
|
||||
* dispatch drift probe). Never rejects — callers log-and-proceed on offline
|
||||
* failures (§3.3 Lifecycle).
|
||||
*
|
||||
* Why a shared cache on the runtime instead of module-scoped: §7.1 relies on
|
||||
* one cache for BOTH the renderer create path and `probeWorktreeDrift`. A
|
||||
* dispatch tick that reuses a just-completed create-path fetch is the
|
||||
* primary telemetry target; splitting the cache by call-site would double
|
||||
* the fetch load on warm repos.
|
||||
*/
|
||||
async fetchRemoteWithCache(repoPath: string, remote: string): Promise<void> {
|
||||
const key = `${repoPath}::${remote}`
|
||||
const lastAt = this.fetchLastCompletedAt.get(key)
|
||||
if (lastAt !== undefined && Date.now() - lastAt < FETCH_FRESHNESS_MS) {
|
||||
// Why: freshness window hit — skip the fetch entirely. Do NOT reuse any
|
||||
// in-flight promise here; the timestamp is only written on success, so
|
||||
// hitting this branch means a previous fetch did succeed recently.
|
||||
return
|
||||
}
|
||||
|
||||
const existing = this.fetchInflight.get(key)
|
||||
if (existing) {
|
||||
// Why: genuine serialization (not check-then-set). Two callers racing
|
||||
// on the same repo+remote share the single underlying `git fetch`.
|
||||
return existing
|
||||
}
|
||||
|
||||
const promise = gitExecFileAsync(['fetch', remote], { cwd: repoPath })
|
||||
.then(() => {
|
||||
// Why (§3.3 Lifecycle): timestamp on success ONLY. Writing on rejection
|
||||
// would make the freshness cache lie about the last known remote state.
|
||||
this.fetchLastCompletedAt.set(key, Date.now())
|
||||
})
|
||||
.catch((err) => {
|
||||
// Why: swallow here so awaiters don't throw at the await site. Outer
|
||||
// create/dispatch paths are already tolerant of offline fetch failure;
|
||||
// this is the behavioral contract of this helper.
|
||||
console.warn(`[fetchRemoteWithCache] ${remote} fetch failed for ${repoPath}:`, err)
|
||||
})
|
||||
.finally(() => {
|
||||
// Why (§3.3 Lifecycle): evict on BOTH success and rejection. A
|
||||
// rejected entry that survived in the Map would wedge every future
|
||||
// create on this repo until Orca restarted (the F2 bug §3.3 pins).
|
||||
this.fetchInflight.delete(key)
|
||||
})
|
||||
|
||||
this.fetchInflight.set(key, promise)
|
||||
return promise
|
||||
}
|
||||
|
||||
/**
|
||||
* Probe how far the worktree's HEAD is behind its tracking remote. Returns
|
||||
* null when the probe cannot establish a signal (no default base ref, or
|
||||
* git failure). Dispatch treats null as "unknown — proceed" (§3.1); only
|
||||
* knowing-and-stale refuses.
|
||||
*/
|
||||
async probeWorktreeDrift(worktreeSelector: string): Promise<{
|
||||
base: string
|
||||
behind: number
|
||||
recentSubjects: string[]
|
||||
} | null> {
|
||||
const wt = await this.resolveWorktreeSelector(worktreeSelector)
|
||||
if (!this.store) {
|
||||
return null
|
||||
}
|
||||
const repo = this.store.getRepos().find((r) => r.id === wt.repoId)
|
||||
if (!repo) {
|
||||
return null
|
||||
}
|
||||
const base = getDefaultBaseRef(repo.path)
|
||||
if (!base) {
|
||||
// Why: brand-new repo with no remote primary — nothing to compare
|
||||
// against, so there's no meaningful drift to report. Dispatch should
|
||||
// not block on a probe that cannot form an opinion.
|
||||
return null
|
||||
}
|
||||
const remote = base.includes('/') ? base.split('/')[0] : 'origin'
|
||||
// Why: fetch failures are non-fatal; we proceed with whatever the
|
||||
// last-known remote ref points at. `fetchRemoteWithCache` never throws.
|
||||
await this.fetchRemoteWithCache(wt.path, remote)
|
||||
const drift = getRemoteDrift(wt.path, 'HEAD', base)
|
||||
if (!drift) {
|
||||
return null
|
||||
}
|
||||
const recentSubjects = getRecentDriftSubjects(wt.path, 'HEAD', base, DRIFT_PROBE_SUBJECT_LIMIT)
|
||||
return { base, behind: drift.behind, recentSubjects }
|
||||
}
|
||||
|
||||
async updateManagedWorktreeMeta(
|
||||
worktreeSelector: string,
|
||||
updates: {
|
||||
@@ -1733,7 +1850,7 @@ export class OrcaRuntimeService {
|
||||
|
||||
waitForMessage(
|
||||
handle: string,
|
||||
options?: { typeFilter?: string[]; timeoutMs?: number }
|
||||
options?: { typeFilter?: string[]; timeoutMs?: number; signal?: AbortSignal }
|
||||
): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
const timeoutMs = options?.timeoutMs ?? MESSAGE_WAIT_DEFAULT_TIMEOUT_MS
|
||||
@@ -1745,7 +1862,27 @@ export class OrcaRuntimeService {
|
||||
timeout: null
|
||||
}
|
||||
|
||||
// Why: if the caller aborts (socket closed on the RPC side — see design
|
||||
// doc §3.1 counter-lifecycle), resolve immediately so the long-poll slot
|
||||
// is released instead of counting down the full timeoutMs with a dead
|
||||
// client on the other end.
|
||||
const signal = options?.signal
|
||||
const onAbort = (): void => {
|
||||
this.removeMessageWaiter(waiter)
|
||||
resolve()
|
||||
}
|
||||
if (signal) {
|
||||
if (signal.aborted) {
|
||||
resolve()
|
||||
return
|
||||
}
|
||||
signal.addEventListener('abort', onAbort, { once: true })
|
||||
}
|
||||
|
||||
waiter.timeout = setTimeout(() => {
|
||||
if (signal) {
|
||||
signal.removeEventListener('abort', onAbort)
|
||||
}
|
||||
this.removeMessageWaiter(waiter)
|
||||
resolve()
|
||||
}, timeoutMs)
|
||||
@@ -2002,8 +2139,15 @@ export class OrcaRuntimeService {
|
||||
|
||||
// Why: Claude Code treats large single PTY writes as paste events and
|
||||
// swallows a \r included in the same write. Send Enter separately after
|
||||
// a delay so the agent processes the pasted message first. Mark messages
|
||||
// as read only after \r is confirmed, so failed deliveries stay queued.
|
||||
// a delay so the agent processes the pasted message first. Stamp
|
||||
// `delivered_at` only after \r is confirmed, so failed deliveries stay
|
||||
// queued.
|
||||
//
|
||||
// Important (design doc §3.2, feedback #2): we stamp `delivered_at` here
|
||||
// instead of flipping `read`. `read` is reserved for "a check-caller
|
||||
// consumed this message." Flipping `read` on push-on-idle would hide the
|
||||
// message from the coordinator's next `check --unread`, which is the
|
||||
// exact bug feedback #2 reported. The two bits must stay independent.
|
||||
const ptyId = leaf.ptyId
|
||||
setTimeout(() => {
|
||||
try {
|
||||
@@ -2012,11 +2156,12 @@ export class OrcaRuntimeService {
|
||||
}
|
||||
const submitted = this.ptyController?.write(ptyId, '\r') ?? false
|
||||
if (submitted) {
|
||||
this._orchestrationDb?.markAsRead(unread.map((m) => m.id))
|
||||
this._orchestrationDb?.markAsDelivered(unread.map((m) => m.id))
|
||||
}
|
||||
} catch {
|
||||
// Terminal may have closed during the delay — messages stay unread
|
||||
// and will be re-delivered on the next idle transition.
|
||||
// Terminal may have closed during the delay — messages stay queued
|
||||
// (delivered_at still NULL) and will be re-delivered on the next
|
||||
// idle transition.
|
||||
}
|
||||
}, 500)
|
||||
}
|
||||
@@ -3133,6 +3278,13 @@ const DEFAULT_TERMINAL_LIST_LIMIT = 200
|
||||
const DEFAULT_WORKTREE_LIST_LIMIT = 200
|
||||
const DEFAULT_WORKTREE_PS_LIMIT = 200
|
||||
const RESOLVED_WORKTREE_CACHE_TTL_MS = 1000
|
||||
// Why (§3.3): 30s freshness window. A second worktree-create or dispatch-probe
|
||||
// against the same repo+remote within this window reuses the previous successful
|
||||
// fetch instead of repeating the round-trip. Chosen so rapid "new worktree"
|
||||
// clicks and successive coordinator dispatches feel snappy, while still being
|
||||
// short enough that a genuinely-changed remote is observed on the next action.
|
||||
const FETCH_FRESHNESS_MS = 30_000
|
||||
const DRIFT_PROBE_SUBJECT_LIMIT = 5
|
||||
function buildPreview(lines: string[], partialLine: string): string {
|
||||
const previewLines = buildTailLines(lines, partialLine)
|
||||
.map((line) => line.trim())
|
||||
|
||||
Reference in New Issue
Block a user