Skip to content

fix(orchestration): allow fresh agents to take over legacy runs - #12896

Merged
Jinwoo-H merged 3 commits into
stablyai:mainfrom
AvichalDwivedi2205:codex/fix-legacy-run-takeover-12804
Aug 8, 2026
Merged

Jinwoo-H merged 3 commits into
stablyai:mainfrom
AvichalDwivedi2205:codex/fix-legacy-run-takeover-12804

Conversation

@AvichalDwivedi2205

Copy link
Copy Markdown
Contributor

Summary

Fixes #12804.

Explicit orchestration run-use --takeover-legacy can now bind an adopted Run from a freshly launched current agent before that agent emits its first hook observation.

The recovery path accepts the runtime's existing current-launch authority only when the caller exactly matches the live PTY, process incarnation, terminal handle, stable pane, host scope, and launch-token hash. Restored callers and ordinary legacy compatibility mutations continue to require agent-hook attestation.

The root cause was that explicit takeover, a current-contract recovery action, reused the stricter legacy compatibility verifier. That made callerAuthority null until a matching hook observation existed, so the takeover guard always returned legacy_read_only even though the runtime already held exact current-launch proof.

An integrated dispatcher regression test reproduces the pre-fix failure without mocking the verifier, proves the fresh local-agent takeover, and covers forged token, forged pane, and caller-chosen SSH attachment rejection.

Screenshots

No visual change.

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test
  • pnpm build
  • Added or updated high-quality tests that would catch regressions, or explained why tests were not needed

Additional validation:

  • Focused takeover, authority, CLI, and SSH suites: 5 files / 39 tests passed.
  • Cross-version terminal wire suite against v1.4.175: 4 tests passed.
  • Full suite exercised 47,131 tests: 47,042 passed and 87 skipped. The GitHub project timeout passed on isolated rerun. The only remaining local failure is the unrelated Windows-signing 7za cold-cache test: its external toolset download reaches 100% and then exits on read ECONNRESET; a direct diagnostic reproduced the same network failure outside the suite.

AI Review Report

The AI review checked the authority boundary from CLI evidence through compatibility preflight, the takeover guard, and the Run binding transaction.

  • Cross-platform: The change is platform-neutral TypeScript with no new paths, shortcuts, labels, shell behavior, or Electron platform branches. Existing local, WSL, and SSH host-scope validation remains shared across macOS, Linux, and Windows.
  • SSH / remote / local: Local takeover is covered through the real verifier/dispatcher stack. SSH coverage proves that a runtime-issued live attachment is accepted and a caller-chosen attachment is rejected. Existing SSH compatibility tests remain green.
  • Agents and integrations: The behavior is provider-neutral and does not change hook ingestion, agent-specific lifecycle behavior, integrations, or git providers.
  • Performance: The option reuses the existing live-terminal lookup and launch-token hash already performed by the verifier. It adds no polling, I/O, dependencies, or background work.
  • UI quality: Not applicable; there is no renderer or interaction change.
  • Security: The review rejected a generic fallback. The bypass is opt-in only for explicit takeover and only for current_runtime launch provenance with an exact pane match. Default legacy verification remains unchanged.

No additional code changes were required after the final review.

Security Audit

This PR changes an authorization decision, so the review specifically checked spoofing and authority downgrade risks.

  • Caller-supplied IDs alone do not grant authority. The runtime must resolve a connected PTY with a live process incarnation and matching handle, pane, host scope, and launch-token hash.
  • SSH callers must also present a runtime-issued live attachment; a fabricated attachment remains rejected.
  • Restored terminals cannot use the current-launch path and still require their durable receipt plus hook attestation.
  • Ordinary legacy compatibility mutations still use the original strict verifier.
  • The raw launch token is neither logged nor stored by this change; returned authority contains only its SHA-256 hash.
  • No commands, paths, IPC schemas, dependencies, credentials, network listeners, or persistence formats were added.

No security follow-up is needed.

Notes

This PR addresses the primary stuck-takeover recovery bug. The issue's secondary request for a general Run deletion/archive surface is intentionally left out to keep this authorization fix focused.

X handle: @Avichal2205

@AvichalDwivedi2205
AvichalDwivedi2205 marked this pull request as ready for review August 6, 2026 09:35
@coderabbitai

