# Rig Agent Harness Architecture

Status: Proposed

## Purpose

This document defines the planned architecture for the MosaicIQ agent harness using Rig inside the existing Tauri application. It is intentionally limited to architecture and implementation planning. It does not introduce any runtime changes by itself.

## Decision Summary

MosaicIQ should use Rig as the primary agent runtime inside the Rust/Tauri backend.

Pi in RPC mode should not be the default agent architecture for this project. It may be considered later only as a specialized integration for narrowly scoped power-user workflows that justify a separate process boundary.

## Why This Direction Fits MosaicIQ

The current repository already points toward an embedded Rust-first architecture:

- The desktop app is built with Tauri plus React.
- `rig-core` is already present in `src-tauri/Cargo.toml`.
- The current "agent" lives entirely in the frontend and uses local mock data and intent matching.
- The Rust backend is not yet acting as the application agent runtime.
- Tauri capabilities are still minimal, which is a good starting point for a constrained tool model.

Given that shape, an embedded Rig harness is the shortest path from the current state to a real in-app research agent without adding a second runtime to package, supervise, and secure.

## Product Goals

The harness should support three classes of behavior:

1. Interactive in-app research
   - Answer requests in the terminal-like UI.
   - Return structured results that map cleanly to existing panels such as company, news, portfolio, and analysis.

2. Non-interactive agentic workflows
   - Run background jobs such as scanning news, refreshing watchlists, summarizing updates, and generating research artifacts.
   - Report progress and completion back to the UI without blocking the main interaction loop.

3. Constrained file manipulation
   - Save notes, reports, exported research, and other app-managed artifacts.
   - Avoid broad arbitrary filesystem access in the initial design.

## Non-Goals

- Building a general-purpose coding agent as the primary product runtime
- Granting unrestricted shell execution to the in-app agent
- Allowing arbitrary filesystem writes outside app-managed locations in the first version
- Introducing a second long-lived Node runtime unless a later requirement clearly demands it

## Architecture Overview

```text
React UI
  |
  v
Tauri invoke/events bridge
  |
  v
Rust agent harness (Rig)
  |- session manager
  |- prompt orchestration
  |- structured output parser
  |- tool router
  |- background job coordinator
  |
  +--> market/news/data adapters
  +--> app storage adapters
  +--> constrained file tools
  +--> model provider adapters
```

## Planned Components

### 1. UI Agent Client

The React layer should become a thin client for the agent runtime rather than the place where intents are classified.

Responsibilities:

- Send interactive prompts to Rust
- Subscribe to agent events and status updates
- Render structured outputs into the existing panel system
- Surface approval requests for restricted actions
- Display progress for long-running jobs

Out of scope:

- Model orchestration
- business logic for tool execution
- local intent heuristics as the source of truth

### 2. Tauri Bridge Layer

Tauri should expose a narrow application protocol for agent actions.

Planned command surface:

- `agent_prompt`
  - Start or continue an interactive agent turn for a workspace
- `start_background_job`
  - Launch a non-interactive workflow
- `get_job_status`
  - Query a job snapshot
- `cancel_job`
  - Stop an in-progress job
- `approve_action`
  - Confirm a restricted write or other gated operation

Planned event surface:

- `agent_delta`
- `agent_result`
- `agent_tool_started`
- `agent_tool_finished`
- `agent_needs_approval`
- `job_progress`
- `job_completed`
- `job_failed`

The bridge should stay application-specific. It should not mirror a generic coding-agent protocol unless MosaicIQ later proves that it needs one.

### 3. Rig Agent Core

Rig should be the orchestration engine inside Rust.

Responsibilities:

- Maintain per-workspace session context
- Compose prompts from user input, workspace state, and tool results
- Select and invoke tools
- Produce structured outputs for UI rendering
- Route long-running work to the background job layer

Design constraints:

- Responses should prefer typed payloads over raw prose when the UI can render a richer result.
- Tool definitions should remain narrow and finance/product specific.
- The agent must degrade safely when tools or providers fail.

### 4. Tool Router

The tool router is the critical control surface of the harness.

Initial tool categories:

- Finance data lookup
  - company profile
  - quote snapshot
  - portfolio snapshot
- News and summarization
  - latest news scan
  - company-filtered news
  - digest generation
- Analysis helpers
  - thesis summary
  - risks and opportunities extraction
  - structured panel generation
- Storage and export
  - save note
  - save report
  - list saved artifacts
- Restricted file actions
  - write within approved app directories only

The tool router should reject actions that fall outside the allowed scope instead of silently widening permissions.

### 5. Background Job Coordinator

Non-interactive workflows should not share the same execution path as simple interactive turns.

Responsibilities:

- Queue and run jobs independently from the active terminal session
- Persist enough state to report progress and final output
- Emit progress events back to the UI
- Support cancellation where practical

Representative background jobs:

- scheduled market news scans
- watchlist brief generation
- multi-symbol analysis batches
- report compilation

### 6. Artifact and Storage Layer

