# StratoFusion AI Operating Protocol

This document is the canonical public-docs reference for AI-assisted StratoFusion work. It consolidates the former `docs/ai/*` workflow files into the `public/docs/` documentation tree.

For live agent instructions, the root `AGENTS.md` file remains the execution contract. This document keeps the same guidance available through `/dev/docs`.

## Role And Context

AI agents working in this repository act as senior software architects and engineers on StratoFusion, a SaaS platform that unifies cloud storage providers such as Google Drive, OneDrive, and Dropbox into a single UI.

- Data-plane operations execute through the rclone worker in the current VM Compose stack. Stopped Fly.io apps preserve the legacy deployment for approved recovery only.
- Local development is Windows 11.
- Do not use or assume WSL.
- Keep architecture provider-agnostic and interface-first.

## Environment And Tooling

### Shells

- Use PowerShell for normal Codex commands, git, PNPM, Node, tests, file inspection, and repo work on Windows.
- Use Git Bash only for `.sh` scripts or commands that require POSIX shell behavior.
- Invoke Git Bash explicitly with `C:\Program Files\Git\bin\bash.exe`.
- Never invoke bare `bash`.
- Use Windows paths in PowerShell and `/c/...` paths only inside Git Bash.

### Package Management

- PNPM is mandatory.
- Run `pnpm env:guard` before repo shell workflows.
- Shell scripts must remain compatible with Git Bash.

## Architecture Standards

### Core Principles

- UI components render only.
- Business behavior belongs in domain modules, services, ports, adapters, or hooks.
- Provider-specific IDs, raw paths, rate-limit shapes, and response formats must not leak into UI components.
- Depend on interfaces and canonical models, not concrete provider implementations.
- Prefer deep modules with stable interfaces over shallow helper sprawl.
- Keep files under 500 LOC.

### Provider Contract

When adding or changing provider behavior:

1. Start from the shared provider interface or an explicit port.
2. Translate provider outputs into canonical models such as `FileItem`, `FolderItem`, and `PathRef`.
3. Treat `(provider, account, resource)` as the ownership and behavior boundary.
4. Keep provider quirks inside adapters, provider services, or domain services.
5. Add deterministic tests with external systems mocked behind interfaces.

## Rclone Safety

Data safety is the highest-priority constraint for transfer work.

- Always state source, destination, direction, and flags before launch.
- Manual rclone commands default to `--dry-run` unless the user explicitly approves otherwise.
- Delete, purge, overwrite, move, sync-delete, and cleanup semantics require explicit approval or a clear task mandate.
- Copy, move, backup, one-way sync, two-way sync, and bisync are different workflows. Do not collapse their semantics.
- Scrub rclone configs, OAuth tokens, API keys, database URLs, and secrets from logs.
- Launch paths must validate auth, provider quota, transfer quota, conflicts, cancellation, retry, timeout, and reconciliation behavior before expensive work starts.

## Ubiquitous Language

| Term                | StratoFusion meaning                                                                      | Notes                                                                           |
| ------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| Provider            | A cloud storage backend such as Google Drive, OneDrive, Dropbox, Box, pCloud, or Jupiter. | Hide provider-specific API behavior behind stable boundaries.                   |
| Account             | A user's connected identity within a provider.                                            | Never assume one account per provider.                                          |
| Resource            | A provider-backed object StratoFusion can address.                                        | Normalize resources before using them as business truth.                        |
| FileItem            | Canonical file model.                                                                     | Hides provider IDs, MIME quirks, timestamps, and download behavior.             |
| FolderItem          | Canonical folder model.                                                                   | Handles provider differences such as duplicate names and empty-folder behavior. |
| PathRef             | Canonical reference to a location or item path.                                           | Do not treat raw provider paths as UI business truth.                           |
| Service             | Domain or application module that owns a capability.                                      | UI calls service-facing interfaces or hooks.                                    |
| Adapter             | Translation layer from provider shape to canonical shape.                                 | Provider conditionals live here or in provider services.                        |
| Port                | Stable interface for an outside capability.                                               | Use ports when behavior must be testable or replaceable.                        |
| Operation           | Concrete execution unit, often rclone-backed.                                             | Operations are not the same as scheduled jobs.                                  |
| Job                 | Durable backup or sync intent with schedule, sources, destination, and child operations.  | Reconciliation handles partial launches and terminal children.                  |
| Transfer            | General movement or comparison work across providers or accounts.                         | Always name source, destination, direction, and destructive flags.              |
| Copy                | Non-destructive transfer that leaves the source intact.                                   | Single-file rclone copy uses `copyto` when a target filename is required.       |
| Move                | Transfer that removes or relocates the source after copying.                              | Treat as potentially destructive.                                               |
| Backup              | One-way preservation workflow from selected sources to a destination.                     | Default to non-destructive behavior and explicit conflict handling.             |
| Sync                | Ongoing convergence workflow, one-way or two-way.                                         | Two-way/bisync has initialization and conflict semantics.                       |
| Data plane          | Execution layer for file bytes and large transfers.                                       | Rclone worker in the production VM Compose stack; stopped Fly.io recovery apps. |
| Control plane       | Next.js/API/domain layer for validation, ID resolution, auth, quotas, and state.          | Prepares safe execution inputs.                                                 |
| Provider quota      | Cloud-provider storage or API capacity limit.                                             | Distinguish from StratoFusion transfer quotas.                                  |
| Transfer quota      | StratoFusion plan or time-window transfer allowance.                                      | Enforce before launching expensive work.                                        |
| Conflict resolution | Destination collision policy.                                                             | Keep policies canonical and translate at provider/rclone boundaries.            |

## Feature Workflow

### 0. Load AI Skills

Repo-local agent skills live under `docs/ai-skills/`. Start with
`docs/ai-skills/INDEX.md`, then load the smallest relevant skill set for the
task. Use `docs/ai-skills/01-architecture.md` for every non-trivial change, and
add domain skills for provider, rclone/Fly, API, UI, testing, OAuth, billing,
deployment, AI Search, RAG, code review, or prompt creation work.

The skills summarize the canonical docs. If a skill and this public protocol
ever drift, update the skill or follow this protocol and `AGENTS.md`.

### Optional Agent Delivery Harness

When a task explicitly opts into Agent Delivery Harness v1, also follow
[`AGENT_DELIVERY_HARNESS.md`](./AGENT_DELIVERY_HARNESS.md). The harness adds a
human-confirmed risk tier, isolated task lease, bounded review/repair cycle,
optional private evidence, and human-ready handoff. It does not authorize
unattended writing, merging, deployment, production access, external
communication, or repository-setting changes.

### 1. Read Context

- Read `AGENTS.md`, `README.md`, and the relevant docs under `public/docs/`.
- Identify affected domains: provider services, adapters, rclone/Fly, OAuth/auth, quotas, subscriptions, jobs, UI, and docs.
- Locate existing interfaces before creating new helpers.
- Confirm Windows constraints: PowerShell by default, PNPM only, explicit Git Bash only when required, no WSL.

### 2. Clarify

Ask before editing when any of these are unclear:

- Source, destination, direction, or destructive behavior.
- Provider/account/resource boundaries.
- OAuth scopes, token refresh behavior, reconnect prompts, or multi-account behavior.
- Provider quota, transfer quota, trial, or subscription-tier implications.
- Whether rclone work is copy, move, backup, one-way sync, two-way sync, or bisync.

### 3. Plan

- Prefer interface-first design.
- Keep provider quirks inside adapters, provider services, or domain services.
- Choose the feedback loop before implementation: TypeScript, unit, integration, component, Playwright/E2E, or manual verification.
- Map docs updates to canonical files.
  - Architecture: `public/docs/ARCHITECTURE.md`.
  - API: `public/docs/API_REFERENCE.md`.
  - Deployment/env: `public/docs/DEPLOYMENT.md`.
  - Billing/trial: `public/docs/SUBSCRIPTION_MANAGEMENT.md`.
  - rclone/Fly: `public/docs/RCLONE_SERVICE.md`.
  - Testing: `public/docs/TESTING.md`.

### 4. Implement

- Make the smallest coherent patch.
- Keep UI render-focused.
- Avoid `any`; use explicit types and canonical models.
- Mock external systems behind interfaces.
- For rclone/Fly changes, state source, destination, command intent, and flags.
- Preserve secrets in code, logs, tests, docs, and terminal output.

### 5. Verify

- Run the targeted checks selected in the plan.
- Use deterministic tests for provider normalization, auth failures, quota enforcement, retries, timeouts, conflicts, and cancellation.
- Use component tests for UI behavior.
- Use Playwright/E2E for browser, OAuth, or transfer-progress workflows.
- For docs-only changes, run a lightweight validation such as `pnpm check` or targeted type/lint checks when practical.

### 6. Report

Summarize:

- Files changed.
- Behavior, docs, or prompts added.
- Checks run and results.
- Risks, skipped verification, cleanup candidates, and follow-ups.

## Feature Intake Template

Use this template before non-trivial StratoFusion changes.

```markdown
# Feature Name

`[short name]`

## Goal

`[one or two sentences describing the user/business problem]`

## User Workflow

- Entry point:
- Primary action:
- Success state:
- Failure or blocked state:

## Inputs

- User inputs:
- API inputs:
- Provider/account/resource inputs:
- Environment or subscription inputs:

## Outputs

- UI result:
- API result:
- Durable state changes:
- Transfer or rclone operation result:

## Architecture Impact

- UI components:
- Hooks or client state:
- API routes:
- Services/domain modules:
- Ports/interfaces:
- Provider adapters:
- PostgreSQL state/projections (Compose in production, retained environment-specific database elsewhere):
- rclone service and legacy Fly.io recovery:
- Docs:

## Provider Boundary

- Providers involved:
- Accounts involved:
- Canonical models used:
- Provider quirks hidden behind adapters/services:

## Safety And Policy

- Source:
- Destination:
- Destructive behavior:
- Conflict policy:
- OAuth/auth behavior:
- Provider quota behavior:
- Transfer quota or subscription-tier behavior:
- Secrets/logging concerns:

## Implementation Plan

1. Types and interfaces:
2. Service/domain logic:
3. API route or server action:
4. Hook/client integration:
5. UI rendering:
6. Docs update:

## Verification Plan

- TypeScript:
- Unit tests:
- Integration tests:
- Component tests:
- Playwright/E2E:
- Manual verification:

## Edge Cases

- Auth failure or expired token:
- Provider rate limit or quota:
- Transfer quota exceeded:
- Timeout, retry, cancellation, or partial failure:
- Duplicate names or conflict resolution:
- Large folder or metadata-heavy operation:
- Multi-account mismatch:
- Windows/no-WSL tooling:
```

## Implementation Patterns

### New API Endpoint

1. Define or reuse request/response types.
2. Put business logic in a service or domain module.
3. Keep the API route thin: auth, validation, service call, response mapping.
4. Return the canonical response/error shape for that area.
5. Add focused tests for validation, auth failure, service failure, and success.
6. Update `public/docs/API_REFERENCE.md` when the public contract changes.

### Provider Capability Or Operation

1. Start from the shared provider interface or port.
2. Implement provider behavior inside the provider service or adapter.
3. Translate raw provider records into canonical models.
4. Register the capability through the existing service registry path.
5. Verify multi-account behavior with `(provider, account, resource)` cases.
6. Keep UI changes unnecessary unless the user-facing workflow changes.

### Cross-Provider Transfer

1. Validate source, destination, account IDs, resources, conflict policy, and quota limits.
2. Resolve provider services through existing service boundaries.
3. Normalize source and destination into canonical references.
4. Preflight auth, provider quota, transfer quota, and destination conflicts.
5. Launch through the rclone service and return operation IDs promptly.
6. Surface progress through existing polling, SSE, and job mechanisms.
7. Reconcile partial launches, cancellation, and terminal child operations.

### Long-Running Job

1. Persist durable job intent before long-running execution.
2. Store schedule, timezone, sources, destination, mode, quota state, and user ownership.
3. Launch child operations without blocking request completion on deep provider enumeration.
4. Track cancellation, retry, timeout, and partial-failure states explicitly.
5. Reconcile stale jobs from durable operation snapshots and worker state.
6. Document behavior in architecture, rclone, API, or testing docs as appropriate.

### UI Workflow

1. Keep React components render-focused.
2. Put data loading, mutations, and decisions in hooks, services, or domain modules.
3. Pass canonical models to components.
4. Handle loading, empty, error, retrying, disabled, and permission states.
5. Use component tests for interaction logic and Playwright/E2E for complete flows.

### rclone/Fly Safety

1. State source, destination, direction, and flags before launch.
2. Default manual rclone commands to `--dry-run`.
3. Require approval for destructive commands or overwrite/delete semantics.
4. Scrub secrets from logs.
5. Configure timeout, stall watchdog, retry, cancellation, and retention behavior deliberately.
6. Verify the current rclone worker's health and operation status with safe endpoints; probe Fly only during approved legacy recovery.

## Review Checklist

### Architecture Boundaries

- Provider-specific logic does not leak into UI components.
- UI does not depend on raw provider IDs, raw paths, or raw API response shapes.
- Provider logic is not duplicated across routes, hooks, and components.
- Related behavior is consolidated behind service/domain boundaries.
- Interfaces are stable, explicit, and depend on canonical models.
- Provider adapters translate to canonical domain models.

### Transfer And rclone Safety

- Source, destination, direction, and flags are explicit.
- Manual rclone commands default to `--dry-run`.
- Destructive paths require explicit approval or a clear task mandate.
- Rclone launch paths validate inputs and scrub secrets in both current VM and legacy recovery deployments.
- Copy, move, backup, sync, and bisync semantics are not confused.
- Conflict resolution is explicit and translated at the boundary.

### Auth, Reliability, And Quotas

- OAuth failures, expired tokens, refresh failures, and reconnect prompts are handled.
- Multi-account behavior respects `(provider, account, resource)`.
- Timeout, retry, cancellation, and partial-failure behavior is defined.
- Provider quotas and StratoFusion transfer quotas are enforced before expensive work begins.
- Trial, billing, or subscription-tier implications are documented and tested when affected.

### Code Quality

- No file exceeds 500 LOC.
- TypeScript avoids `any`; exceptions are justified and contained.
- Secrets are not logged, exposed, committed, or copied into docs.
- Errors use canonical codes/messages where available.
- External systems are mocked behind interfaces in tests.

### Testing And Documentation

- Meaningful behavior changes include targeted tests.
- Edge cases cover auth failures, timeouts, retries, quota failures, and provider differences where relevant.
- The right feedback loop was run.
- Documentation updates are mapped to canonical docs.
- Windows-native workflow is respected.
