subagent-cortex-code-main
# Cortex Code Integration — Reference Documentation
What this skill does
# Cortex Code Integration — Reference Documentation
> **Installing?** Use: `npx skills add snowflake-labs/subagent-cortex-code --copy`
> This installs from `skills/cortex-code/` which is the universal, agent-agnostic skill.
This skill enables Claude Code to leverage Cortex Code's specialized Snowflake expertise by intelligently routing Snowflake-related operations to Cortex Code CLI in headless mode.
## Architecture Overview
**Routing Principle**: ONLY Snowflake operations → Cortex Code. Everything else → Claude Code.
**Key Components**:
- Dynamic skill discovery at session initialization
- LLM-based semantic routing (not keyword matching)
- Security wrapper with approval modes (prompt/auto/envelope_only)
- Stateless Cortex execution with context enrichment
- Hybrid memory management
- Audit logging for compliance
## Security
The skill includes a security wrapper around Cortex execution with three approval modes:
### Approval Modes
1. **prompt** (default): High security
- User shown approval prompt with predicted tools and confidence
- User must approve before execution
- No audit logging required
- Best for: Interactive sessions, untrusted prompts, production
2. **auto**: Medium security
- All operations auto-approved
- Mandatory audit logging
- Envelopes still enforced
- Best for: Automated workflows, trusted environments
3. **envelope_only**: Medium security
- No tool prediction (faster)
- Auto-approved with audit logging
- Relies on envelope blocklist only
- Best for: Trusted environments, low latency needs
**Configuration**: Set in `config.yaml` in the skill's install directory, or via organization policy.
### Built-in Protections
- **Prompt Sanitization**: Automatic PII removal and injection detection
- **Credential Blocking**: Prevents routing when credential paths detected
- **Secure Caching**: SHA256-validated cache in `~/.cache/cortex-skill/`
- **Audit Logging**: Structured JSONL logs (mandatory for auto/envelope_only)
- **Organization Policy**: Enterprise override via `~/.snowflake/cortex/claude-skill-policy.yaml`
## Session Initialization
When this skill is first loaded in a Claude Code session:
### Step 1: Discover Cortex Capabilities
```bash
python scripts/discover_cortex.py
```
This script:
1. Runs `cortex skill list` to enumerate all available Cortex skills
2. Reads each skill's SKILL.md frontmatter and trigger patterns
3. Caches capabilities with `CacheManager` in the configured cache directory
4. Returns structured data about what Cortex can handle
Expected output: JSON mapping of skill names to their trigger patterns and capabilities.
### Step 2: Load Routing Context
The discovered capabilities are loaded into memory to inform routing decisions throughout the session.
## Workflow: Handling User Requests
### Step 1: Analyze Request with LLM-Based Routing
Before taking any action, analyze the user's request:
```bash
python scripts/route_request.py --prompt "USER_PROMPT_HERE"
```
This script:
1. Loads Cortex capabilities from cache
2. Uses LLM reasoning to classify the request
3. Returns routing decision with confidence score
**Routing Logic**:
- **Route to Cortex** if request involves:
- Snowflake databases, warehouses, schemas, tables
- SQL queries specifically for Snowflake
- Cortex AI features (Cortex Search, Cortex Analyst, ML functions)
- Snowpark, dynamic tables, streams, tasks
- Data governance, data quality, or security in Snowflake context
- User explicitly mentions "Cortex" or "Snowflake"
- **Route to Claude Code** if request involves:
- Local file operations (reading, writing, editing local files)
- General programming (Python, JavaScript, etc. not Snowflake-specific)
- Non-Snowflake databases (PostgreSQL, MySQL, MongoDB, etc.)
- Web development, frontend work
- Infrastructure/DevOps unrelated to Snowflake
- Git operations, GitHub, version control
### Step 2: Execute Based on Routing Decision
#### If routed to Claude Code:
Handle the request directly using Claude Code's built-in capabilities. No Cortex involvement.
#### If routed to Cortex Code:
Proceed to Step 3.
### Step 3: Choose Security Envelope and Handle Approval
Before executing Cortex, the security wrapper handles approval based on configured mode.
#### Step 3a: Check Approval Mode
Read configuration to determine approval behavior:
- **prompt mode** (default): Requires user approval
- **auto mode**: Auto-approve with audit logging
- **envelope_only mode**: Auto-approve, no tool prediction
#### Step 3b: Handle Approval (if prompt mode)
If using prompt mode:
```bash
python scripts/security_wrapper.py \
--prompt "ENRICHED_PROMPT" \
--envelope "RW"
```
This will:
1. Predict required tools using LLM
2. Display approval prompt to user:
```
Cortex Code needs to execute the following tools:
• snowflake_sql_execute
• Read
• Write
Envelope: RW
Confidence: 85%
Approve execution? [yes/no]
```
3. If approved, proceed to Step 3c
4. If denied, abort execution
#### Step 3c: Determine Security Envelope
Determine the appropriate security envelope based on the operation:
- **RO** (Read-Only): For queries and read operations - blocks Edit, Write, destructive Bash
- **RW** (Read-Write): For data modifications - allows most operations, blocks destructive Bash
- **RESEARCH**: For exploratory work - read access plus web tools
- **DEPLOY**: For deployment operations - blocks destructive Bash commands
- **NONE**: Custom blocklist via --disallowed-tools
### Step 4: Enrich Context for Cortex
Build an enriched prompt that includes:
**Claude Conversation Context**:
- Last 2-3 relevant exchanges from current Claude session
- Any Snowflake-specific details already discussed
**Recent Cortex Session Context**:
```bash
python scripts/read_cortex_sessions.py --limit 3
```
This reads the most recent Cortex session files from `~/.local/share/cortex/sessions/` to understand what Cortex recently worked on.
**Enriched Prompt Format**:
```
# Context from Claude Code Session
[Recent relevant conversation history]
# Recent Cortex Work
[Summary from recent Cortex sessions]
# User Request
[Original user prompt]
```
### Step 5: Execute Cortex Code Headlessly
```bash
python scripts/execute_cortex.py \
--prompt "ENRICHED_PROMPT" \
--connection "connection_name" \
--envelope "RW" \
--disallowed-tools "tool1" "tool2"
```
This script:
1. Invokes `cortex -p "prompt" --output-format stream-json`
2. Uses print mode for prompt delivery and stream JSON output for non-TTY parsing
3. Applies envelope-based security via `--disallowed-tools` blocklist for safety
4. Parses NDJSON event stream in real-time
5. Detects tool use events and execution results
**Key Insight**: The wrapper intentionally does not combine `-p` with `--input-format stream-json`. Cortex reserves `--input-format` for JSON stdin input; with closed stdin, that combination can emit only an init event and exit before processing the prompt.
**Security Envelopes**:
- **RO** (Read-Only): Blocks Edit, Write, destructive Bash commands
- **RW** (Read-Write): Blocks destructive operations like rm -rf, sudo
- **RESEARCH**: Read access plus web tools, blocks write operations
- **DEPLOY**: Deployment operations, blocks destructive Bash commands
- **NONE**: Custom blocklist via --disallowed-tools parameter
**Event Stream Handling**:
- `type: assistant` → Cortex's responses, display to user
- `type: tool_use` → Cortex is calling a tool
- `type: result` → Final outcome
### Step 6: Handle Permission Requests
With the security wrapper:
- **prompt mode**: User approves BEFORE execution (no mid-execution prompts)
- **auto/envelope_only modes**: Non-blocked tools execute under the configured envelope and audit policy
The security wrapper handles permission management through:
1. **Upfront approval** (prompt mode): User approves predicted tools before execution
2. **Audit logging** (auto/envelope_only): Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.