Skip to content

feat(ssh): update, roll back, recover and stop a managed orcad server (#16741 T6-5 follow-up) - #24463

Merged
OrcaWin merged 2 commits into
mainfrom
OrcaWin/node-rt-p3-t6-5b
Oct 1, 2026
Merged

OrcaWin merged 2 commits into
mainfrom
OrcaWin/node-rt-p3-t6-5b

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Oct 1, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​718 $\color{#cf222e}{\Huge{\mathbf{−}}}$​2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​716
Prod 24 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​989 $\color{#cf222e}{\Huge{\mathbf{−}}}$​43 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​946

ELI5

#24453 lets Orca create a managed orcad server on an empty SSH host. This PR adds the actions that come after creation:

  • update it to this app's build;
  • roll it back to the previous build;
  • recover an update or stop that was interrupted;
  • stop it and remove it from Orca;
  • cancel a stop that hasn't started yet.

Every action first asks the server how many terminals it is running. If any are running, or the server can't say, the action holds off rather than risk them.

Nothing in the UI calls this yet. The settings screens arrive in T6-6, so users see no change.

What Changed

Before: a managed server could be created and its status read, but nothing could update, roll back, recover or stop it.

After (main process only, through new IPC channels with no renderer caller yet):

  • Terminal census.
    • Over the wire: a new runtime RPC, orcad.terminalCensus, is advertised as the orcad.terminal-census.v1 capability and returns the daemon's live session count, how many started since activation, and the owning daemon protocol.
    • On the server: listLiveDaemonSessionsWithProtocol labels each session with its daemon generation's protocol. Sessions spread over several protocols leave the protocol unknown.
    • Client side (orcad-terminal-census-client.ts): the client calls it through the server's tunnel, with a status preflight, and only when the capability is advertised. All of these give an unverifiable census, never zero:
      • an older host;
      • method-not-found;
      • a malformed answer;
      • lost contact;
      • a tunnel that won't open.
  • Update (orcad-runtime-maintenance.ts):
    • It runs T6-2's deployOrcad with that census, so the existing update plan defers over live or uncounted terminals (D7).
    • A deferral is returned with its code and whether forcing is allowed, and is recorded per server for this session.
    • getOrcadStatus now reports deferredUpdate and the live terminals census.
    • A successful update re-probes readiness against the build hash this client holds.
  • Rollback.
    • It runs T6-2's rollbackOrcad against the previous slot's installed bytes, using that slot's build hash as read from the host.
    • It refuses unless the census shows zero terminals, because this client cannot read the older build's daemon protocol to show it would reach running terminals.
  • Recover. It runs T6-2/T6-4's recoverInterruptedOrcadActivation and re-opens the tunnel once a serving slot is restored.
  • Stop (orcad-runtime-decommission.ts):
    • It runs T6-4's decommissionRemoteOrcad with the census.
    • An interrupted stop is finished from its journal instead of starting a new one.
    • The Active Server is refused before the host is contacted.
    • It unlinks only on proven exited:
      1. remove the environment and its sidecar orcadDeployment record;
      2. run the same local cleanup as removing a server: capability evidence, manual-disconnect state, transport, browser partition storage;
      3. close the tunnel;
      4. release the SSH target claim and flush it.
    • On any live or unverifiable verdict, everything stays linked.
  • Cancel stop. Under the stale activation-recovery lock, it withdraws a dispatched stop through T6-4's cancelRemoteOrcadManagedStop and keeps the server on its recorded slot. If orcad already acted on the stop, or already exited, it says so and changes nothing.
  • Store (runtime-environment-managed-orcad-store.ts):
    • removeManagedOrcadEnvironment.
    • refreshManagedOrcadPairing, which rewrites only when the tunneled offer changed and keeps the deployment link bound to the new pairing revision.
  • IPC: updateOrcad, rollbackOrcad, recoverOrcad, stopOrcad, cancelOrcadStop.
    • The transport is invalidated after an update, a rollback, or a recovery that restores a serving slot.
    • The server-removal cleanup is extracted into runtime-environment-removal-cleanup.ts, so runtimeEnvironments:remove and stop share it.

Why

  • Built on main, not re-ported. feat(orcad): consolidate Bun runtime and SSH/Remote migration #16741's maintenance and decommission predate the T6-2 and T6-4 rewrites, so these call main's journaled deploy, rollback, recovery and decommission directly.
  • Census over RPC, capability-gated. Only the daemon can count its sessions. Desktop and orcad versions change independently, so the client asks only a server that advertises the method, and counts every other answer as unverifiable. An update therefore never restarts over terminals it couldn't count.
  • Unlink only on proven exit. Losing contact is not evidence that orcad has exited. Unlinking on anything less would hide a server that is still running.
  • Environment removed before the claim is released. A crash in between leaves a hidden target that can be resumed, never a linked server whose SSH target was already handed back.

Wire compatibility

There is one new RPC method, orcad.terminalCensus, behind the orcad.terminal-census.v1 capability.

  • A new client talking to an older server never calls it, and treats the census as unverifiable, so updates and stops defer or refuse.
  • An older client never asks for it.

rpc-params-catalog.generated.ts is regenerated, and --check passes.

Linked Issue

Part of #16741.

Visual Proof

N/A: no UI change. The new IPC channels have no renderer caller until T6-6.

Testing

  • New tests, 9 files and 84 tests:

    • the orcad census;
    • the census client (capability gate, method-not-found, malformed, lost contact, tunnel failure);
    • update (deferral reported in status, deferral cleared, pairing kept or re-bound);
    • rollback (refusals, success against the slot's hash);
    • recover;
    • stop (unlink only on exited; every refusal keeps the links; journal resume; another journal blocks; Active Server refused);
    • cancel stop (none, canceled, already dispatched, already stopped);
    • store removal and pairing refresh;
    • the maintenance IPC.
  • Broad run over all src/main/ipc/ssh*, src/main/ssh/*, runtime-environment, RPC, daemon and orcad tests: 847 files, 9066 passed, 74 skipped, 1 failed. The one failure was ssh-relay-incumbent-process.test.ts ("real generated incumbent probe"); it passes 9/9 on its own and this PR doesn't touch it.

  • A scoped tsc over the changed files and their main/shared importers (335 files) is clean.

  • oxlint, the changed-code quality gate, the max-lines ratchet and the runtime-electron ratchet are clean.

  • POSIX hosts only, as with the rest of the orcad deploy core.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • SSH: every remote verdict keeps live / unverifiable / exited, and only exited unlinks.
  • Secrets: pairing tokens are never logged. Results are redacted.
  • Folder workspaces: no change. Managed targets were already empty.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

…#16741 T6-5 follow-up)

Builds managed-server maintenance on T6-2's deploy, rollback and recovery and
T6-4's journaled decommission. Each step reads a terminal census through the
server's tunnel; orcad answers it through a new capability-gated
orcad.terminalCensus RPC, and an older host or lost answer is unverifiable.
Update defers over live or uncounted terminals and status reports the last
deferral. A stop unlinks the server (deployment record, tunnel, SSH claim)
only after a proven exit. Inert until the T6-6 settings UI.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@greptile-apps

greptile-apps Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 3/5

[High risk] Adds server lifecycle operations: update, rollback, recover, and stop.

The PR does not yet appear safe to merge because both previously reported managed-server lifecycle issues remain.

Findings

  1. P1 Pairing refresh can lose deployment link ▶
  2. P1 Recovered stop leaves server linked ▶

Summary

The PR adds managed orcad terminal census, update, rollback, recovery, stop, and cancel-stop operations through new main-process IPC channels. The change since the previous review makes the census module load lazily; no new actionable issue was established from that change.

Reviews (2) · Last reviewed commit: "fix(rpc): load the orcad terminal census..."

Comment on lines +146 to +150
writeRuntimeEnvironmentSidecarEntry(userDataPath, environments, next, {
...state,
orcadDeployment: deployment
})
writeEnvironmentStore(userDataPath, { version: 1, environments })

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Pairing refresh can lose deployment link

When an update or rollback changes the pairing offer, this writes the new sidecar entry before the environment store. If the process exits or the second write fails between those writes, the store keeps the old pairing revision and ignores the newly bound sidecar. The managed server then loses its deployment link, so maintenance actions can no longer resolve it.

Comment on lines +190 to +200
const updated = result.readiness
? refreshPairing(userDataPath, environment, result.readiness, deployment.localPort)
: environment
if (result.activeVersion) {
await ensureOrcadManagedTunnel(userDataPath, environment.id)
}
return {
outcome: 'recovered',
resolution: result.resolution,
activeVersion: result.activeVersion,
environment: redactRuntimeEnvironment(updated)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Recovered stop leaves server linked

When recovery confirms that an interrupted decommission has stopped the server, it returns activeVersion: null but does not remove the environment or release its tunnel and SSH target claim. Unlike the stop path, this leaves a server that is no longer serving registered as managed, with its target still claimed until someone explicitly stops it again.

@coderabbitai

coderabbitai Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

🧰 Additional context used
📚 Code guidelines (1)
AGENTS.md — auto-discovered
📝 Walkthrough

Walkthrough

The changes add protocol-aware terminal census collection and expose it through RPC and managed runtime status. They add managed Orcad update, rollback, recovery, stop, and stop-cancellation operations. The changes also add pairing refresh and environment removal behavior, update IPC registration and cleanup, and define shared result and status types.

Priority: ➖ Normal

Merge Risk: 🟡 Moderate · up to 475ef

A terminal opened during an update or rollback can be interrupted or orphaned, and an update can miss a terminal opened during artifact preparation. Close these census and admission windows before merging.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 475ef

Authentication and conservative handling of unavailable session counts limit exposure. However, session counts can become stale before an update or rollback commits, potentially interrupting running terminals or separating them from their saved state. These maintenance actions are not yet exposed through the renderer bridge, which limits immediate exposure but does not resolve the transition risk.

Retained concerns

  • Medium · reliability · inferred: The new managed rollback path accepts a zero-session census, then performs additional remote work before stopping the incumbent and restoring its pre-activation snapshot. The locked rollback uses that original census without an inspected terminal-admission fence. A terminal admitted during this window can remain daemon-owned while disappearing from the restored state, undermining rollback's terminal-ownership and reattachment guarantees. The lifecycle queue and activation-record identity check protect competing maintenance operations, not terminal creation.
  • Medium · reliability · inferred: The new managed update path samples terminal inventory before artifact materialization and activation. A later daemon-replacement preflight does recheck sessions, but an exact-zero result permits subsequent cleanup without an admission fence in the inspected preflight. A terminal created between that check and replacement can therefore be exposed to cleanup that kills child PTYs. The replacement mechanism is preexisting; the design concern is its use by the new managed-server update flow. Final cleanup enforcement remains a coverage limitation, so the outcome is inferred rather than verified.
Security review details

Security Blast Radius

  • inferred — The identified transition risks affect terminal continuity and persisted runtime state on the selected managed SSH host. They require a maintenance operation overlapping terminal admission; the inspected evidence does not establish unauthenticated maintenance access, cross-tenant authority, or broader infrastructure privilege changes.

Security Findings and Attack Paths

  • inferred — A participant already able to create terminals could overlap terminal creation with an operator's maintenance operation and invalidate an earlier zero-session decision. The supported concern is loss of continuity or rollback ownership, not a demonstrated authentication bypass or privilege escalation.

Trust Boundaries and Controls

  • observed — Network RPC ingress validates a device token, rejects mismatches with the channel-bound identity, and applies the mobile method allowlist before dispatch. The dispatcher validates the declared parameter schema. The census endpoint itself only reads daemon inventory and returns aggregate information.
  • observed — Capability advertisement is a client-side compatibility gate, not method-specific server authorization. The new mutating IPC handlers ignore their event argument, but the inspected renderer bridge does not expose those channels; this does not establish an unauthorized renderer attack path.

Resilience and Maintainability Implications

  • observed — Managed stop has stronger daemon-retirement admission handling than the inspected update and rollback paths: it requests idle retirement, and a busy or unverifiable daemon is left running. Retirement is best effort and does not veto Orcad's own stop, so process-exit proof and terminal-daemon retirement are distinct guarantees.

Hardening Proposals

  • proposed — Bind destructive update and rollback admission to a daemon-side fence or lease held through replacement or snapshot restoration. Define release and recovery behavior for refusal, interruption, and failed activation; a fresh count alone still leaves a check-to-use window.
  • proposed — Before exposing maintenance channels to renderer callers, explicitly enforce the intended sender and current-frame authority in the main process rather than relying on the absence of a renderer bridge.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 35.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 40 functions across 32 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the primary changes: updating, rolling back, recovering, and stopping a managed Orcad server.
Description check ✅ Passed The description includes the required sections and provides clear user impact, implementation details, rationale, issue reference, visual-proof status, testing results, compatibility notes, and checkl…
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 01be5702-8fc1-4ded-a03c-06a1692706af

📥 Commits

Reviewing files that changed from the base of the PR and between 8b76683 and afab3c9.

⛔ Files ignored due to path filters (1)
  • src/shared/rpc-contract/rpc-params-catalog.generated.ts is excluded by !**/*.generated.*
📒 Files selected for processing (32)
  • src/main/daemon/daemon-provider-census.test.ts
  • src/main/daemon/daemon-provider-state.ts
  • src/main/ipc/orcad-runtime-lifecycle-handlers.ts
  • src/main/ipc/orcad-runtime-maintenance-handlers.test.ts
  • src/main/ipc/orcad-runtime-maintenance-handlers.ts
  • src/main/ipc/runtime-environment-connectivity-handlers.ts
  • src/main/ipc/runtime-environment-handler-channels.ts
  • src/main/ipc/runtime-environment-removal-cleanup.ts
  • src/main/ipc/runtime-environments-pairing.test.ts
  • src/main/ipc/runtime-environments.ts
  • src/main/orcad/orcad-terminal-census.test.ts
  • src/main/orcad/orcad-terminal-census.ts
  • src/main/runtime/rpc/methods/index.ts
  • src/main/runtime/rpc/methods/orcad-terminal-census.ts
  • src/main/ssh/orcad-managed-lifecycle-test-fixture.ts
  • src/main/ssh/orcad-managed-runtime-context.ts
  • src/main/ssh/orcad-managed-update-deferrals.ts
  • src/main/ssh/orcad-runtime-decommission.test.ts
  • src/main/ssh/orcad-runtime-decommission.ts
  • src/main/ssh/orcad-runtime-deployment.test.ts
  • src/main/ssh/orcad-runtime-deployment.ts
  • src/main/ssh/orcad-runtime-lifecycle.ts
  • src/main/ssh/orcad-runtime-maintenance.test.ts
  • src/main/ssh/orcad-runtime-maintenance.ts
  • src/main/ssh/orcad-runtime-status.ts
  • src/main/ssh/orcad-terminal-census-client.test.ts
  • src/main/ssh/orcad-terminal-census-client.ts
  • src/shared/orcad-managed-runtime.ts
  • src/shared/orcad-terminal-census.ts
  • src/shared/protocol-version.ts
  • src/shared/runtime-environment-managed-orcad-store.test.ts
  • src/shared/runtime-environment-managed-orcad-store.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Comment on lines +71 to +117
export function updateManagedOrcadEnvironment(
userDataPath: string,
args: LifecycleArgs & { force?: boolean }
): Promise<OrcadManagedDeployResult> {
return withManagedOrcadLifecycle(userDataPath, args.selector, async ({ environment, deployment }) => {
const context = await resolveLinkedOrcadContext(environment, deployment, args.signal)
const census = await collectManagedTerminalCensus(
userDataPath,
environment,
context.activationRecord
)
const localOrcadDir = await materializeOrcadArtifact(context.serverTarget, {
signal: args.signal
})
const result = await deployOrcad({
...managedOrcadSlot(context, deployment.remotePort, args.signal),
localOrcadDir,
target: context.serverTarget,
census,
force: args.force
})
if (result.outcome === 'installed-not-activated') {
const deferral = {
outcome: 'deferred' as const,
candidateVersion: result.fullVersion,
code: result.code,
reason: result.reason,
forceable: isForceableOrcadDeferral(result.code)
}
recordManagedOrcadUpdateDeferral(environment.id, deferral)
return deferral
}
clearManagedOrcadUpdateDeferral(environment.id)
const readiness = await probeManagedOrcadReadiness(
context,
localOrcadDir,
result.fullVersion,
args.signal
)
const updated = refreshPairing(userDataPath, environment, readiness, deployment.localPort)
return {
outcome: result.outcome === 'already-active' ? 'already-current' : 'updated',
environment: redactRuntimeEnvironment(updated),
activeVersion: result.fullVersion
}
})
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '71,117p' src/main/ssh/orcad-runtime-maintenance.ts
rg -n 'liveSessions|sessionsStartedSinceActivation|terminalCensus|force' src/main/orcad

Repository: stablyai/orca

Length of output: 7777


🏁 Script executed:

set -eu
printf '%s\n' '--- revisions ---'
for rev in 8b76683b400911b6348623d60e29f8ff5e21cbe7 afab3c90dfb88368dc5d2b41c6a083af1583929f; do
  if git cat-file -e "$rev^{commit}" 2>/dev/null; then
    git rev-parse "$rev^{commit}"
  else
    printf 'UNAVAILABLE %s\n' "$rev"
  fi
done
printf '%s\n' '--- diff stat ---'
git diff --stat 8b76683b400911b6348623d60e29f8ff5e21cbe7 afab3c90dfb88368dc5d2b41c6a083af1583929f
printf '%s\n' '--- changed paths ---'
git diff --name-only 8b76683b400911b6348623d60e29f8ff5e21cbe7 afab3c90dfb88368dc5d2b41c6a083af1583929f | sed -n '1,120p'
printf '%s\n' '--- deployment symbols ---'
rg -n --glob '*.{ts,tsx}' 'deployOrcad|materializeOrcadArtifact|collectManagedTerminalCensus|withManagedOrcadLifecycle|updateManagedOrcadEnvironment' src
printf '%s\n' '--- candidate outlines ---'
ast-grep outline src/main/ssh/orcad-runtime-maintenance.ts
ast-grep outline src/main/orcad/orcad-terminal-census.ts
ast-grep outline src/main/orcad/orcad-managed-stop-decision.ts

Repository: stablyai/orca

Length of output: 14330


🏁 Script executed:

set -eu
printf '%s\n' '--- revisions ---'
for rev in 8b76683b400911b6348623d60e29f8ff5e21cbe7 afab3c90dfb88368dc5d2b41c6a083af1583929f; do
  if git cat-file -e "$rev^{commit}" 2>/dev/null; then git rev-parse "$rev^{commit}"; else printf 'UNAVAILABLE %s\n' "$rev"; fi
done
printf '%s\n' '--- diff stat ---'
git diff --stat 8b76683b400911b6348623d60e29f8ff5e21cbe7 afab3c90dfb88368dc5d2b41c6a083af1583929f
printf '%s\n' '--- changed paths ---'
git diff --name-only 8b76683b400911b6348623d60e29f8ff5e21cbe7 afab3c90dfb88368dc5d2b41c6a083af1583929f | sed -n '1,120p'
printf '%s\n' '--- deployment symbols ---'
rg -n --glob '*.{ts,tsx}' 'deployOrcad|materializeOrcadArtifact|collectManagedTerminalCensus|withManagedOrcadLifecycle|updateManagedOrcadEnvironment' src
printf '%s\n' '--- candidate outlines ---'
ast-grep outline src/main/ssh/orcad-runtime-maintenance.ts
ast-grep outline src/main/orcad/orcad-terminal-census.ts
ast-grep outline src/main/orcad/orcad-managed-stop-decision.ts

Repository: stablyai/orca

Length of output: 14330


🏁 Script executed:

set -eu
printf '%s\n' '--- remote deploy ---'
cat -n src/main/ssh/orcad-remote-deploy.ts | sed -n '1,230p'
printf '%s\n' '--- runtime deployment ---'
cat -n src/main/ssh/orcad-runtime-deployment.ts | sed -n '1,155p'
printf '%s\n' '--- census client ---'
cat -n src/main/ssh/orcad-terminal-census-client.ts | sed -n '1,150p'
printf '%s\n' '--- lifecycle and maintenance entrypoints ---'
cat -n src/main/ssh/orcad-runtime-lifecycle.ts
cat -n src/main/ipc/orcad-runtime-maintenance-handlers.ts | sed -n '1,100p'
printf '%s\n' '--- focused base-to-head diff ---'
git diff --unified=35 8b76683b400911b6348623d60e29f8ff5e21cbe7 afab3c90dfb88368dc5d2b41c6a083af1583929f -- \
  src/main/ssh/orcad-runtime-maintenance.ts \
  src/main/ssh/orcad-remote-deploy.ts \
  src/main/ssh/orcad-runtime-deployment.ts \
  src/main/ssh/orcad-terminal-census-client.ts \
  src/main/ipc/orcad-runtime-maintenance-handlers.ts
printf '%s\n' '--- deployment tests around safety cases ---'
cat -n src/main/ssh/orcad-remote-deploy.test.ts | sed -n '270,350p;420,535p;570,655p'
printf '%s\n' '--- maintenance tests ---'
cat -n src/main/ssh/orcad-runtime-maintenance.test.ts | sed -n '1,155p'

Repository: stablyai/orca

Length of output: 42548


🏁 Script executed:

set -eu
printf '%s\n' '--- activation symbols ---'
rg -n --glob '*.ts' 'activateInstalledOrcad|OrcadTerminalCensus|startedSinceActivation|orcad_update_terminals_running|terminal.*census|force' src/main/ssh src/main/orcad src/shared
printf '%s\n' '--- activation implementation ---'
cat -n src/main/ssh/orcad-installed-activation.ts | sed -n '1,280p'
printf '%s\n' '--- update plan and gate candidates ---'
fd -i -t f 'orcad-update-plan|orcad-activation-gate|activation-gate|installed-activation' src/main/ssh
for f in $(fd -i -t f 'orcad-update-plan|orcad-activation-gate|activation-gate' src/main/ssh); do
  printf '%s\n' "--- $f ---"
  cat -n "$f" | sed -n '1,240p'
done
printf '%s\n' '--- exact maintenance diff ---'
git diff --unified=12 8b76683b400911b6348623d60e29f8ff5e21cbe7 afab3c90dfb88368dc5d2b41c6a083af1583929f -- src/main/ssh/orcad-runtime-maintenance.ts
printf '%s\n' '--- activation-related tests ---'
rg -n -C 8 'startedSinceActivation|orcad_update_terminals_running|force|census' src/main/ssh/*activation*.test.ts src/main/ssh/orcad-remote-deploy.test.ts src/main/ssh/orcad-runtime-maintenance.test.ts

Repository: stablyai/orca

Length of output: 42548


🏁 Script executed:

set -eu
printf '%s\n' '--- exact activation binding ---'
rg -n --glob '*.ts' 'function activateInstalledOrcad|const activateInstalledOrcad|export .*activateInstalledOrcad|from .*/orcad-installed-activation' src
printf '%s\n' '--- installed activation outline ---'
ast-grep outline src/main/ssh/orcad-installed-activation.ts
printf '%s\n' '--- installed activation focused reads ---'
rg -n -C 12 'planOrcadUpdate|census|liveSessions|startedSinceActivation|force|stop|snapshot|activate' src/main/ssh/orcad-installed-activation.ts
printf '%s\n' '--- update plan ---'
cat -n src/main/ssh/orcad-update-plan.ts | sed -n '1,155p'
printf '%s\n' '--- daemon census ---'
cat -n src/main/orcad/orcad-terminal-census.ts | sed -n '1,100p'
printf '%s\n' '--- maintenance header and update ---'
cat -n src/main/ssh/orcad-runtime-maintenance.ts | sed -n '1,118p'

Repository: stablyai/orca

Length of output: 26917


🏁 Script executed:

set -eu
printf '%s\n' '--- daemon preservation symbols ---'
rg -n -C 12 'shouldPreserveDaemonWithLiveSessions|live sessions|liveSessions|disconnectDaemon|shutdownDaemon|daemon-init|entry-path|version mismatch|preserve' src/main
printf '%s\n' '--- daemon supervision and init candidates ---'
fd -i -t f 'daemon-supervision|daemon-init|daemon-provider|orcad.*daemon' src/main
for f in $(fd -i -t f 'daemon-supervision|daemon-init|daemon-provider|orcad.*daemon' src/main); do
  printf '%s\n' "--- $f ---"
  rg -n -C 8 'shouldPreserveDaemonWithLiveSessions|disconnectDaemon|shutdownDaemon|live|version|entry' "$f"
done
printf '%s\n' '--- related tests ---'
rg -n -C 12 'preserv|mixed pair|entry.path|live session|daemon.*version|disconnectDaemon|shutdownDaemon' src/main/daemon src/main/ssh src/main/orcad

Repository: stablyai/orca

Length of output: 45626


🏁 Script executed:

set -eu
printf '%s\n' '--- protocol crossing ---'
cat -n src/main/ssh/orcad-daemon-protocol-crossing.ts | sed -n '1,180p'
printf '%s\n' '--- bounded exact searches ---'
rg -n 'shouldPreserveDaemonWithLiveSessions|preserveDaemonWithLiveSessions|daemon-init|entry-path|mixed pair|live terminal|live sessions' src/main/ssh src/main/orcad src/main/daemon -g '*.ts' | sed -n '1,240p'
printf '%s\n' '--- daemon launch/adoption calls from Orcad path ---'
rg -n -C 5 'launchOrcad|launchOrcadSlot|disconnectDaemon|shutdownDaemon|daemon.*preserv|preserv.*daemon|listLiveDaemon' src/main/ssh/orcad-*.ts src/main/ssh/*daemon*.ts | sed -n '1,260p'

Repository: stablyai/orca

Length of output: 40384


🏁 Script executed:

set -eu
cat -n src/main/daemon/daemon-replacement-preflight.ts | sed -n '88,145p;245,285p'

Repository: stablyai/orca

Length of output: 4411


Collect the census after artifact materialization.

A non-forced update can collect zero sessions, then a terminal can start while materializeOrcadArtifact runs. activateInstalledOrcad uses that stale zero without another census and proceeds with the restart. The later daemon gate preserves the old daemon, but the candidate Orcad then runs against it until the terminal exits instead of deferring as required.

Suggested fix
- * Every step reads the terminal census through the server's tunnel first; an unanswered census
+ * Every update reads the terminal census through the server's tunnel immediately before deployment; an unanswered census
  * is unverifiable, never zero, so an update over live or uncounted terminals defers (D7).
...
-    const census = await collectManagedTerminalCensus(
-      userDataPath,
-      environment,
-      context.activationRecord
-    )
     const localOrcadDir = await materializeOrcadArtifact(context.serverTarget, {
       signal: args.signal
     })
+    const census = await collectManagedTerminalCensus(
+      userDataPath,
+      environment,
+      context.activationRecord
+    )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export function updateManagedOrcadEnvironment(
userDataPath: string,
args: LifecycleArgs & { force?: boolean }
): Promise<OrcadManagedDeployResult> {
return withManagedOrcadLifecycle(userDataPath, args.selector, async ({ environment, deployment }) => {
const context = await resolveLinkedOrcadContext(environment, deployment, args.signal)
const census = await collectManagedTerminalCensus(
userDataPath,
environment,
context.activationRecord
)
const localOrcadDir = await materializeOrcadArtifact(context.serverTarget, {
signal: args.signal
})
const result = await deployOrcad({
...managedOrcadSlot(context, deployment.remotePort, args.signal),
localOrcadDir,
target: context.serverTarget,
census,
force: args.force
})
if (result.outcome === 'installed-not-activated') {
const deferral = {
outcome: 'deferred' as const,
candidateVersion: result.fullVersion,
code: result.code,
reason: result.reason,
forceable: isForceableOrcadDeferral(result.code)
}
recordManagedOrcadUpdateDeferral(environment.id, deferral)
return deferral
}
clearManagedOrcadUpdateDeferral(environment.id)
const readiness = await probeManagedOrcadReadiness(
context,
localOrcadDir,
result.fullVersion,
args.signal
)
const updated = refreshPairing(userDataPath, environment, readiness, deployment.localPort)
return {
outcome: result.outcome === 'already-active' ? 'already-current' : 'updated',
environment: redactRuntimeEnvironment(updated),
activeVersion: result.fullVersion
}
})
}
export function updateManagedOrcadEnvironment(
userDataPath: string,
args: LifecycleArgs & { force?: boolean }
): Promise<OrcadManagedDeployResult> {
return withManagedOrcadLifecycle(userDataPath, args.selector, async ({ environment, deployment }) => {
const context = await resolveLinkedOrcadContext(environment, deployment, args.signal)
const localOrcadDir = await materializeOrcadArtifact(context.serverTarget, {
signal: args.signal
})
const census = await collectManagedTerminalCensus(
userDataPath,
environment,
context.activationRecord
)
const result = await deployOrcad({
...managedOrcadSlot(context, deployment.remotePort, args.signal),
localOrcadDir,
target: context.serverTarget,
census,
force: args.force
})
if (result.outcome === 'installed-not-activated') {
const deferral = {
outcome: 'deferred' as const,
candidateVersion: result.fullVersion,
code: result.code,
reason: result.reason,
forceable: isForceableOrcadDeferral(result.code)
}
recordManagedOrcadUpdateDeferral(environment.id, deferral)
return deferral
}
clearManagedOrcadUpdateDeferral(environment.id)
const readiness = await probeManagedOrcadReadiness(
context,
localOrcadDir,
result.fullVersion,
args.signal
)
const updated = refreshPairing(userDataPath, environment, readiness, deployment.localPort)
return {
outcome: result.outcome === 'already-active' ? 'already-current' : 'updated',
environment: redactRuntimeEnvironment(updated),
activeVersion: result.fullVersion
}
})
}

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No critical issues — one wire field that cannot currently carry a value, plus one design point worth confirming.

Reviewed changes

Initial review of all 33 files: the managed-orcad maintenance lifecycle (update, rollback, recover, stop, cancel-stop) built on T6-2/T6-4. Main process only; the new IPC channels have no renderer caller until T6-6.

  • Terminal census. New orcad.terminalCensus RPC behind orcad.terminal-census.v1; listLiveDaemonSessionsWithProtocol labels each live session with its daemon generation's protocol; the client reads every failure (older host, method-not-found, malformed, lost contact, tunnel failure) as an all-null unverifiable census, never zero.
  • Update / rollback / recover (orcad-runtime-maintenance.ts) run main's journaled deployOrcad / rollbackOrcad / recoverInterruptedOrcadActivation, deferring an update over live or uncounted terminals, refusing rollback unless the census is zero, and re-pairing through the same tunnel after a successful change.
  • Stop / cancel-stop (orcad-runtime-decommission.ts) run T6-4's decommission, finish an interrupted stop from its journal, refuse the Active Server before contacting the host, and unlink only on proven orcad exit; cancel withdraws a not-yet-dispatched stop under the stale-recovery lock.
  • Store & IPC: removeManagedOrcadEnvironment and refreshManagedOrcadPairing; new updateOrcad / rollbackOrcad / recoverOrcad / stopOrcad / cancelOrcadStop channels; shared runtime-environment-removal-cleanup.ts extracted so server removal and stop share the client-side cleanup.

ℹ️ Stop unlinks on orcad exit, not daemon idleness

stopManagedOrcadEnvironment proves orcad exited before unlinking; it does not require the host's terminal daemon to be idle. decommissionRemoteOrcad already refuses a non-zero census at dispatch, but the settle can still come back retirement: 'live' (a terminal started inside the window, or a daemon it could not settle), and stopRemote then returns a Stopped result that unlinks while reporting verdict: 'exited' with retirement: 'live'. Two branches also skip the census entirely: the !record.active shortcut (src/main/ssh/orcad-runtime-decommission.ts:107-110) and the interrupted-decommission recovery branch (:81-86). withDeactivatedVersion (src/main/ssh/orcad-activation-record.ts:157-168) documents that a null active version keeps previous precisely because "the slot whose daemon may still own terminals", and collectRemoteOrcadTerminalCensus reports zero for that record shape. Both branches read like they resume an already-authorized stop, so this may well be intended — it would just be worth stating that unlink is gated on orcad exit alone (not daemon idleness), and that terminals surviving the unlink in that window is accepted.

Technical details
# Unlink proof is orcad exit, not daemon idleness

## Affected sites
- `src/main/ssh/orcad-runtime-decommission.ts:106-110` — `!record.active` returns `{version: null, retirement: null}` with no census and no liveness probe; the caller unlinks.
- `src/main/ssh/orcad-runtime-decommission.ts:81-86` — interrupted decommission recovered to `activeVersion === null` (orcad slot proven `DEAD` only) unlinks without consulting `census.liveSessions`.
- `src/main/ssh/orcad-runtime-decommission.ts:111-116` — normal path passes the census, but `decommissionRemoteOrcad` can return `retirement: 'live'` and the stop still unlinks.
- `src/main/ssh/orcad-activation-record.ts:157-168` / `src/main/ssh/orcad-decommission-transaction.ts:52` — the deactivated record shape (`active: null`, `previous` pinned) that the shortcut treats as "nothing running".
- `src/main/ssh/orcad-terminal-census-client.ts:33-35,71-73` — census is hard-coded to `liveSessions: 0` whenever `!record.active`.

## Required outcome
- Confirm (in a comment or the PR body) whether unlinking on proven orcad exit alone — accepting that a live daemon may keep terminals the client can no longer reach — is the intended contract, since the result type already reports `retirement: 'live'`.
- If the `!record.active` / recovery-unlink paths are meant only to resume an already-authorized stop, say so; otherwise they need a daemon census before unlinking.

## Open questions for the human
- Is a deactivated-but-linked environment (crash between host commit and client unlink) the only way these two branches are reached in production?

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

Comment on lines +25 to +34
const timestampsKnown = sessions.every(
(session) => Number.isFinite(session.createdAt) && session.createdAt > 0
)
const protocols = new Set(sessions.map((session) => session.protocolVersion))
const [protocol] = protocols
return {
liveSessions: sessions.length,
startedSinceActivation: timestampsKnown
? sessions.filter((session) => session.createdAt >= activatedAt).length
: null,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

startedSinceActivation is unreachable as a real count: the daemon's only live-session listing hardcodes createdAt: 0 (src/main/daemon/terminal-host-session-listing.ts:27), so timestampsKnown is false for any non-empty daemon and this field is always null. The activatedAt param is therefore inert over the new wire.

Nothing misbehaves today — rollbackManagedOrcadEnvironment refuses on liveSessions !== 0 before the census reaches rollbackOrcad, so assessOrcadRollback's startedSinceActivation branches never run through the managed flow. But the PR's own test calls createdAt: 0 an edge case when it is every real session, and if the rollback gate is ever relaxed to the semantics assessOrcadRollback was written for (allow pre-activation sessions, refuse only post-activation ones), every non-empty daemon would read orcad_rollback_census_unavailable and the orphan-detection branch could never fire. Either populate createdAt from the live session, or drop the field and the param.

…s not pull in the xterm window polyfill

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found in this delta.

Reviewed changes

Incremental re-review of afab3c90df..475efa1c6b: one commit that fixes a module-load-order regression introduced by the initial commit.

  • Lazy census import. src/main/runtime/rpc/methods/orcad-terminal-census.ts now loads collectOrcadTerminalCensus via a dynamic await import(...) inside the handler instead of a static top-level import. The census module reaches the daemon modules, whose xterm-env-polyfill defines a global window (src/main/daemon/headless-emulator.ts:1), so the static import pulled that polyfill into every process that imports the RPC dispatcher. The chain was verified end to end, and the handler already returns a promise at that seam, so the change is behavior-neutral for callers.

The prior inline thread on startedSinceActivation (src/main/orcad/orcad-terminal-census.ts:25-34) is unaffected by this commit and remains open; it is informational and not re-raised here.

Pullfrog  | Fix it ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (2)

🟠 Major · Fence terminal admission before replacing the daemon. · orcad-runtime-maintenance.ts:77-91

src/main/ssh/orcad-runtime-maintenance.ts:77-91
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Fence terminal admission before replacing the daemon.

The update path can pass a zero census to deployOrcad. The later replacement preflight performs another point-in-time count, but it does not use requestIdleDaemonRetirement() to fence new terminals. A terminal can be admitted after that count returns zero and before cleanup replaces the daemon. Because daemon replacement kills its child PTYs, the newly admitted terminal can be interrupted and lost.

Route the zero-session replacement decision through the existing atomic idle-retirement mechanism, and hold its admission fence until replacement completes.

🟠 Major · Rollback can orphan a terminal admitted after the census. · orcad-runtime-maintenance.ts:134-159

src/main/ssh/orcad-runtime-maintenance.ts:134-159
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Rollback can orphan a terminal admitted after the census.

collectManagedTerminalCensus is a point-in-time check. After it returns zero, rollback does not fence daemon admission or collect another census before stopOrcadSlot and snapshot restoration. A terminal admitted in that interval can remain owned by the incumbent while rollback restores a snapshot that does not contain it.

Rollback must atomically prevent new terminal admission before the final idle check and keep that fence through incumbent shutdown and snapshot restoration.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: bb371e6c-7472-417e-a805-f49e6132fbeb

📥 Commits

Reviewing files that changed from the base of the PR and between afab3c9 and 475efa1.

📒 Files selected for processing (1)
  • src/main/runtime/rpc/methods/orcad-terminal-census.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.

@OrcaWin
OrcaWin merged commit 38c2d1d into main Oct 1, 2026
66 checks passed
OrcaWin added a commit that referenced this pull request Oct 2, 2026
* Revert "feat(orcad): source-side dormant export of a relay-hosted SSH target (#16741 T6-8) (#24519)"

This reverts commit 783101b.

* Revert "feat(ssh): update, roll back, recover and stop a managed orcad server (#16741 T6-5 follow-up) (#24463)"

This reverts commit 38c2d1d.

* Revert "feat(ssh): deploy and pair an empty managed orcad server over SSH (#16741 T6-5) (#24453)"

This reverts commit 8b76683.

* Revert "fix(ssh): orcad GC honors the activation journal; readiness requires proven daemon coverage (#16741 T6 follow-up) (#24451)"

This reverts commit d3f8c50.

* Revert "feat(ssh): remote orcad stop by request file and journaled decommission (#16741 T6-4) (#24449)"

This reverts commit 43d9b43.

* Revert "feat(orcad): supervisable server: stop requests, managed stop receipts and a lifetime that keeps its lock on failed teardown (#16741 T6-3) (#24433)"

This reverts commit b093d3a.

* Revert "feat(ssh): crash-safe orcad activation, rollback and recovery (#16741 T6-2) (#24423)"

This reverts commit 1a9ac0e.

* Revert "feat(runtime): SSH access links for paired servers in a downgrade-safe sidecar (#16741 T5-1+T5-2) (#24420)"

This reverts commit 99db2bf.

* Revert "feat(relay): capability-gated owner reset with a durable preparation journal (#16741 T3 R1) (#24418)"

This reverts commit 34a582b.

* Revert "feat(ssh): track connection-manager drains, test probes and provider continuations (#16741 T2 P3+P8a) (#24407)"

This reverts commit d53063d.

* Revert "feat(daemon): idle retirement, session census and recovery-only provider (#16741 T2 P4b) (#24409)"

This reverts commit ff212db.

* Revert "feat(ssh): add pty.resumeClient and split SSH PTY process listing (#16741 T2 P5+P6) (#24414)"

This reverts commit 92cb717.

* Revert "feat(relay): await owned watcher and agent children on shutdown (#16741 T2 P1) (#24400)"

This reverts commit 6b36e4f.

* Revert "feat(session): retry failed renderer session writes and verify local folder PTYs (#16741 T2 P9) (#24406)"

This reverts commit d23ecef.

* Revert "feat(ssh): remote orcad primitives on the pinned Node runtime (#16741 T6-1) (#24419)"

This reverts commit dd87ae5.

* Revert "fix(runtime): fence runtime-environment subscriptions and status probes by identity (#16741 T5-3) (#24421)"

This reverts commit ece9e4d.

* Revert "feat(orcad): migration manifest and dormant-state contracts (#16741 T6-7) (#24422)"

This reverts commit 3fbdaba.

* Revert "feat(ssh): wire SshConnection through the work and transport close ledgers (#16741 T2 P2) (#24401)"

This reverts commit 4e8edc8.

* Revert "feat(profiles): carry markdown frontmatter visibility in project transfers (#16741 T2 P7) (#24405)"

This reverts commit 60c9326.

* Revert "fix(runtime): project the PTY incarnation onto mobile session tabs (#24413)"

This reverts commit 99e0303.

* Revert "feat(daemon): tag daemon stream data with the PTY incarnation id (#16741 T2 P4a) (#24402)"

This reverts commit 817af76.

* Revert "feat(ssh): port the SSH connection work ledger and transport close ledger (#16741 T2) (#24210)"

This reverts commit c991893.

* Revert "feat(relay): fence and drain file and git response streams on shutdown (#24185)"

This reverts commit dc08ffe.

* Revert "refactor(runtime-rpc): extract the Node WebSocket lifecycle; opt-in pinned port (#24186)"

This reverts commit a789233.

* Revert "feat(relay): route relay handlers through work admission; producer publication drain (#24181)"

This reverts commit 0b812bd.

* Revert "feat(relay): land the #16741 T1 seam (work drain, publication drain, release gate) (#24156)"

This reverts commit 3aa2d3a.

---------

Co-authored-by: m4air <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant