Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions packages/opencode/script/postinstall.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,39 @@ function printWelcome(version) {
out(bot)
}

function copyDirRecursive(src, dst) {
fs.mkdirSync(dst, { recursive: true })
for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
const srcPath = path.join(src, entry.name)
const dstPath = path.join(dst, entry.name)
if (entry.isDirectory()) {
copyDirRecursive(srcPath, dstPath)
} else {
fs.copyFileSync(srcPath, dstPath)
}
}
}

/**
* Copy bundled skills to ~/.altimate/builtin/ on every install/upgrade.
* The entire directory is wiped and replaced so each release is the single
* source of truth. Intentionally separate from ~/.altimate/skills/ which users own.
*/
function copySkillsToAltimate() {
try {
const skillsSrc = path.join(__dirname, "skills")
if (!fs.existsSync(skillsSrc)) return // skills not in package (shouldn't happen)

const builtinDst = path.join(os.homedir(), ".altimate", "builtin")

// Full wipe-and-replace — each release owns this directory entirely
if (fs.existsSync(builtinDst)) fs.rmSync(builtinDst, { recursive: true, force: true })
copyDirRecursive(skillsSrc, builtinDst)
} catch {
// Non-fatal — skills can be installed manually
}
}

/**
* Write a marker file so the CLI can show a welcome/upgrade banner on first run.
* npm v7+ silences postinstall stdout, so the CLI reads this marker at startup instead.
Expand Down Expand Up @@ -144,6 +177,7 @@ async function main() {
// On Windows, the .exe is already included in the package and bin field points to it
// No postinstall setup needed
if (version) writeUpgradeMarker(version)
copySkillsToAltimate()
return
}

Expand All @@ -161,6 +195,7 @@ async function main() {
// Write marker only — npm v7+ suppresses all postinstall output.
// The CLI picks up the marker and shows the welcome box on first run.
if (version) writeUpgradeMarker(version)
copySkillsToAltimate()
} catch (error) {
console.error("Failed to setup altimate-code binary:", error.message)
process.exit(1)
Expand Down
2 changes: 2 additions & 0 deletions packages/opencode/script/publish.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ const version = Object.values(binaries)[0]

await $`mkdir -p ./dist/${pkg.name}`
await $`cp -r ./bin ./dist/${pkg.name}/bin`
await $`cp -r ./src/skill/builtin ./dist/${pkg.name}/skills`
await $`cp ./script/postinstall.mjs ./dist/${pkg.name}/postinstall.mjs`
await Bun.file(`./dist/${pkg.name}/LICENSE`).write(await Bun.file("../../LICENSE").text())
await Bun.file(`./dist/${pkg.name}/CHANGELOG.md`).write(await Bun.file("../../CHANGELOG.md").text())
Expand Down Expand Up @@ -70,6 +71,7 @@ const unscopedDir = `./dist/${unscopedName}`
try {
await $`mkdir -p ${unscopedDir}`
await $`cp -r ./bin ${unscopedDir}/bin`
await $`cp -r ./src/skill/builtin ${unscopedDir}/skills`
await $`cp ./script/postinstall.mjs ${unscopedDir}/postinstall.mjs`
await Bun.file(`${unscopedDir}/LICENSE`).write(await Bun.file("../../LICENSE").text())
await Bun.file(`${unscopedDir}/CHANGELOG.md`).write(await Bun.file("../../CHANGELOG.md").text())
Expand Down
134 changes: 134 additions & 0 deletions packages/opencode/src/skill/builtin/cost-report/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
---
name: cost-report
description: Analyze Snowflake query costs and identify optimization opportunities
---

# Cost Report

## Requirements
**Agent:** any (read-only analysis)
**Tools used:** sql_execute, sql_analyze, finops_analyze_credits, finops_expensive_queries, finops_warehouse_advice, finops_unused_resources, finops_query_history

Analyze Snowflake warehouse query costs, identify the most expensive queries, detect anti-patterns, and recommend optimizations.

## Workflow

1. **Query SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY** for the top 20 most expensive queries by credits used:

```sql
SELECT
query_id,
query_text,
user_name,
warehouse_name,
query_type,
credits_used_cloud_services,
bytes_scanned,
rows_produced,
total_elapsed_time,
execution_status,
start_time
FROM SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY
WHERE start_time >= DATEADD('day', -30, CURRENT_TIMESTAMP())
AND execution_status = 'SUCCESS'
AND credits_used_cloud_services > 0
ORDER BY credits_used_cloud_services DESC
LIMIT 20;
```

Use `sql_execute` to run this query against the connected Snowflake warehouse.

2. **Group and summarize** the results by:
- **User**: Which users are driving the most cost?
- **Warehouse**: Which warehouses consume the most credits?
- **Query type**: SELECT vs INSERT vs CREATE TABLE AS SELECT vs MERGE, etc.

Present each grouping as a markdown table.

3. **Analyze the top offenders** - For each of the top 10 most expensive queries:
- Run `sql_analyze` on the query text to detect anti-patterns (SELECT *, missing LIMIT, cartesian products, correlated subqueries, etc.)
- Summarize anti-patterns found and their severity

4. **Classify each query into a cost tier**:

| Tier | Credits | Label | Action |
|------|---------|-------|--------|
| 1 | < $0.01 | Cheap | No action needed |
| 2 | $0.01 - $1.00 | Moderate | Review if frequent |
| 3 | $1.00 - $100.00 | Expensive | Optimize or review warehouse sizing |
| 4 | > $100.00 | Dangerous | Immediate review required |

5. **Warehouse analysis** - Run `finops_warehouse_advice` to check if warehouses used by the top offenders are right-sized.

6. **Unused resource detection** - Run `finops_unused_resources` to find:
- **Stale tables**: Tables not accessed in the last 30+ days (candidates for archival/drop)
- **Idle warehouses**: Warehouses with no query activity (candidates for suspension/removal)

Include findings in the report under a "Waste Detection" section.

7. **Query history enrichment** - Run `finops_query_history` to fetch recent execution patterns:
- Identify frequently-run expensive queries (high frequency × high cost = top optimization target)
- Find queries that could benefit from result caching or materialization

8. **Output the final report** as a structured markdown document:

```
# Snowflake Cost Report (Last 30 Days)

## Summary
- Total credits consumed: X
- Number of unique queries: Y
- Most expensive query: Z credits

## Cost by User
| User | Total Credits | Query Count | Avg Credits/Query |
|------|--------------|-------------|-------------------|

## Cost by Warehouse
| Warehouse | Total Credits | Query Count | Avg Credits/Query |
|-----------|--------------|-------------|-------------------|

## Cost by Query Type
| Query Type | Total Credits | Query Count | Avg Credits/Query |
|------------|--------------|-------------|-------------------|

## Top 10 Expensive Queries (Detailed Analysis)

### Query 1 (X credits) - DANGEROUS
**User:** user_name | **Warehouse:** wh_name | **Type:** SELECT
**Anti-patterns found:**
- SELECT_STAR (warning): Query uses SELECT * ...
- MISSING_LIMIT (info): ...

**Optimization suggestions:**
1. Select only needed columns
2. Add LIMIT clause
3. Consider partitioning strategy

**Cost tier:** Tier 1 (based on credits used)

...

## Waste Detection
### Unused Tables
| Table | Last Accessed | Size | Recommendation |
|-------|--------------|------|----------------|

### Idle Warehouses
| Warehouse | Last Query | Size | Recommendation |
|-----------|-----------|------|----------------|

## Recommendations
1. Top priority optimizations
2. Warehouse sizing suggestions
3. Unused resource cleanup
4. Scheduling recommendations
```

## Usage

The user invokes this skill with:
- `/cost-report` -- Analyze the last 30 days
- `/cost-report 7` -- Analyze the last 7 days (adjust the DATEADD interval)

Use the tools: `sql_execute`, `sql_analyze`, `finops_analyze_credits`, `finops_expensive_queries`, `finops_warehouse_advice`, `finops_unused_resources`, `finops_query_history`.
135 changes: 135 additions & 0 deletions packages/opencode/src/skill/builtin/data-viz/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
---
name: data-viz
description: >
Build modern, interactive data visualizations and dashboards using code-based
component libraries (shadcn/ui, Recharts, Tremor, Nivo, D3, Victory, visx).
Use this skill whenever the user asks to visualize data, build dashboards,
create analytics views, chart metrics, tell a data story, build a reporting
interface, create KPI cards, plot graphs, or explore a dataset — even if they
mention PowerBI, Tableau, Streamlit, Metabase, Looker, Grafana, or similar
tools. Also trigger when the user says "make a dashboard", "show me the data",
"chart this", "visualize trends", "build an analytics page", "data story", or
anything involving turning raw data into interactive visual interfaces. If the
task involves presenting data visually — this is the skill. Always prefer
building a real, interactive, code-based UI over exporting to or recommending
a BI platform.
---

# AI-First Data Visualization

## Philosophy

Build production-quality interactive data interfaces with modern component libraries — no vendor lock-in, embeddable anywhere. When no tool is specified, build code-first. When the user explicitly names a BI tool, use it — only suggest code-first if they ask for options or hit a technical blocker.

## Technology Stack

Full API patterns & code: `references/component-guide.md`

### Framework Priority

1. **React + Tailwind** — Default when JSX/TSX supported
2. **HTML + CSS + Vanilla JS** — Fallback (use D3 or Chart.js)
3. **Python (Plotly/Dash)** — Python-only environments only

### Library Selection

| Library | Best For |
|---------|----------|
| **shadcn/ui charts** | Default first choice — general dashboards, most chart types |
| **Recharts** | Line, bar, area, composed, radar — fine-grained control |
| **Tremor** | KPI cards, metric displays, full dashboard layouts |
| **Nivo** | Heatmaps, treemaps, choropleth, calendar, Sankey, funnel |
| **visx** | Bespoke custom viz — D3-level control with React |
| **D3.js** | Force-directed graphs, DAGs, maps — maximum flexibility |
| **Victory** | When animation quality matters most |

**Supporting**: Tailwind CSS · Radix UI · Framer Motion · Lucide React · date-fns · Papaparse · lodash

## Building a Visualization

### Step 1: Understand the Data Story

Before code, identify: **What question does the data answer?** Who is the audience (exec → KPIs only, analyst → drill-down, public → narrative)? **What's the ONE key insight?** Design around it.

### Step 2: Choose Chart Type

| Data Relationship | Chart Type | Library |
|---|---|---|
| Trend over time | Line, Area | shadcn/Recharts |
| Category comparison | Bar (horizontal if many) | shadcn/Recharts |
| Part of whole | Donut, Treemap | shadcn/Nivo |
| Distribution | Histogram, Box, Violin | Nivo/visx |
| Correlation | Scatter, Bubble | Recharts/visx |
| Geographic | Choropleth, Dot map | Nivo/D3 |
| Hierarchical | Treemap, Sunburst | Nivo |
| Flow / Process | Sankey, Funnel | Nivo/D3 |
| Single KPI | Metric card, Gauge, Sparkline | Tremor/shadcn |
| Multi-metric overview | Dashboard grid of cards | Tremor + shadcn |
| Ranking | Horizontal bar, Bar list | Tremor |
| Column/model lineage | Force-directed DAG | D3 |
| Pipeline dependencies | Hierarchical tree, DAG | D3/Nivo |
| Multi-dimensional quality | Radar/Spider | Recharts |
| Activity density over time | Calendar heatmap | Nivo |
| Incremental change breakdown | Waterfall | Recharts (custom) |

### Step 3: Build the Interface

Start from this layout — remove what the data doesn't need:

```
┌─────────────────────────────────────────┐
│ Header: Title + Description + Date Range│
├─────────────────────────────────────────┤
│ KPI Row: 3-5 metric cards + sparklines │
├─────────────────────────────────────────┤
│ Primary Visualization (largest chart) │
├──────────────────┬──────────────────────┤
│ Secondary Chart │ Supporting Chart/Tbl │
├──────────────────┴──────────────────────┤
│ Detail Table (sortable, filterable) │
└─────────────────────────────────────────┘
```

A single insight might just be one chart with a headline and annotation. Scale complexity to audience.

### Step 4: Design Principles

- **Data-ink ratio**: Remove chartjunk — unnecessary gridlines, redundant labels, decorative borders
- **Color with purpose**: Encode meaning (red=bad, green=good, blue=neutral). Max 5-7 colors. Single-hue gradient for sequential data
- **Typography hierarchy**: Title → subtitle (muted) → axis labels (small) → data labels
- **Responsive**: `min-h-[VALUE]` on all charts. Grid stacks on mobile
- **Animation**: Entry transitions only, `duration-300` to `duration-500`. Never continuous
- **Accessibility**: `aria-label` on charts, WCAG AA contrast, don't rely on color alone

### Step 5: Interactivity & Annotations

**Priority**: Tooltips (every chart) → Filtering → Sorting → Drill-down → Cross-filtering → Export → Annotations

**Annotations** turn charts into stories. Mark: inflection points, threshold crossings (amber), external events (indigo/red), anomalies (red), achievements (green). **Limit 3 per chart.** Implementation: `references/component-guide.md` → Annotation Patterns.

### Step 6: Tell the Story

- **Headline states insight**: "Revenue grew 23% QoQ, driven by enterprise" — not "Q3 Revenue Chart"
- **Annotate key moments** directly on chart
- **Contextual comparisons**: vs. prior period, vs. target, vs. benchmark
- **Progressive disclosure**: Overview first — detail on demand

## Environment-Specific Guidance

| Environment | Approach |
|---|---|
| **Claude Artifacts** | React (JSX), single file, default export. Available: `recharts`, `lodash`, `d3`, `lucide-react`, shadcn via `@/components/ui/*`, Tailwind |
| **Claude Code / Terminal** | Vite + React + Tailwind. Add shadcn/ui + Recharts. Structure: `src/components/charts/`, `src/components/cards/`, `src/data/` |
| **Python / Jupyter** | Plotly for charts, Plotly Dash for dashboards |
| **Cursor / Bolt / other IDEs** | Match existing framework. Prefer shadcn/ui if present |

## Anti-Patterns

- Screenshot/static charts — build interactive components
- Defaulting to BI tools unprompted — build code-first when no tool specified
- Default matplotlib — always customize in Python
- Rainbow palettes — use deliberate, meaningful colors
- 3D charts — almost never appropriate
- Pie charts > 5 slices — use horizontal bar
- Unlabeled dual y-axes — use two separate charts
- Truncated bar axes — always start at zero
Loading
Loading