---
name: sdk-test-decompiled-patterns
type: analysis
title: "Decompiled Code Patterns — 10 Architectural Patterns from 3305 Functions"
description: "Architectural patterns extracted from Ghidra decompilation of the agy Go binary: Cascade Architecture, Trajectory Persistence, Battle Mode, Subagent Architecture, MCP Integration, Browser Automation, Knowledge Management, CEL Enforcement, Feature Flags, and Hardcoded Permissions"
tags: [reverse-engineering, ghidra, golang, architecture, patterns, jetsky, decompilation]
timestamp: 2026-07-22
---

# Decompiled Code Patterns — 10 Architectural Patterns from 3305 Functions

## Overview

Systematic analysis of 3,305 decompiled functions from the `agy` Go binary (`language_server_hub`) reveals 10 distinct architectural patterns. These patterns define the internal structure of the JETSKY platform and reveal how Google's agent runtime is engineered at scale.

The binary's internal package root is `github.com/anthropics/jetsky/internal/...`. All function names, package paths, and structural relationships were extracted via Ghidra MCP decompilation.

```mermaid
mindmap
  root((JETSKY Binary<br/>3305 Functions))
    Cascade Architecture
      CascadeManager
      Trajectory orchestration
      Battle Mode
    Trajectory Persistence
      Serialization to disk
      Resume from saved state
      ProtoStore
    Battle Mode
      Multi-model A/B
      Winner selection
      Step replacement
    Subagent Architecture
      InvokeSubagentHandler
      Task mode
      Inbox management
    MCP Integration
      Stdio + HTTP transports
      System MCP
      Tool routing
    Browser Automation
      CDP client
      Screenshot capture
      JS execution
    Knowledge Management
      Knowledge Items
      Document manager
      Web scraping
    CEL Enforcement
      Expression evaluation
      Request authorization
      Sandbox proxy
    Feature Flags
      UnleashWrapper
      Experiment configs
      Gradual rollout
    Hardcoded Permissions
      getHardcodedGrants
      Access control
      Permission system
```

## Pattern 1: Cascade Architecture

### What Is a Cascade?

The "cascade" is the core agent execution loop. It is the fundamental unit of agent computation in JETSKY. A cascade manages a trajectory (conversation session), handles model calls, tool execution, and state transitions.

### Key Functions

| Function | Package | Size | Purpose |
|----------|---------|------|---------|
| `CascadeManager.New` | `cortex` | ~8KB | Creates the cascade manager |
| `CascadeManager.EndBattleMode` | `cortex` | — | Ends battle mode for a cascade |
| `CascadeManager.applyBattleModeWinner` | `cortex` | — | Applies winning model from A/B test |
| `CascadeManager.ensureTrajectoryLoaded` | `cortex` | — | Loads trajectory from disk if needed |
| `CascadeManager.getBaseTrajectory` | `cortex` | — | Gets the root trajectory |
| `CascadeManager.getTrajectoryMetadata` | `cortex` | — | Gets trajectory metadata |
| `CascadeManager.normalizeWorkspaceURI` | `cortex` | — | Normalizes workspace paths |
| `Server.StartCascade` | `language_server` | — | Starts a new cascade on the server |

### Architecture

```mermaid
graph TB
    subgraph "CascadeManager"
        CM["CascadeManager<br/>Orchestrates all cascades"]
        CM -->|"manages"| C1["Cascade 1<br/>trajectory: main"]
        CM -->|"manages"| C2["Cascade 2<br/>trajectory: subagent-1"]
        CM -->|"manages"| C3["Cascade 3<br/>trajectory: subagent-2"]
    end

    subgraph "Per-Cascade"
        direction TB
        Traj["Trajectory<br/>(conversation state)"]
        Exec["CascadeExecutor<br/>(execution engine)"]
        Gen["Generator<br/>(model API calls)"]
        Tools["Tool Manager<br/>(tool execution)"]
        
        Traj --> Exec
        Exec --> Gen
        Exec --> Tools
    end

    C1 --> Traj
    C2 --> Traj
    C3 --> Traj

    style CM fill:#2a4a6b
```

### Relationship to SDK

The SDK's `LocalConnection` maps to a single cascade. The `cascade_id` in `HarnessConfig` identifies which cascade the SDK is connected to. Subagents create additional cascades tracked by the `CascadeManager`.

## Pattern 2: Trajectory Persistence

### What Is a Trajectory?

A trajectory is the serialized state of a conversation -- including all steps, tool calls, model responses, and metadata. It can be saved to disk and resumed later.

### Key Functions

| Function | Package | Purpose |
|----------|---------|---------|
| `protoTrajectory` | `trajectory` | Converts internal trajectory to protobuf |
| `StepHeaderMetadata` | `trajectory` | Metadata header for each step |
| `StepHeaderTaskDetails` | `trajectory` | Task-specific step details |
| `ChatModelHeader` | `trajectory` | Model information header |
| `GeneratorMetadataHeader` | `trajectory` | Generator metadata |
| `PlannerResponseStepView` | `trajectory` | Planner response visualization |
| `processPendingUpdates` | `traj` | Processes queued trajectory updates |
| `startCommitWorker` | `traj` | Background trajectory persistence worker |
| `Manager` | `trajectorystore` | Trajectory store manager |
| `ProtoStore` | `trajectorystore` | Protobuf-based storage backend |

### Persistence Flow

```mermaid
sequenceDiagram
    participant Agent as Agent Loop
    participant Store as TrajectoryStore
    participant Worker as Commit Worker
    participant Disk as Filesystem

    Agent->>Store: Add step to trajectory
    Store->>Store: Queue pending update
    
    Worker->>Store: Poll for pending updates
    Store-->>Worker: Batch of updates
    Worker->>Worker: Serialize to protobuf
    Worker->>Disk: Write trajectory file
    
    Note over Disk: Path: ~/.gemini/antigravity/<session-id>/trajectory.pb
    
    Agent->>Store: Session resume requested
    Store->>Disk: Read trajectory file
    Disk-->>Store: Protobuf bytes
    Store->>Store: Deserialize trajectory
    Store-->>Agent: Restored trajectory state
```

### SDK Integration

The SDK can resume sessions via the `initial_trajectory` field in `HarnessConfig`:

```python
config = LocalAgentConfig(
    conversation_id="previous-session-id",
    save_dir="/path/to/saved/trajectory",
)
```

The harness reads the saved trajectory from `save_dir` and passes it as `initial_trajectory` bytes in the handshake.

## Pattern 3: Battle Mode

### What Is Battle Mode?

Battle Mode is an internal **A/B testing mechanism** that runs multiple models in parallel on the same input and compares their outputs. The winning model's output is used.

### Key Functions

| Function | Package | Purpose |
|----------|---------|---------|
| `CascadeManager.EndBattleMode` | `cortex` | Ends battle mode for a cascade |
| `CascadeManager.applyBattleModeWinner` | `cortex` | Applies the winning model's output |
| `trajectoryWithReplacer` | `battlemode` | Step replacement logic |
| `trajectoryWithReplacer.clone` | `battlemode` | Clones trajectory for parallel execution |
| Step status indexing | `battlemode` | Tracks step completion across models |

### Architecture

```mermaid
graph TB
    Input["User Input"] --> BM["Battle Mode Manager"]
    
    BM -->|"Clone trajectory"| M1["Model A<br/>(e.g., gemini-2.5-pro)"]
    BM -->|"Clone trajectory"| M2["Model B<br/>(e.g., gemini-3.5-flash)"]
    BM -->|"Clone trajectory"| M3["Model C<br/>(e.g., deepseek-v4)"]
    
    M1 -->|"Response A"| Judge["Winner Selection<br/>(quality metric)"]
    M2 -->|"Response B"| Judge
    M3 -->|"Response C"| Judge
    
    Judge -->|"Winner"| Apply["applyBattleModeWinner()<br/>Replace trajectory steps"]
    Apply --> Output["Final Response"]
    
    style BM fill:#6b2a4a
    style Judge fill:#4a6b2a
```

### How It Works

1. **Clone**: The current trajectory is cloned for each competing model
2. **Execute**: All models process the same input in parallel
3. **Compare**: A quality metric (human feedback, automated scoring, or heuristic) evaluates outputs
4. **Select**: The winning model's trajectory replaces the original
5. **Discard**: Losing trajectories are discarded

This is likely used for internal quality benchmarking and model selection optimization.

## Pattern 4: Subagent Architecture

### Key Functions

| Function | Package | Purpose |
|----------|---------|---------|
| `InvokeSubagentHandler.Handle` | `handlers` | Main subagent invocation |
| `InvokeSubagentHandler.handleTaskMode` | `handlers` | Task-mode subagent |
| `DefineSubagentSubHandler.Handle` | `handlers` | Subagent definition |
| `ManageInboxSubHandler.handleList` | `handlers` | Inbox management |
| `ConversationSubagentManager` | `subagent` | Subagent lifecycle manager |
| `SubagentUpdateForwarder` | `agent_state_component` | Forwards updates from subagent to parent |
| `mergeParallelArrays` | `agent_state_component` | Merges parallel subagent results |
| `mergeTrajectoryUpdates` | `agent_state_component` | Combines trajectory state from subagents |

### Subagent Invocation Flow

```mermaid
sequenceDiagram
    participant Parent as Parent Agent
    participant Handler as InvokeSubagentHandler
    participant CM as CascadeManager
    participant Sub as Subagent Cascade

    Parent->>Handler: Tool call: start_subagent(task="...")
    Handler->>Handler: handleTaskMode(task)
    Handler->>CM: Create new cascade
    CM->>Sub: Initialize subagent trajectory
    
    loop Subagent execution
        Sub->>Sub: Process task
        Sub->>Handler: SubagentUpdateForwarder
        Handler->>Parent: Forward updates to parent trajectory
    end

    Sub->>Handler: Task complete
    Handler->>Parent: Return subagent result
    CM->>CM: Clean up subagent cascade
```

### Parent-Child Relationship

- Parent trajectories track subagent IDs in `_active_subagent_ids`
- Subagent trajectories have unique `trajectory_id` values
- The connection only goes idle when ALL trajectories (parent + subagents) complete
- `mergeParallelArrays` combines results when multiple subagents run in parallel

## Pattern 5: MCP Integration

### Key Functions

| Function | Package | Purpose |
|----------|---------|---------|
| `setUpMcpManager` | `language_server` | Initialize MCP manager |
| `setUpSystemMcpManager` | `language_server` | Initialize system-level MCP |
| `McpServersSection.Content` | `mixins` | System prompt section for MCP |
| MCP server management | `mcp` / `mcpcore` | MCP protocol implementation |

### Transport Support

```mermaid
graph LR
    subgraph "MCP Manager"
        MM["McpManager"]
    end

    subgraph "Stdio Transport"
        ST["Subprocess<br/>stdin/stdout<br/>JSON-RPC 2.0"]
    end

    subgraph "HTTP Transport"
        HT["HTTP Client<br/>Streamable HTTP<br/>SSE support"]
    end

    subgraph "System MCP"
        SM["Built-in MCP servers<br/>managed by harness"]
    end

    MM --> ST
    MM --> HT
    MM --> SM
    ST -->|"tool call"| Ext1["External MCP Server 1"]
    HT -->|"tool call"| Ext2["External MCP Server 2"]
    SM -->|"tool call"| Built["Built-in Tools"]
```

### System Prompt Injection

MCP servers are injected into the system prompt via `McpServersSection`:

```
## Available MCP Servers

### server-name
Tools:
- tool1: Description of tool1
- tool2: Description of tool2
```

This is generated by the `mixins.McpServersSection.Content` function and appended to the system instructions.

## Pattern 6: Browser Automation

### Key Functions

