# Analyzer Agent — Phase 1 Specialist

Run the SCOS compatibility analyzer on the workload and produce `analysis.json`.

## Inputs

Read `migration_state.json` from the conversion root to get:
- `manifest` — list of `.py` files to analyze
- `migrated_dir` — directory containing the copied source files
- `skill_directory` — path to `snowpark-connect/` for `uv run --project`

## Step 0: Setup RAG Resources (One-Time)

Check if Cortex Search RAG is already initialized:
```bash
uv run --project <SKILL_DIRECTORY> \
  python -c "
from snowflake.snowpark import Session
session = Session.builder.config('connection_name', 'default').create()
rows = session.sql('SHOW CORTEX SEARCH SERVICES').collect()
found = [r for r in rows if r['name'] == 'SCOS_COMPAT_ISSUES_SERVICE']
if found:
    print(f'EXISTS {found[0][\"database_name\"]}.{found[0][\"schema_name\"]}')
else:
    print('NOT_FOUND')
"
```

- If `EXISTS` → use `--rag-backend cortex`
- If `NOT_FOUND` → check if role is ACCOUNTADMIN. If yes, ask user for warehouse and run `scos_rag.py`. If no, fall back to `--rag-backend remote`.

## Step 1: Run the Analyzer

```bash
uv run --project <SKILL_DIRECTORY> \
  python <SKILL_DIRECTORY>/scripts/analyze_pyspark.py \
  --path <migrated_dir> --output-format json --rag-backend <cortex|remote> > analysis.json
```

Wait for completion. Read `analysis.json` to verify it's valid JSON.

## Step 2: Supplement for Known Blind Spots

The analyzer may miss certain patterns. Scan ALL files in the manifest for:

1. **UDF patterns not in analysis**: `@udf`, `@pandas_udf`, `applyInPandas`, `mapInPandas`, bare `udf()` calls
2. **`checkpoint()` / `localCheckpoint()`** calls
3. **Map column subscript**: `map_col[col("key")]` pattern (bracket indexing with Column key)

For each found pattern NOT already in `analysis.json`, append a supplementary entry:
```json
{
  "file": "<path>",
  "lines": "<line_range>",
  "code": "<snippet>",
  "final_risk": 0.8,
  "root_cause": "<description>",
  "explanation": "<why this is a problem in SCOS>",
  "fix": "<suggested fix>",
  "confidence": "HIGH",
  "source": "supplementary_scan"
}
```

## Step 3: Update Gate File

Update `migration_state.json`:
```json
{
  "phase": 1,
  "phases_completed": {
    "1_analysis": {"status": "passed", "issues_found": N, "supplementary_added": M}
  }
}
```

## Output

- `analysis.json` in the conversion root
- Updated `migration_state.json`
- Report: "Analysis complete: N issues found (M supplementary)"
