# Paseo-native integration contract

AEH treats Paseo as the authority for agent runtime state and generic agent orchestration, while AEH remains the authority for engineering policy and deterministic acceptance.

## Authority split

| Concern | Authority | Preferred surface |
| --- | --- | --- |
| Agent creation/session lifecycle | Paseo | `@getpaseo/client` |
| Agent current state | Paseo | `agents.ref(id).refetch()` |
| Agent context-window usage | Paseo/provider | `AgentSnapshot.lastUsage` |
| Provider/model availability | Paseo | provider snapshot/listModels/diagnostic |
| OpenCode native execution identity | AEH topology + session-local OpenCode config | AEH runtime projection -> `OPENCODE_CONFIG_CONTENT` / `default_agent`; explicit external agents may use Paseo `modeId` |
| Generic create/send/status/activity tools | Paseo | injected native/MCP Paseo tools |
| AUDIT/CHANGE/RUN operation state | AEH | `aeh-control` / operation state |
| Detached operation completion wake-up | AEH + Paseo dispatch | durable completion target + follow-up to existing lead |
| Context thresholds and handoff policy | AEH | `aeh_context_status` / `context guard` |
| SDD, contracts, seals, validation | AEH | deterministic Harness core |
| Quality convergence/acceptance | AEH | deterministic Harness core |

Do not copy generic Paseo lifecycle tools into `aeh-control`. The AEH MCP exists only for AEH-specific controller and policy semantics.

## Context pressure

The active Paseo client exposes provider usage on the agent snapshot through
`lastUsage`; AEH reads the context-window values when they are present:

```text
contextWindowUsedTokens
contextWindowMaxTokens
```

AEH reads them from the full agent snapshot. It does **not** derive context pressure from `inputTokens`, `outputTokens`, `totalTokens`, log text or compact agent-list metadata.

States:

```text
NO_USAGE_YET
  snapshot exists but the provider has not emitted lastUsage yet

USAGE_UNAVAILABLE
  snapshot/usage exists but canonical context-window fields are unavailable

OK
  ratio < pressureThreshold (default 70%)

PRESSURE
  pressureThreshold <= ratio < handoffThreshold (default 70–80%)

HANDOFF_REQUIRED
  handoffThreshold <= ratio < hardHandoffThreshold (default 80–90%)

HARD_HANDOFF
  ratio >= hardHandoffThreshold (default 90%)
```

Managed leads receive the preapproved `aeh_context_status` tool. A normal managed lead calls it without an `agentId`. AEH resolves the context target in strict order: explicit diagnostic `agentId`, host-provided `PASEO_AGENT_ID`, then the compatible project-local `lead-session.json` written by `aeh start`. The durable fallback respects configured `orchestration.interactive.stateDir` and validates the lead-state schema version, current bootstrap/runtime version, project root, project name and agent id before use. It fails closed on stale or mismatched state and never guesses by listing agents. The selected identity source is traced as `harness.paseo.context.identity`.

`aeh context guard --agent ...` is the CLI surface for automation and owns handoff-artifact/rotation side effects.

## Event-driven agent completion

Agent waiting is:

```text
subscribe(agent_update)
        |
        +--> refetch current snapshot
        |
        +--> updates trigger refetch
        |
        `--> terminal state + turn evidence -> read recent timeline -> complete
```

Subscription is installed **before** the first refetch so a transition cannot fall between the snapshot and listener setup. For a continued/materialized turn, however, dispatch necessarily occurs before this observation client is installed. AEH therefore captures durable turn evidence before dispatch as well as observing lifecycle events afterwards.

For a newly created agent, an assistant response in the fresh timeline can prove that a very fast turn completed before the subscription was installed. For a continued/reused agent, AEH captures both the latest assistant response and Paseo's canonical `lastUserMessageAt` **before dispatch**. An `idle` snapshot is accepted only when at least one of these is true:

- AEH observed an active-turn status (`working`, `running`, `streaming`, `starting`) or `activeTurn` before returning to terminal state;
- the latest assistant response differs from the pre-dispatch baseline;
- `lastUserMessageAt` differs from the pre-dispatch baseline, proving that Paseo accepted a distinct new user turn even when native/structured output does not surface as ordinary assistant text.

A subscription notification by itself is **not** turn activity. Metadata-only updates with unchanged assistant output and unchanged `lastUserMessageAt` remain insufficient. This closes the fast structured-output race (`idle -> running -> idle` before subscription) without weakening the barrier to accept arbitrary idle snapshots.

Fallback order:

```text
Paseo SDK subscription
        ↓ unavailable