| Function | Package | Purpose |
|----------|---------|---------|
| `CommonBrowserHandler.handleInternal` | `browser` | Main browser operation handler |
| `BrowserSubagentHandler.internalHandle` | `browser` | Browser subagent handler |
| `BrowserSubagentHandler.handleStopRecording` | `browser` | Stop recording |
| `Operator.CaptureScreenshot` | `browser` | Screenshot capture |
| `BrowserPage.evaluateCDP` | `browserabstractions` | CDP command execution |
| `captureContextsMetadata` | `browserabstractions` | Capture page context |
| `NewCaptureBrowserScreenshotHandler` | `browser` | Screenshot handler factory |
| `NewCaptureBrowserConsoleLogsHandler` | `browser` | Console log handler |
| `NewListBrowserPagesHandler` | `browser` | Page enumeration |
| `NewReadBrowserPageHandler` | `browser` | Page content reader |
| `NewBrowserScrollHandler` | `browser` | Scroll control |
| `executeJavaScriptAction` | `browser` | JS execution |
| `mouseWheelAction` / `pressKeyAction` | `browser` | Input simulation |

### CDP Integration

```mermaid
graph TB
    subgraph "Browser Subsystem"
        BH["Browser Handler"]
        BP["Browser Page"]
        CDP["CDP Client"]
    end

    subgraph "Chrome DevTools Protocol"
        Screenshot["Page.captureScreenshot"]
        DOM["DOM.getDocument"]
        JS["Runtime.evaluate"]
        Input["Input.dispatchMouseEvent<br/>Input.dispatchKeyEvent"]
    end

    subgraph "Output"
        PNG["Screenshot PNG"]
        Content["Page Content"]
        Console["Console Logs"]
    end

    BH --> BP
    BP --> CDP
    CDP --> Screenshot
    CDP --> DOM
    CDP --> JS
    CDP --> Input
    Screenshot --> PNG
    DOM --> Content
    JS --> Content
```

### Browser Capabilities

| Capability | Function | CDP Method |
|-----------|----------|------------|
| Screenshot | `CaptureScreenshot` | `Page.captureScreenshot` |
| DOM Reading | `ReadBrowserPage` | `DOM.getDocument` |
| JS Execution | `executeJavaScriptAction` | `Runtime.evaluate` |
| Mouse Events | `mouseWheelAction` | `Input.dispatchMouseEvent` |
| Keyboard Events | `pressKeyAction` | `Input.dispatchKeyEvent` |
| Console Logs | `CaptureBrowserConsoleLogs` | `Runtime.consoleAPICalled` |
| Page Navigation | `ListBrowserPages` | `Target.getTargets` |

### Media Output

Screenshots are converted to protobuf format:
- `imageToPNGImageProto` -- converts raw screenshot to PNG protobuf
- `makeClickFeedbackPNG` -- generates visual feedback for clicks
- `makeDragFeedbackPNGs` -- generates visual feedback for drag operations

## Pattern 7: Knowledge Management

### Key Functions

| Function | Package | Purpose |
|----------|---------|---------|
| `localManager.scanKILocked` | `knowledge` | Scan Knowledge Items |
| Document management | `document` / `documentmanager` | Document lifecycle |
| Document parsing | `doc` | Document content extraction |
| Notebook support | `notebook` | Jupyter/notebook integration |
| Web scraping | `web_scraping` | Web content extraction |

### Knowledge Item System

```mermaid
graph TB
    subgraph "Knowledge Sources"
        Files["Local Files"]
        Web["Web Pages"]
        Docs["Documents"]
        NB["Notebooks"]
    end

    subgraph "Knowledge Manager"
        KM["localManager"]
        KI["Knowledge Items<br/>(structured memory)"]
        Index["Index<br/>(searchable)"]
    end

    subgraph "Agent Access"
        Agent["Agent Loop"]
        Context["Context Injection"]
    end

    Files --> KM
    Web --> KM
    Docs --> KM
    NB --> KM
    
    KM --> KI
    KI --> Index
    Index --> Agent
    Agent --> Context
```

The Knowledge system provides structured memory for agents. Knowledge Items are scanned, indexed, and injected into the agent's context when relevant.

## Pattern 8: CEL Enforcement

### Key Functions

| Function | Package | Purpose |
|----------|---------|---------|
| `celEnforcer.IsRequestAllowed` | `sandboxproxy` | CEL-based request authorization |

### What Is CEL?

CEL (Common Expression Language) is Google's expression language for policy evaluation. It is used in JETSKY for fine-grained request authorization.