coderabbitai Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PTY spawn path now validates launch-token authority and passes valid metadata to PTY registration. PTY registration stores the authority only when the PTY, pane, incarnation, token, and agent identity match. The compatibility verifier supports current runtime launch sufficiency and can return frozen caller authority for matching current panes. Legacy takeover uses this option. Tests cover valid and invalid launch proofs, SSH attachment validation, and current-runtime takeover.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes satisfy the primary objective in [#12804] by enabling authorized fresh-agent legacy takeover while preserving security checks.
Out of Scope Changes check ✅ Passed The code and tests remain focused on legacy takeover authorization, launch authority validation, and regression coverage.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title clearly summarizes the main change: enabling fresh agents to take over legacy runs.
Description check ✅ Passed The description covers the summary, testing, AI review, security audit, platform compatibility, screenshots, and scope notes.

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

🧹 Nitpick comments (1)
src/main/runtime/orca-runtime.ts (1)

12021-12033: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Bypass branch is correctly scoped, but consider documenting the invariant locally and removing duplication.

The new branch only returns frozen authority when terminalProvenance === 'current_runtime' (which requires the caller's launchToken to hash to the live PTY's actual launchToken) and claimedPaneKey === terminal.paneKey (the pane key resolved from the live PTY, not from caller input). Host-scope validation, including the SSH attachment/incarnation check, already runs unconditionally before this branch. This matches the PR's stated invariant that the recovery path requires an exact match on live PTY, pane, host scope, and launch-token hash, and it correctly excludes restored callers, since a restored terminal never reaches terminalProvenance === 'current_runtime'.

Two smaller points:

  • This function has no local comment explaining why skipping attestAgentHookCompatibilityAuthorityFn is safe here. The rationale currently lives only in the caller (orchestration-legacy-compatibility.ts). Since this is a security-sensitive authorization function, a short comment at the definition site would help future readers auditing it in isolation.
  • The returned object (hostScope, paneKey, terminalHandle, processIncarnation, launchTokenHash) duplicates the construction in the final Object.freeze(...) return a few lines below. Extracting a small helper would prevent the two authority-construction sites from silently diverging if a future security-relevant field is added to one but not the other.
♻️ Proposed refactor to share authority construction and document the invariant
+    // Why: a fresh, non-restored launch already proves its live PTY, host
+    // scope, and launch secret via the checks above, so it can skip hook
+    // attestation only when the caller's claimed pane also matches exactly.
     if (
       options?.currentRuntimeLaunchSufficient &&
       terminalProvenance === 'current_runtime' &&
       claimedPaneKey === terminal.paneKey
     ) {
-      return Object.freeze({
-        hostScope: Object.freeze({ ...terminal.hostScope }),
-        paneKey: claimedPaneKey,
-        terminalHandle,
-        processIncarnation: terminal.processIncarnation,
-        launchTokenHash
-      })
+      return this.freezeOrchestrationCompatibilityCallerAuthority(
+        terminal,
+        claimedPaneKey,
+        terminalHandle,
+        launchTokenHash
+      )
     }
     const attestation = this.attestAgentHookCompatibilityAuthorityFn?.({
       paneKey: claimedPaneKey,
       launchTokenHash,
       connectionId: terminal.hostScope.kind === 'ssh' ? terminal.hostScope.targetId : null,
       terminalProvenance
     })
     if (!attestation || attestation.paneKey !== terminal.paneKey) {
       return null
     }
-    return Object.freeze({
-      hostScope: Object.freeze({ ...terminal.hostScope }),
-      paneKey: attestation.paneKey,
-      terminalHandle,
-      processIncarnation: terminal.processIncarnation,
-      launchTokenHash
-    })
+    return this.freezeOrchestrationCompatibilityCallerAuthority(
+      terminal,
+      attestation.paneKey,
+      terminalHandle,
+      launchTokenHash
+    )
+  }
+
+  private freezeOrchestrationCompatibilityCallerAuthority(
+    terminal: OrchestrationCompatibilityTerminalAuthority,
+    paneKey: string,
+    terminalHandle: string,
+    launchTokenHash: string
+  ): OrchestrationCompatibilityCallerAuthority {
+    return Object.freeze({
+      hostScope: Object.freeze({ ...terminal.hostScope }),
+      paneKey,
+      terminalHandle,
+      processIncarnation: terminal.processIncarnation,
+      launchTokenHash
+    })
   }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 79f47813-5ef9-4842-aaf8-2ca60a03754f

📥 Commits

Reviewing files that changed from the base of the PR and between ac961d6 and 7674b4c.

📒 Files selected for processing (3)
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/orchestration-legacy-compatibility.ts
  • src/main/runtime/rpc/orchestration-legacy-takeover-current-authority.test.ts

@Jinwoo-H Jinwoo-H 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.

Thanks—verified the takeover authorization direction and reproduced the migration failure. During review I found the reported renderer-backed terminal create --command claude path still dropped fresh launch authority before main could verify it, so I added a bounded PTY-registration handoff and regression coverage.

  • Exact pre-hook legacy takeover now succeeds.
  • Forged token, pane, and SSH attachment evidence remain rejected.
  • New Runs and ordinary compatibility mutations remain hook-attested.
  • 505 focused tests and typecheck pass on the pushable head; latest-main validation also passed full lint, 506 focused tests, and Electron E2E.

@Jinwoo-H
Jinwoo-H merged commit 96a6c93 into stablyai:main Aug 8, 2026
43 checks passed

@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.

🧹 Nitpick comments (1)
src/main/ipc/pty.test.ts (1)

7997-8004: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add an at-limit launch-token boundary case.

AGENT_LAUNCH_TOKEN_MAX_LENGTH = 128 accepts tokens up to 128 characters and rejects 129, but this test only covers "matching proof" and "oversized proof". If the cap changes or drifts, the boundary can become untested. Add a 128-character expectedToken case to keep acceptance across the boundary pinned.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: cac44a9c-773a-43df-97e2-a47a663c8766

📥 Commits

Reviewing files that changed from the base of the PR and between bfcbb31 and 183f7b9.

📒 Files selected for processing (3)
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/main/runtime/orca-runtime.ts

enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…lyai#12896)

* fix(orchestration): allow fresh agents to take over legacy runs

* test(orchestration): cover forged takeover evidence

* fix(orchestration): retain renderer launch authority

---------

Co-authored-by: Jinwoo-H <[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.

orchestration run-use --takeover-legacy always fails with legacy_read_only, leaving legacy dispatches permanently stuck

4 participants