The harness should distinguish between agent outputs that are transient and outputs that become durable user artifacts.

Durable artifacts may include:

- research notes
- generated summaries
- report exports
- cached workflow outputs

The storage layer should define approved directories and filename rules before any write-capable tool is enabled.

## Interaction Model

### Interactive Flow

1. User submits a prompt from the terminal UI.
2. React sends the prompt and workspace context through Tauri.
3. Rust creates or resumes the workspace session.
4. Rig evaluates whether it can answer directly or needs tools.
5. Tools execute through the router.
6. Rust emits progress and tool events back to the UI.
7. Final output is returned as either:
   - structured panel payload
   - textual response
   - approval request

### Background Flow

1. User triggers a job directly or indirectly through an agent request.
2. The job coordinator persists job metadata and starts execution.
3. The coordinator emits progress updates.
4. The final result is stored and surfaced to the UI.
5. The UI can render the result immediately or expose it from history/artifacts later.

## Session Model

Sessions should be tied to MosaicIQ workspaces or tabs.

Each session should track:

- conversation history relevant to the workspace
- last structured outputs
- pending approvals
- active jobs launched from the workspace
- tool execution summaries where needed for continuity

This keeps agent context aligned with the current UI model instead of introducing a separate session concept that the user cannot see.

## Structured Output Strategy

The agent should default to structured outputs whenever a result maps to a known UI concept.

Expected output families:

- `company`
- `portfolio`
- `news`
- `analysis`
- `report`
- `job_status`
- `text`
- `approval_request`

This preserves a clean contract between orchestration and rendering and avoids making the frontend parse narrative prose.

## Security and Permission Boundaries

The initial harness should use the narrowest viable permission model.

Defaults:

- No unrestricted shell access
- No arbitrary filesystem traversal
- No write access outside explicitly approved artifact paths
- No silent execution of destructive actions
- Restricted actions require an approval round-trip from the UI

This is a major reason not to lead with Pi RPC for the product runtime. Pi's strengths are strongest when broad tool access is desirable, but broad tool access is not the correct default for MosaicIQ at this stage.

## Why Not Pi RPC As The Default

Pi RPC mode is attractive when the core problem is open-ended tool execution, file editing, shell automation, or external process orchestration. That is not the current center of gravity for MosaicIQ.

For this project, choosing Pi RPC now would introduce:

- a second runtime to ship and supervise
- a more complex protocol boundary than the current app needs
- additional packaging and lifecycle concerns inside a Tauri desktop app
- pressure to expose a broader tool surface earlier than is desirable

Pi should only be reconsidered if MosaicIQ grows a clearly separate power-user mode that depends on:

- arbitrary workspace editing
- shell-first automation
- long-lived interactive repair or refactor loops
- strict process isolation from the main app runtime

If that happens, Pi should be integrated as a specialized external integration rather than replacing the embedded Rig harness.

## Implementation Phases

### Phase 1: Move the Agent Boundary to Rust

Outcome:

- React becomes a thin client
- Rust owns prompt handling
- the existing mock-driven flows still work through a real Tauri command boundary

### Phase 2: Add Rig-Orchestrated Structured Responses

Outcome:

- Rig produces typed outputs for existing panels
- prompt and tool orchestration moves into Rust
- frontend intent heuristics are retired as the source of truth

### Phase 3: Add Tool Routing and Approval Flow

Outcome:

- finance, news, storage, and export tools are introduced
- restricted actions require approval
- failure paths are explicit and user-visible

### Phase 4: Add Background Workflows

Outcome:

- news scans and report generation run as jobs
- jobs expose progress, completion, and failure state
- work can continue without blocking the terminal interaction path

### Phase 5: Add Bounded File Manipulation

Outcome:

- the agent can create and update app-managed artifacts
- writes are constrained to approved locations
- arbitrary editing remains out of scope unless future product needs justify it

## Acceptance Criteria

The architecture should be considered correctly implemented when all of the following are true:

- Interactive prompts flow through Rust rather than frontend-only intent matching.
- Existing panel-oriented experiences can be returned as structured outputs.
- Background workflows have a separate lifecycle from interactive turns.
- Restricted writes require explicit approval.
- Session state stays isolated per workspace/tab.
- Provider or tool failures do not corrupt session state and are surfaced clearly.

## Testing Strategy

The implementation should be validated with at least these scenarios:

- company lookup request returns a structured company panel payload
- news request can stream progress and complete with a structured news payload
- analysis request can fall back gracefully when a provider or tool fails
- a background scan job starts, reports progress, completes, and can be queried later
- a write-capable tool is denied outside approved directories
- one workspace session does not leak outputs or tool state into another

## Defaults and Assumptions

- Rig is the primary in-process agent runtime.
- Tauri remains the only required shipped runtime.
- File manipulation is limited to app-managed artifacts in the first version.
- The harness is product-specific, not a general-purpose coding agent.
- Pi RPC remains an optional future integration pattern, not the base architecture.