```mermaid
flowchart TD
    Req["Incoming Request"] --> CEL["CEL Enforcer"]
    CEL --> Eval{"Evaluate CEL<br/>Expressions"}
    Eval -->|"Allow"| Process["Process Request"]
    Eval -->|"Deny"| Reject["Reject with Error"]
    Eval -->|"Condition"| Check["Check Additional<br/>Conditions"]
    Check -->|"Pass"| Process
    Check -->|"Fail"| Reject
```

### Use Cases

- Per-user rate limiting: `request.user.rate_limit < 100`
- Feature gating: `request.feature in user.enabled_features`
- Geographic restrictions: `request.geo in allowed_regions`
- Resource quotas: `request.tokens + user.used_tokens < user.quota`

### Integration with Sandbox Proxy

The CEL enforcer sits in the `sandboxproxy` layer, intercepting all requests before they reach the backend:

```mermaid
sequenceDiagram
    participant Client as Client Request
    participant Proxy as Sandbox Proxy
    participant CEL as CEL Enforcer
    participant Backend as Backend Service

    Client->>Proxy: gRPC Request
    Proxy->>CEL: IsRequestAllowed(request)
    
    alt Allowed
        CEL-->>Proxy: true
        Proxy->>Backend: Forward request
        Backend-->>Proxy: Response
        Proxy-->>Client: Response
    else Denied
        CEL-->>Proxy: false
        Proxy-->>Client: PERMISSION_DENIED
    end
```

## Pattern 9: Feature Flags (Unleash)

### Key Functions

| Function | Package | Purpose |
|----------|---------|---------|
| `UnleashWrapper` | `unleash` | Feature flag wrapper |
| `UnleashWrapperFactory` | `unleash` | Factory for creating wrappers |
| `contextFieldState` | `unleash` | Context field management |
| `InitializeFactory` | `unleash` | Factory initialization |
| `mergeExperimentConfigs` | `unleash` | Merge experiment configurations |
| `setUpUnleash` | `language_server` | Initialize feature flags at startup |

### Architecture

```mermaid
graph TB
    subgraph "Unleash System"
        UW["UnleashWrapper"]
        Factory["UnleashWrapperFactory"]
        Context["contextFieldState"]
        Config["ExperimentConfigs"]
    end

    subgraph "Feature Checks"
        F1["Feature A: enabled"]
        F2["Feature B: disabled"]
        F3["Feature C: gradual rollout 10%"]
    end

    subgraph "Components"
        Server["Language Server"]
        MCP["MCP Manager"]
        Browser["Browser System"]
        Agent["Agent Loop"]
    end

    Factory --> UW
    UW --> Context
    UW --> Config
    Config --> F1
    Config --> F2
    Config --> F3

    Server -->|"check feature"| UW
    MCP -->|"check feature"| UW
    Browser -->|"check feature"| UW
    Agent -->|"check feature"| UW
```

### Feature Flag Flow

1. At startup, `setUpUnleash` initializes the Unleash client
2. Feature configurations are fetched from the `GetUnleashContextFields` API
3. `mergeExperimentConfigs` combines local and remote configurations
4. Components check features via `UnleashWrapper.isEnabled(feature_name)`
5. Gradual rollouts use the installation ID for consistent hashing

## Pattern 10: Hardcoded Permissions

### Key Functions

| Function | Package | Purpose |
|----------|---------|---------|
| `getHardcodedGrants` | `permissions` | Returns hardcoded permission grants |
| Permission management | `permissions` | Permission system infrastructure |

### What Are Hardcoded Grants?

The binary contains a set of **baked-in permission grants** that cannot be overridden by configuration. These define the minimum set of capabilities available to all users.

```mermaid
graph TB
    subgraph "Permission System"
        HG["getHardcodedGrants()<br/>Always active"]
        CP["Config Permissions<br/>User/team configurable"]
        DP["Dynamic Permissions<br/>Runtime evaluation"]
    end

    subgraph "Effective Permissions"
        EP["Effective Permission Set<br/>HG ∪ CP ∪ DP"]
    end

    HG --> EP
    CP --> EP
    DP --> EP
    
    EP -->|"Check"| Tools["Tool Access"]
    EP -->|"Check"| Features["Feature Access"]
    EP -->|"Check"| Resources["Resource Access"]
```