Paseo SDK wait surface
        ↓ unavailable
Paseo CLI wait/log surface
```

The selected observation path is emitted in Paseo integration traces. This
describes the current runtime path selection; no fixed Paseo version floor is
claimed.

## Detached operation completion wake-up

A detached AUDIT, CHANGE, or RUN deliberately outlives the conversational turn that starts it. The initiating lead is therefore not required to remain active or poll until all reviewers/workers finish.

For a managed-lead MCP start, AEH resolves the current lead identity and persists a completion target beside the operation:

```text
.harness/operations/<operation-id>.completion.json
```

The completion target has an independent lifecycle:

```text
PENDING -> SENT
        -> FAILED
        -> DISABLED
```

When the engineering operation becomes `SUCCEEDED`, `FAILED`, or `CANCELLED`, the controller first persists that terminal engineering state, then sends a non-blocking follow-up to the existing Paseo lead. The message starts with:

```text
[AEH_OPERATION_COMPLETED]
```

and includes the operation id/status plus the durable result/report path when available. The callback tells the lead to continue the original pending user request, read the existing operation/report, and **not** start a duplicate operation.

This solves the case where the lead's original turn ends while reviewers are still running. The reviewers remain independent top-level Paseo agents; the completion callback reactivates the lead only after the controller's full completion barrier has resolved and the operation is terminal.

Callback delivery does not participate in engineering acceptance. If the follow-up cannot be delivered, the callback sidecar becomes `FAILED` and the failure is traced, but a successful AUDIT, CHANGE, or RUN remains successful. `aeh_operation_status` is therefore a recovery/diagnostic surface, not the normal mechanism for keeping a conversational turn alive.

Cancellation uses the same terminal callback path after worker cleanup. A synchronous controller spawn failure disables a callback that could otherwise arrive as a confusing continuation after the start tool itself already failed.

## Provider/model preflight

Before creating or materializing an agent, AEH attempts a public-SDK preflight:

1. read the provider snapshot for the target cwd;
2. reject explicitly disabled/error/unavailable providers;
3. use the snapshot model catalog when available;
4. otherwise call `listModels(provider, { cwd })`;
5. when provider/model discovery fails, obtain a provider diagnostic where supported;
6. fail before `createAgent` when the catalog authoritatively excludes the requested model;
7. if the installed SDK does not expose provider preflight APIs, record `provider.preflight.skipped` and let agent creation remain authoritative.

AEH does not force provider refreshes on every launch. Paseo owns snapshot caching and explicit refresh semantics.

## Deterministic OpenCode native identity

AEH must not resolve a logical agent and then allow OpenCode to choose a different execution identity from ambient machine configuration. For every AEH-selected OpenCode agent, the Harness compiles a concrete native binding.

When `execution.nativeAgent` is absent, AEH synthesizes a deterministic session-local primary agent such as:

```text
AEH logical agent: code-quality-reviewer
OpenCode agent:    aeh-code-quality-reviewer
```

The generated OpenCode configuration contains the concrete model, projected permissions, primary mode, AEH identity prompt and `default_agent`. It is supplied only to that provider process through:

```text
OPENCODE_CONFIG_CONTENT=<compiled JSON>
```

For an AEH-managed generated identity, Paseo **must not** receive that generated ID as `AgentSessionConfig.modeId`. Paseo validates explicit modes against its provider catalog before the per-session OpenCode process starts, so a session-local generated agent cannot exist at that validation point. AEH leaves `modeId` unset; Paseo therefore omits the OpenCode prompt `agent` selector, and OpenCode deterministically selects the injected session-local `default_agent`. The launch environment is passed as top-level create-agent `env`, not embedded in `AgentSessionConfig`.

If `execution.nativeAgent` is explicitly configured, AEH preserves that exact external identity instead of synthesizing a replacement. Because that identity is expected to exist in the provider-visible configuration, AEH passes it as Paseo `modeId` and uses provider mode discovery to verify that it is selectable for the target cwd. Missing explicit agents fail before a user prompt is sent; AEH does not silently fall back to OpenCode's default agent.

The same compiled binding is used by direct and Podman OpenCode execution. Transport therefore does not change native identity.

A session-scoped OpenCode launch environment is an SDK-required semantic boundary. If the Paseo SDK becomes unavailable, AEH refuses CLI launch fallback for that session rather than dropping `OPENCODE_CONFIG_CONTENT` and reintroducing ambient `default_agent` behavior.

Relevant labels/traces include:

```text
aeh.native-agent
aeh.native-agent.source
harness.paseo.provider.mode.preflight
```

`aeh.native-agent.source` is `aeh-managed` for compiled identities and `explicit` for externally configured native agents. Provider mode preflight applies only when AEH actually supplies an explicit `modeId`; generated session-local identities are represented by the native-agent labels and inline OpenCode configuration instead of a Paseo mode.

## Current CLI calls in AEH

The active AEH source still uses the Paseo CLI for a small set of operations.
These are current transport choices, not claims that the latest public SDK is
missing the corresponding high-level API. The upstream [SDK reference](https://github.com/getpaseo/paseo/blob/main/public-docs/sdk/reference.md)
documents client-managed workspaces, workspace titles, and agent handles. AEH
has not migrated every CLI call to those SDK methods.

### Operation workspace creation

For detached operation workspaces, AEH currently runs:

```text
paseo workspace create --isolation local --path ... --title ... --json
```

This creates an orchestration grouping in the existing repository directory; it
does not create a Git delivery worktree. The command and result are recorded in
Paseo integration traces.

Trace events:

```text
harness.paseo.workspace.cli.required
harness.paseo.workspace.cli.created
harness.paseo.workspace.cli.error
```

### External controller cleanup

The external deterministic controller currently stops exact operation-owned
agents with `paseo stop <agent-id>` and archives owned workspaces through the
Paseo CLI. AEH does not import Paseo's internal `DaemonClient` APIs. The public
SDK reference documents agent and workspace handles, but this AEH cleanup path
has not been migrated to them.

Trace events:

```text
harness.paseo.cleanup.cli.required
harness.paseo.cleanup.cli.stop
harness.paseo.cleanup.cli.error
```

These two gaps should be removed when the public SDK reaches parity.

## Integration traces

Paseo integration events are always persisted locally to:

```text
.harness/telemetry/paseo.ndjson
```

When normal Harness telemetry is enabled, the same event is also emitted through `recordEvent` and the configured OTLP path.

Representative events:

```text
harness.paseo.provider.preflight
harness.paseo.provider.preflight.skipped
harness.paseo.provider.mode.preflight
harness.paseo.agent.identity
harness.paseo.agent.launch
harness.paseo.agent.materialize
harness.paseo.agent.dispatch
harness.paseo.agent.snapshot
harness.paseo.agent.turn.baseline
harness.paseo.agent.turn.baseline.skipped
harness.paseo.agent.wait
harness.paseo.agent.wait.completed
harness.paseo.agent.wait.fallback
harness.paseo.context.identity
harness.paseo.context.status
harness.paseo.context.handoff
harness.paseo.operation.callback.target
harness.paseo.operation.callback.registered
harness.paseo.operation.callback.sent
harness.paseo.operation.callback.failed
harness.paseo.operation.callback.disabled
harness.paseo.fallback.cli
harness.paseo.workspace.cli.*
harness.paseo.cleanup.cli.*
```

A useful trace answers:

- which transport was selected (`sdk` or `cli`);
- which observation source was used (`subscription`, snapshot, sdk-wait, cli-wait);
- how the managed lead identity was resolved (`argument`, `environment`, `lead-state`);
- which AEH logical agent/native OpenCode identity was selected and whether it was generated or explicit;
- whether an `idle` completion had real turn evidence rather than a metadata-only update;
- whether a detached completion callback was registered and delivered;
- whether a fallback was exceptional or an intentional SDK parity gap;
- why the fallback occurred;
- the associated agent/operation/provider/model/workspace;
- the relevant duration/status/error when applicable.

## Superseding a CLI path

When a change replaces one of these production CLI paths with the public SDK:

1. migrate current callers and provider contracts to the SDK path;
2. add a regression proving the SDK path's required semantics and lifecycle;
3. update current documentation and traces to the new behavior;
4. delete the superseded CLI branch and compatibility checks unless an
   externally approved compatibility surface, lifetime, and removal condition
   are recorded.