### Implications

The presence of `getHardcodedGrants` means:
1. Some permissions are non-negotiable -- they cannot be denied
2. The permission system has a baseline that all configurations build upon
3. These grants likely include basic read operations and system-level access

## Subsystem Function Map

### Core Server (`language_server.*`)

| Function | Size | Purpose |
|----------|------|---------|
| `CreateLanguageServerAndServe` | ~15KB | Main entry point -- massive initialization |
| `setUpLogging` | — | Logging configuration |
| `setUpFS` | — | Filesystem setup |
| `setUpFSInjection` | — | Filesystem injection (virtual FS) |
| `setUpTracing` | — | Distributed tracing |
| `setUpInstallationID` | — | Installation ID generation |
| `setUpMetadataProvider` | — | Metadata provider setup |
| `setUpServerPortListeners` | — | Port binding |
| `setUpUnleash` | — | Feature flag initialization |
| `setUpExtensionServerClient` | — | Extension server connection |
| `setUpClients` | — | Client initialization |
| `setUpWorkspaceManager` | — | Workspace management |
| `setUpConversationAnnotationsManager` | — | Conversation annotations |
| `setUpMcpManager` | — | MCP manager initialization |
| `setUpSystemMcpManager` | — | System MCP initialization |
| `setUpCustomizationOptions` | — | Customization setup |
| `setUpTrajectorySaver` | — | Trajectory persistence setup |
| `setUpGoMaxProcs` | — | Go runtime configuration |

### Agent State (`agent_state.*`)

| Function | Purpose |
|----------|---------|
| `component.mergeParallelArrays` | Merges parallel subagent results |
| `component.mergeTrajectoryUpdates` | Combines trajectory state |
| `component.buildFullStateUpdateLocked` | Builds complete state snapshot |
| `SubagentUpdateForwarder` | Forwards subagent updates to parent |

### Handlers (`handlers.*`)

| Function | Purpose |
|----------|---------|
| `InvokeSubagentHandler.Handle` | Main subagent invocation |
| `InvokeSubagentHandler.handleTaskMode` | Task-mode subagent |
| `DefineSubagentSubHandler.Handle` | Subagent definition |
| `ManageInboxSubHandler.handleList` | Inbox management |
| `CodeActionHandler.ApplyCodeEdit` | Code action application |

### Serialization (`serializers.*`)

| Function | Purpose |
|----------|---------|
| `stepToMessage` | Converts internal steps to wire format |
| `checkpointSummaryOutput` | Generates checkpoint summaries |

### Git/VCS (`git.*`, `vcs.*`)

| Function | Purpose |
|----------|---------|
| `CreateOrUpdatePullRequest` | PR management |
| `GitStatusShell` | Git status |
| `GetDiffsFromUncommittedChangesConfig` | Diff computation |
| `VcsCache.FindCodeiumYamlForDir` | Config file discovery |
| `Repository.createPatchForOneUntrackedFile` | Patch generation |

### Utils (`utils.*`)

| Function | Purpose |
|----------|---------|
| `TrajectoryToCascadeSummary` | Summarize trajectory for display |
| `DOMTreeJSONToProto` | Convert DOM tree to protobuf |
| `StepToMarkdown` | Convert step to markdown |

## Cross-References

- [[sdk-test-localharness]] — How these patterns manifest in the SDK-harness communication
- [[sdk-test-protobuf]] — Protobuf messages used by these patterns
- [[sdk-test-hooks-deep]] — Hook points where these patterns are intercepted
- [[sdk-test-auth-chain]] — Auth subsystem functions
- [[sdk-test-grpc-protocol]] — gRPC services and descriptors
- [[sdk-test-reverse-engineering]] — Full RE analysis (3305 functions, subsystems)
- [[sdk-test-deepseek-heartbeat]] — DeepSeek integration and heartbeat protocol

---

*Source: Ghidra MCP decompilation of `agy` binary. 3,305 `.c` files in `reverse_engineering/language_server_hub/decompiled/`. Entry point: `language_server_CreateLanguageServerAndServe` (~15KB). Core agent loop: `cortex_ptrCascadeManager_New` (~8KB).*
