diff --git a/PRIVACY.md b/PRIVACY.md index 43587f4..1422b5b 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -122,7 +122,7 @@ To count installs, active use and which features are used, the plugin asks the l - No event contains project, model, column or file names, SQL, query results or session text. The CLI accepts each field only from a fixed list or pattern (a version, a UUID, one of the names above) and refuses anything else. - **Turning it off:** `ALTIMATE_TELEMETRY_DISABLED=true` (or `1`) in the environment Claude Code starts in: the plugin then starts no CLI for these events, or for the lineage report's, and makes no install id. The CLI also drops them under its own opt-out (`ALTIMATE_TELEMETRY_DISABLED`, or `telemetry.disabled` in its config), as for every other event. - The events are sent in the background and never delay a hook. An altimate-code that predates them refuses them, and nothing is sent or shown. -- **`/savings` sends no usage event.** Typing it, pressing its buttons and opening its pane are not counted, and nothing about the check (its queries, findings or amounts) goes to Altimate. See [The Databricks savings check](#the-databricks-savings-check). +- **`/savings` sends no usage event.** Typing it, pressing its buttons and opening its pane are not counted, and nothing about the check (its queries, findings or amounts) goes to Altimate. See [The savings check](#the-savings-check). ## Data flows when a task is delegated @@ -135,9 +135,11 @@ To count installs, active use and which features are used, the plugin asks the l **Bring Your Own Key (BYOK):** if you configure your own provider (Anthropic, OpenAI, Bedrock, Azure OpenAI, Ollama, and others), your prompts go directly from your machine to that provider. Altimate is not in that delegation path; workspace service requests still go to Altimate. -## The Databricks savings check +## The savings check -`/savings` runs altimate-code's `finops_databricks_savings` tool on your machine, with your own Databricks connection. It reads usage from your workspace's system tables and decides the savings locally. The plugin runs it with telemetry turned off, in altimate-code's assessment mode (`ALTIMATE_ASSESSMENT_MODE=true`) and outside its tool daemon. In assessment mode the CLI sends no usage event, not even the one-time telemetry opt-out event, and does not fetch the model catalog or download ripgrep, so your warehouse is the only host the run contacts; an altimate-code release without assessment mode ignores the setting and would still send that opt-out event and make those fetches, so the plugin first asks `altimate --version` (which sends nothing) and does not start a release older than 0.12.12, or a source build (which prints `local` whatever its age), for the check. The plugin sends no usage event of its own for `/savings` either (see [Plugin usage events](#plugin-usage-events)), so nothing about the check, its queries or its results goes to Altimate. The findings are shown in a pane, not added to the conversation. Not assessed: Databricks Apps spend; a serverless SQL warehouse gets only the over-sized check. The run starts the connection's SQL warehouse if it is stopped, and needs the `@databricks/sql` driver installed. Costs cover the six full billed days before the window's last day, scaled to seven, which read about 7% below the seven billed days on one measured workspace. To show a flagged warehouse's observed spend before and after a later change, the plugin keeps its size, type and weekly cost in Claude Code's local plugin store on your machine. **Draft the fix** puts one finding's details in your prompt box; they reach your model provider only if you send that prompt. When Claude runs the same tool itself, its answer is a tool result like any other and reaches your model provider. +For a Databricks connection, `/savings` runs altimate-code's `finops_databricks_savings` tool on your machine, with your own connection (Snowflake: see below). It reads usage from your workspace's system tables and decides the savings locally. The plugin runs it with telemetry turned off, in altimate-code's assessment mode (`ALTIMATE_ASSESSMENT_MODE=true`) and outside its tool daemon. In assessment mode the CLI sends no usage event, not even the one-time telemetry opt-out event, and does not fetch the model catalog or download ripgrep, so your warehouse is the only host the run contacts; an altimate-code release without assessment mode ignores the setting and would still send that opt-out event and make those fetches, so the plugin first asks `altimate --version` (which sends nothing) and does not start a release older than 0.12.12, or a source build (which prints `local` whatever its age), for the check. The plugin sends no usage event of its own for `/savings` either (see [Plugin usage events](#plugin-usage-events)), so nothing about the check, its queries or its results goes to Altimate. The findings are shown in a pane, not added to the conversation. Not assessed: Databricks Apps spend; a serverless SQL warehouse gets only the over-sized check. The run starts the connection's SQL warehouse if it is stopped, and needs the `@databricks/sql` driver installed. Costs cover the six full billed days before the window's last day, scaled to seven, which read about 7% below the seven billed days on one measured workspace. To show a flagged warehouse's observed spend before and after a later change, the plugin keeps its size, type and weekly cost in Claude Code's local plugin store on your machine. **Draft the fix** puts one finding's details in your prompt box; they reach your model provider only if you send that prompt. When Claude runs the same tool itself, its answer is a tool result like any other and reaches your model provider. + +Snowflake connections are checked the same way, with altimate-code's `finops_snowflake_savings` tool. The last answer per connection is kept in that same local plugin store for 7 days (removed at the next session start after that), so the status line, the pane and a one-line note under a tool call on a flagged warehouse can show it without querying anything; **Draft the fix** also keeps the resource, its daily cost and the date there for 90 days, so a later run can say what the change did. At session start the plugin runs altimate-code's `warehouse_list` under the same switches to learn which connections exist; it reaches no warehouse. To tell which warehouse a connection runs on, the plugin reads `~/.altimate-code/connections.json` and the project's `.altimate-code/connections.json`, and for a `dbt run` or `dbt build` the dbt project and `profiles.yml`; those files hold credentials, and only `http_path`, the workspace host, `warehouse`, the Snowflake `account` and the target's type are taken from them. The host or account is kept with the answer in the local plugin store, so that an answer is shown only where the same workspace or account is connected; nothing else from those files is kept. **Share report** writes a local HTML page and opens it; nothing is uploaded. The Altimate button opens the sign-up page with nothing from your run in its address. ## Usage telemetry @@ -178,7 +180,9 @@ The plugin and the altimate-code CLI are professional developer tools, not direc We will update this document in this repository and revise the effective date when our practices change. Material changes to Altimate-wide practices are governed by the master [Privacy Policy](https://www.altimate.ai/privacy). -**November 19, 2026:** added [The Databricks savings check](#the-databricks-savings-check) (plugin 1.9.0): `/savings` runs altimate-code's savings tool with telemetry off, sends no plugin usage event, and keeps the findings out of the conversation. +**November 19, 2026:** [The savings check](#the-savings-check) now covers Snowflake, the 7-day local copy of the last answer, which local files are read to match a tool call to its warehouse, and the local report page. + +**November 19, 2026:** added [The savings check](#the-savings-check) (plugin 1.9.0): `/savings` runs altimate-code's savings tool with telemetry off, sends no plugin usage event, and keeps the findings out of the conversation. **November 19, 2026:** added [Plugin usage events](#plugin-usage-events) (plugin 1.8.2): the anonymous session start and feature-used events, and the plugin's own check of the telemetry opt-out. diff --git a/plugins/altimate-code/CHANGELOG.md b/plugins/altimate-code/CHANGELOG.md index dffc748..6bf2ffa 100644 --- a/plugins/altimate-code/CHANGELOG.md +++ b/plugins/altimate-code/CHANGELOG.md @@ -14,6 +14,13 @@ All notable changes to this plugin will be documented in this file. - A line above the prompt when the session edits Databricks bundle or Terraform files or runs a `databricks` compute command: the flagged resource's saving, or a once-a-session offer of `/savings`. - One connection checks every workspace the account's system tables show; the pane counts every workspace the CLI read (`workspaces_checked`), one with only clusters or jobs and no finding included, and names each finding's workspace. With a CLI that does not report the count, it counts the workspaces of the warehouses and findings. - `/savings` asks `altimate --version` first and does not start an altimate-code older than 0.12.12, or a source build, for the check: before assessment mode, its `tool run` would send the one-time telemetry opt-out event. +- A status-line entry: the platforms your altimate-code connections cover plus `/savings`, then the monthly range of the kept answer. The answer is kept on this machine for 7 days, and nothing runs the check but `/savings` or a button you press. +- One line under a tool call that runs on a warehouse with a kept finding: altimate-code's SQL tools by connection, `dbt run` and `dbt build` by their target. +- After a drafted fix: Draft the fix keeps the resource, its daily cost and the date; later runs say it is unchanged, `measuring (n of 7 days)`, or its observed spend a day before and after, from billing (different weeks, so never called saved). +- The pane names the hosted product's checks that did not run, with counts from your own run and one button to Altimate; Share report writes a self-contained local HTML page. +- Snowflake: with both kinds of connection, `/savings` runs `finops_snowflake_savings` too and the pane has a section for each. +- The pane opens slim on every run: the total (each resource counted once, at its largest saving), the three resources with the largest saving across both platforms with one fact each, a line for the other findings (how many, and what the resources not shown add to the total, so the lines add up to the total) and the count of checks Altimate runs beyond these. Show all opens the full detail (every finding and its evidence, what-ifs, checks not run, Run again); Share report keeps the full detail. +- A finished check raises no notice while Claude is working; it comes when the turn ends. - `runTool` takes an environment and `noDaemon` for one CLI run, and hands back a CLI's raw output when it is not an answer (an altimate-code too old for the tool gets "update"). ### Fixed diff --git a/plugins/altimate-code/README.md b/plugins/altimate-code/README.md index 4f496ec..250ccb3 100644 --- a/plugins/altimate-code/README.md +++ b/plugins/altimate-code/README.md @@ -156,17 +156,25 @@ Compile and validate runs a query on your warehouse after every model edit (`dbt When Claude mentions `altimate-dbt`, it is the dbt command line that comes with altimate-code (`npm i -g @altimateai/altimate-code`, the same install as the plugin's engine). It finds your dbt project folder, Python environment and warehouse adapter by itself, and altimate-code's agent uses it instead of the raw dbt tool for better error messages. Its commands include `init`, `doctor`, `compile`, `build`, `run`, `test`, `deps`, `columns `, `graph` (lineage) and `execute ""` (a query through the dbt adapter). You do not need to run it yourself: Claude and the altimate-code agent call it when a task needs it, and the plugin's own dbt helpers above do not depend on it. See [altimate-dbt in the altimate-code docs](https://docs.altimate.sh/data-engineering/tools/dbt-tools/#altimate-dbt-cli). -## Databricks savings check +## Warehouse savings check -`/savings [connection]` checks a Databricks workspace for savings with four of Altimate's Databricks checks: Classic or Pro SQL warehouses that would cost less as serverless, warehouses larger than their queries need, idle all-purpose clusters, and scheduled or continuous jobs running on all-purpose clusters. A pane beside the chat shows each finding with what it rests on and a monthly range at list price, each resource counted once at its largest saving. +`/savings [connection]` checks your Databricks and Snowflake connections for savings, each with four of the checks Altimate's hosted product runs. On Databricks: Classic or Pro SQL warehouses that would cost less as serverless, warehouses larger than their queries need, idle all-purpose clusters, and scheduled or continuous jobs running on all-purpose clusters. On Snowflake: high idle time, warehouses that could be downsized, underutilized clusters and frequent restarts. With both kinds of connection, one `/savings` checks both. A pane beside the chat shows each finding with what it rests on and a monthly range (at list price, or at your Snowflake account's own credit price when the check can read it), each resource counted once at its largest saving. +- **Slim first.** Each run opens the pane slim: one header for every connection checked, the total (each resource counted once, at its largest saving), and the three resources with the largest saving across both platforms (by the high end of their monthly range), each on one line at its largest finding, with the one measured fact you can check in your own console and its Draft the fix button. Below them, how many other findings there are and what the resources not shown add to the total, so the three amounts shown plus that line make the total; then how many more checks Altimate runs on these platforms, Share report and Close. A drafted fix's line stays under its finding, or shows on its own once its finding has cleared. **Show all** opens the full detail, a section per platform: every finding with all its evidence, the what-ifs, the checks that did not run and Run again; **Show fewer** goes back. Every run, refused or not, and every new session open slim again. The Share report page always has the full detail. + +- **It runs only when you ask.** A run queries your warehouse and can start a stopped one, which costs you money. So nothing here runs the check by itself: the status line, the notes under tool calls and the pane all read the last answer, kept on this machine for 7 days (`$.store`) or until you run `/savings` for that connection again. An answer shows only where its connection reaches the same workspace or account, so one project's results do not appear in another's. +- **Status line.** At session start the plugin asks altimate-code which connections you have (`warehouse_list`, which reads its config and reaches no warehouse) and shows the platforms plus `/savings`. After a run it shows the monthly range, with the age of the answer once it is a day old. +- **A note under the tool call.** When a tool call runs on a warehouse with a kept finding, one quiet line under its row gives the warehouse, the strongest fact and the monthly range. That covers altimate-code's `sql_execute` and `sql_explain` (over MCP or `altimate tool run`), by the connection they name, and `dbt run` / `dbt build`, by the target in `profiles.yml` (on Snowflake, only when the connection names its account). To know which warehouse a connection runs on, the plugin reads `connections.json` for Databricks' `http_path` and workspace host and Snowflake's `warehouse` and `account`. It uses nothing else from that file, and keeps only the host or account, beside the answer, so the answer appears only where the same workspace or account is connected. A connection set only through an `ALTIMATE_CODE_CONN_*` variable has none of this, so its notes rely on the warehouse its own run went through. A `dbt` line that follows a `cd` in an earlier command is read against the session's project. - **Draft the fix.** Each finding has a button that puts the change in your prompt box (serverless, a smaller `cluster_size`, auto-termination, or a job cluster) for Claude to draft against your bundle or Terraform, or as CLI JSON. Nothing is sent until you press Enter, and nothing is applied. -- **What if.** For each flagged warehouse, press serverless or any smaller size to see what it would cost a month and whether its cores still cover what its queries need. +- **After a drafted fix.** Draft the fix keeps the resource, what it cost a day and the date. A later `/savings` says one of: `measuring (n of 7 days)`, with no change seen yet or with one seen; nothing changed over a whole window, so no saving is claimed; or, once a whole window has passed since the change was seen, its observed spend a day before and after, from billing. The two amounts come from different weeks, so a quieter or busier week moves them too: the pane shows what was billed and never calls the difference saved. A draft changes nothing and the plugin cannot see when a change lands, so days are counted from the first run that saw a new size or type. A fix that changes neither (auto-suspend, a cluster maximum) gets no saving: when its finding clears, the pane gives the cost before and after and says it cannot tell whether your change did that. Clusters and jobs say whether they are still flagged, since their cost afterwards is not in the answer. - **Spend since a change.** The first run that flags a warehouse remembers its size, type and cost on this machine (`$.store`), all from that run. A later run that finds the size or type changed shows its observed spend a month before and after the change, and names only the settings read both times. A setting the CLI did not list then is taken from the first later run that reads every setting the baseline knew, finds none changed and gives a cost: that run's read, date and spend replace the first run's, so the comparison starts from it. The two amounts come from different weeks, so a quieter or busier week moves them too: they are what was billed, not a measured saving. +- **What if.** For each flagged warehouse, press serverless or any smaller size to see what it would cost a month and whether its cores still cover what its queries need. +- **Checks that did not run.** The pane names the hosted product's other checks for that platform, each with a count from your own run of what it would look at, and one button opens Altimate's sign-up page. The address carries nothing from your run. +- **Share report.** Writes the findings, evidence, what-ifs and checks not run to one self-contained HTML page (`target/.altimate-lineage/savings-report.html` in a dbt project, else `~/.altimate-code/savings-report.html`) and opens it. Nothing is uploaded; it stays on your machine until you send it. - **At the right moment.** Editing a bundle's `databricks.yml`, a YAML file under `resources/` whose top-level `resources:` block lists jobs, pipelines, clusters or SQL warehouses, or a Terraform file with a line that starts with a `databricks` provider, resource or data source, or running a `databricks` warehouses, clusters, bundle or jobs command, shows a line above the prompt: the flagged resource's saving when the file names it, else, when the file mentions warehouses or clusters (a command always counts), a once-a-session offer of `/savings`. Nothing runs by itself. -- **What runs.** altimate-code's `finops_databricks_savings` tool, with your own altimate-code Databricks connection (the first one that runs through a SQL warehouse, or the one named). It reads seven days of Databricks system tables (`system.billing`, `system.compute`, `system.query`, `system.lakeflow`) on that SQL warehouse, which Databricks starts if it is stopped and bills while it runs, so it runs only when you type `/savings` (or press its Run button), never on its own; the check stops after 9 minutes, cancelling any query still running. System tables cover every workspace of the account they can see, so one connection checks all of them, and the pane names each finding's workspace. A check that could not run (its tables could not be read, or the time ran out) is named as not checked, with the reason; the others still report. -- **What it needs.** altimate-code 0.12.12 or later, which has that tool and assessment mode, and a Databricks connection whose `http_path` is a SQL warehouse (`/sql/1.0/warehouses/`) with an access token that can read those system tables. -- **What leaves your machine.** The plugin first asks `altimate --version`, which starts no telemetry, and does not start an older altimate-code, or a source build (which prints `local` whatever its age), for the check. It then runs the tool with `ALTIMATE_TELEMETRY_DISABLED=true`, `ALTIMATE_ASSESSMENT_MODE=true` and `--no-daemon`, so neither altimate-code nor altimate-core sends usage telemetry for it. `/savings` sends no plugin usage event either: typing it and opening its pane are not counted, and the check's queries and results never go to Altimate. The findings stay in the pane until you send a Draft the fix request. Claude can also run the same tool itself; its answer then reaches your model provider like any other tool result. +- **What runs.** altimate-code's `finops_databricks_savings` and `finops_snowflake_savings` tools, with your own connection (the first of each platform, or the one named). The Databricks check reads seven days of system tables (`system.billing`, `system.compute`, `system.query`, `system.lakeflow`) on that SQL warehouse, which Databricks starts if it is stopped and bills while it runs, so it runs only when you type `/savings` or press a button for it. System tables cover every workspace of the account they can see, so one connection checks all of them, and Show all names each finding's workspace. A check whose tables the connection cannot read is named as not checked; the others still report. +- **What it needs.** altimate-code 0.12.12 or later, which has the Databricks tool and assessment mode, and a Databricks connection whose `http_path` is a SQL warehouse (`/sql/1.0/warehouses/`) with an access token that can read those system tables. Snowflake needs an altimate-code that has `finops_snowflake_savings`; an older one is told to update while the Databricks section still shows. +- **What leaves your machine.** The plugin first asks `altimate --version`, which starts no telemetry, and does not start an older altimate-code, or a source build (which prints `local` whatever its age), for the check or for listing connections. It then runs them with `ALTIMATE_TELEMETRY_DISABLED=true`, `ALTIMATE_ASSESSMENT_MODE=true` and `--no-daemon`, so neither altimate-code nor altimate-core sends usage telemetry for them. `/savings` sends no plugin usage event either: typing it, its buttons and opening its pane are not counted, and the check's queries and results never go to Altimate. The findings stay in the pane until you send a Draft the fix request. Claude can also run the same tool itself; its answer then reaches your model provider like any other tool result. ## Settings diff --git a/plugins/altimate-code/hooks/features/defer.tsx b/plugins/altimate-code/hooks/features/defer.tsx index 888485b..542ccce 100644 --- a/plugins/altimate-code/hooks/features/defer.tsx +++ b/plugins/altimate-code/hooks/features/defer.tsx @@ -109,7 +109,7 @@ type DeferAnswer = { const dirname = (path: string) => path.replace(/[\\/]+[^\\/]*$/, '') || '/' /** The dbt project the session works in: the folder or one above it with a dbt_project.yml, else the only one a level below. */ -async function findProject($: EngineInterface): Promise { +export async function findProject($: EngineInterface): Promise { // A call that throws at once (an engine without a session) is no project either. const root = await Promise.resolve().then(() => $.session.root()).catch(() => null) if (!root) return null diff --git a/plugins/altimate-code/hooks/features/index.test.ts b/plugins/altimate-code/hooks/features/index.test.ts index 94c6e7e..3c860bc 100644 --- a/plugins/altimate-code/hooks/features/index.test.ts +++ b/plugins/altimate-code/hooks/features/index.test.ts @@ -32,7 +32,8 @@ const engine = () => { process: { run: async (argv: readonly string[]) => nothingToReport(argv) ?? { exitCode: 1, stdout: '', stderr: 'no CLI here' } }, clock: { now: async () => 0, after: () => {}, every: () => {}, sleep: async () => {} }, session: { root: async () => '/repo', cwd: async () => '/repo' }, - store: { get: async () => null, set: async () => {} }, + store: { get: async () => null, set: async () => {}, keys: async () => [], delete: async () => {} }, + env: { get: async () => undefined }, mcp: { connect: async () => ({ isConnected: false, reason: 'not_connected', message: 'off' }) }, } return { logs, $: $ as any } diff --git a/plugins/altimate-code/hooks/features/savings-core.testkit.ts b/plugins/altimate-code/hooks/features/savings-core.testkit.ts index d648cb6..acab866 100644 --- a/plugins/altimate-code/hooks/features/savings-core.testkit.ts +++ b/plugins/altimate-code/hooks/features/savings-core.testkit.ts @@ -1,7 +1,8 @@ -// For tests: what core's savings rules return, captured from core's compiled binding (`databricksSavings`) -// called with the synthetic facts below. It has every finding kind Databricks has, a cluster with no -// auto-termination setting and a warehouse with no size (core sends null for both), and what-if rows for one -// warehouse id in two workspaces. Regenerate by passing the facts, as JSON, to the binding the CLI ships. +// For tests: what core's savings rules return, captured from core's compiled binding (`databricksSavings` and +// `snowflakeSavings`) called with the synthetic facts below. It has every finding kind each platform has, +// Snowflake's Underutilized Cluster among them with no dollar estimate; a cluster with no auto-termination +// setting and a warehouse with no size (core sends null for both); and what-if rows for one warehouse id in +// two workspaces. Regenerate by passing the facts, as JSON, to the binding the CLI ships. /** The `DatabricksSavingsInput` core was given. */ export const DATABRICKS_FACTS = { @@ -555,3 +556,462 @@ export const DATABRICKS_REPORT = { } ] } as const + +/** The `SnowflakeSavingsInput` core was given. */ +export const SNOWFLAKE_FACTS = { + "lookback_days": 7, + "price_per_credit": 3, + "warehouses": [ + { + "warehouse_id": "sf-synth-idle", + "warehouse_name": "SYNTH_IDLE", + "warehouse_size": "Medium", + "warehouse_type": "STANDARD", + "min_cluster_count": 1, + "max_cluster_count": 1, + "query_count": 500, + "sub_five_second_queries": 480, + "sub_five_second_credits": 30, + "usage_days": [ + { + "day": "2026-11-10", + "credits_used": 40, + "active_periods": 10, + "short_periods": 1 + }, + { + "day": "2026-11-11", + "credits_used": 40, + "active_periods": 10, + "short_periods": 1 + }, + { + "day": "2026-11-12", + "credits_used": 40, + "active_periods": 10, + "short_periods": 1 + }, + { + "day": "2026-11-13", + "credits_used": 40, + "active_periods": 10, + "short_periods": 1 + }, + { + "day": "2026-11-14", + "credits_used": 40, + "active_periods": 10, + "short_periods": 1 + }, + { + "day": "2026-11-15", + "credits_used": 40, + "active_periods": 10, + "short_periods": 1 + }, + { + "day": "2026-11-16", + "credits_used": 40, + "active_periods": 10, + "short_periods": 1 + } + ], + "idle_days": [ + { + "day": "2026-11-10", + "active_seconds": 33000, + "idle_seconds": 30000, + "credits_used": 40 + }, + { + "day": "2026-11-11", + "active_seconds": 33000, + "idle_seconds": 30000, + "credits_used": 40 + }, + { + "day": "2026-11-12", + "active_seconds": 33000, + "idle_seconds": 30000, + "credits_used": 40 + }, + { + "day": "2026-11-13", + "active_seconds": 33000, + "idle_seconds": 30000, + "credits_used": 40 + }, + { + "day": "2026-11-14", + "active_seconds": 33000, + "idle_seconds": 30000, + "credits_used": 40 + }, + { + "day": "2026-11-15", + "active_seconds": 33000, + "idle_seconds": 30000, + "credits_used": 40 + }, + { + "day": "2026-11-16", + "active_seconds": 33000, + "idle_seconds": 30000, + "credits_used": 40 + } + ] + }, + { + "warehouse_id": "sf-synth-multi", + "warehouse_name": "SYNTH_MULTI", + "warehouse_size": "Large", + "warehouse_type": "STANDARD", + "min_cluster_count": 1, + "max_cluster_count": 2, + "query_count": 4000, + "sub_five_second_queries": 100, + "sub_five_second_credits": 5, + "usage_days": [ + { + "day": "2026-11-10", + "credits_used": 60, + "active_periods": 40, + "short_periods": 30 + }, + { + "day": "2026-11-11", + "credits_used": 60, + "active_periods": 40, + "short_periods": 30 + }, + { + "day": "2026-11-12", + "credits_used": 60, + "active_periods": 40, + "short_periods": 30 + }, + { + "day": "2026-11-13", + "credits_used": 60, + "active_periods": 40, + "short_periods": 30 + }, + { + "day": "2026-11-14", + "credits_used": 60, + "active_periods": 40, + "short_periods": 30 + }, + { + "day": "2026-11-15", + "credits_used": 60, + "active_periods": 40, + "short_periods": 30 + }, + { + "day": "2026-11-16", + "credits_used": 60, + "active_periods": 40, + "short_periods": 30 + } + ], + "cluster_days": [ + { + "day": "2026-11-10", + "clusters": [ + { + "cluster_number": 1, + "idle_seconds": 100, + "busy_seconds": 30000 + }, + { + "cluster_number": 2, + "idle_seconds": 200, + "busy_seconds": 50 + } + ] + }, + { + "day": "2026-11-11", + "clusters": [ + { + "cluster_number": 1, + "idle_seconds": 100, + "busy_seconds": 30000 + }, + { + "cluster_number": 2, + "idle_seconds": 200, + "busy_seconds": 50 + } + ] + }, + { + "day": "2026-11-12", + "clusters": [ + { + "cluster_number": 1, + "idle_seconds": 100, + "busy_seconds": 30000 + }, + { + "cluster_number": 2, + "idle_seconds": 200, + "busy_seconds": 50 + } + ] + }, + { + "day": "2026-11-13", + "clusters": [ + { + "cluster_number": 1, + "idle_seconds": 100, + "busy_seconds": 30000 + }, + { + "cluster_number": 2, + "idle_seconds": 200, + "busy_seconds": 50 + } + ] + }, + { + "day": "2026-11-14", + "clusters": [ + { + "cluster_number": 1, + "idle_seconds": 100, + "busy_seconds": 30000 + }, + { + "cluster_number": 2, + "idle_seconds": 200, + "busy_seconds": 50 + } + ] + }, + { + "day": "2026-11-15", + "clusters": [ + { + "cluster_number": 1, + "idle_seconds": 100, + "busy_seconds": 30000 + }, + { + "cluster_number": 2, + "idle_seconds": 200, + "busy_seconds": 50 + } + ] + }, + { + "day": "2026-11-16", + "clusters": [ + { + "cluster_number": 1, + "idle_seconds": 100, + "busy_seconds": 30000 + }, + { + "cluster_number": 2, + "idle_seconds": 200, + "busy_seconds": 50 + } + ] + } + ], + "restart_days": [ + { + "day": "2026-11-10", + "gaps": [ + { + "gap_seconds": 20, + "bounces": 40 + } + ] + }, + { + "day": "2026-11-11", + "gaps": [ + { + "gap_seconds": 20, + "bounces": 40 + } + ] + }, + { + "day": "2026-11-12", + "gaps": [ + { + "gap_seconds": 20, + "bounces": 40 + } + ] + }, + { + "day": "2026-11-13", + "gaps": [ + { + "gap_seconds": 20, + "bounces": 40 + } + ] + }, + { + "day": "2026-11-14", + "gaps": [ + { + "gap_seconds": 20, + "bounces": 40 + } + ] + }, + { + "day": "2026-11-15", + "gaps": [ + { + "gap_seconds": 20, + "bounces": 40 + } + ] + }, + { + "day": "2026-11-16", + "gaps": [ + { + "gap_seconds": 20, + "bounces": 40 + } + ] + } + ] + } + ] +} as const + +/** Core's `SnowflakeSavingsReport` for those facts. */ +export const SNOWFLAKE_REPORT = { + "findings": [ + { + "check_id": "high_idle_time", + "daily_max": 109.09090909090911, + "daily_min": 76.36363636363637, + "evidence": { + "active_seconds": 231000, + "credits_used": 280, + "flagged_days": [ + "2026-11-10", + "2026-11-11", + "2026-11-12", + "2026-11-13", + "2026-11-14", + "2026-11-15", + "2026-11-16" + ], + "idle_ratio": 0.9090909090909091, + "idle_seconds": 210000, + "kind": "high_idle_time", + "price_per_credit": 3, + "wasted_cost": 763.6363636363637 + }, + "monthly_max": 3272.7272727272734, + "monthly_min": 2290.909090909091, + "resource_id": "sf-synth-idle", + "resource_name": "SYNTH_IDLE", + "resource_type": "sql_warehouse", + "severity": "critical", + "title": "High Idle Time", + "workspace_id": null + }, + { + "check_id": "frequent_restart_overcharge", + "daily_max": 16, + "daily_min": 10.67, + "evidence": { + "bounces": 280, + "credits_per_hour": 8, + "double_billed_seconds": 11200, + "flagged_days": [ + "2026-11-10", + "2026-11-11", + "2026-11-12", + "2026-11-13", + "2026-11-14", + "2026-11-15", + "2026-11-16" + ], + "kind": "frequent_restart", + "price_per_credit": 3 + }, + "monthly_max": 480, + "monthly_min": 320.1, + "resource_id": "sf-synth-multi", + "resource_name": "SYNTH_MULTI", + "resource_type": "sql_warehouse", + "severity": "low", + "title": "Frequent Restart Overcharge", + "workspace_id": null + }, + { + "check_id": "downsize_warehouse", + "daily_max": 6.428571428571429, + "daily_min": 3.857142857142857, + "evidence": { + "cost_basis": 90, + "current_size": "Medium", + "kind": "downsize_warehouse", + "price_per_credit": 3, + "query_count": 500, + "recommended_size": "Small", + "short_period_percent": null, + "sub_five_second_percent": 96 + }, + "monthly_max": 192.85714285714286, + "monthly_min": 115.71428571428572, + "resource_id": "sf-synth-idle", + "resource_name": "SYNTH_IDLE", + "resource_type": "sql_warehouse", + "severity": "medium", + "title": "Downsize Warehouse", + "workspace_id": null + }, + { + "check_id": "underutilized_cluster", + "daily_max": 0, + "daily_min": 0, + "evidence": { + "flagged_days": [ + "2026-11-10", + "2026-11-11", + "2026-11-12", + "2026-11-13", + "2026-11-14", + "2026-11-15", + "2026-11-16" + ], + "highest_idle_percent": 80, + "kind": "underutilized_cluster", + "max_cluster_count": 2, + "recommended_max_cluster_count": 1 + }, + "monthly_max": 0, + "monthly_min": 0, + "resource_id": "sf-synth-multi", + "resource_name": "SYNTH_MULTI", + "resource_type": "sql_warehouse", + "severity": "low", + "title": "Underutilized Cluster", + "workspace_id": null + } + ], + "lookback_days": 7, + "price_per_credit": 3, + "total": { + "monthly_max": 3752.7272727272734, + "monthly_min": 2611.009090909091, + "resources": 2 + }, + "what_if": [] +} as const diff --git a/plugins/altimate-code/hooks/features/savings-snowflake-capture.test-data.ts b/plugins/altimate-code/hooks/features/savings-snowflake-capture.test-data.ts new file mode 100644 index 0000000..d44fc04 --- /dev/null +++ b/plugins/altimate-code/hooks/features/savings-snowflake-capture.test-data.ts @@ -0,0 +1,780 @@ +// What `altimate tool run finops_snowflake_savings --json` answered on Altimate's own Snowflake account, for +// the seven days to 2026-11-18, with warehouse names that could identify people or projects replaced and +// the tool's text output shortened. The tests read it so the pane is held to the tool's real answer. +export const SNOWFLAKE_CAPTURE = { + "status": "ok", + "title": "Snowflake Savings: $342–$489 a month on 7 warehouses", + "output": "Snowflake savings: 69 warehouses checked", + "metadata": { + "success": true, + "window": { + "start": "2026-11-11", + "end": "2026-11-18" + }, + "warehouse": "snowflake", + "ran_on": "ALTIMATE_WH", + "warehouses_checked": 69, + "price": { + "per_credit": 3, + "source": "rate_sheet", + "as_of": "2026-08-05" + }, + "skipped": [], + "limited": [], + "warehouses": [ + { + "id": "6163", + "name": "ALTIMATE_METRICS_WH", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0.48906166500000003 + }, + { + "id": "107", + "name": "ALTIMATE_WH", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0.0024208350000000005 + }, + { + "id": "1", + "name": "COMPUTE_WH", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 12.519939225000002 + }, + { + "id": "3003", + "name": "DBT_INTEGRATION_TEST_WH", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 72.86214285300001 + }, + { + "id": "2863", + "name": "NATIVE_APP_WH", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 45.75015684899999 + }, + { + "id": "2240", + "name": "SA_WH", + "type": "STANDARD", + "size": "Medium", + "window_cost": 18.763462368000003 + }, + { + "id": "6223", + "name": "TELEMETRY_DASHBOARD_WH", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 1.551656667 + }, + { + "id": "2323", + "name": "TEST_WH_A", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0.070725 + }, + { + "id": "WAREHOUSE_01", + "name": "WAREHOUSE_01", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_02", + "name": "WAREHOUSE_02", + "type": "STANDARD", + "size": "Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_03", + "name": "WAREHOUSE_03", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_04", + "name": "WAREHOUSE_04", + "type": "STANDARD", + "size": "Large", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_05", + "name": "WAREHOUSE_05", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_06", + "name": "WAREHOUSE_06", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_07", + "name": "WAREHOUSE_07", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_08", + "name": "WAREHOUSE_08", + "type": "STANDARD", + "size": "Medium", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_09", + "name": "WAREHOUSE_09", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_10", + "name": "WAREHOUSE_10", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_11", + "name": "WAREHOUSE_11", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_12", + "name": "WAREHOUSE_12", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_13", + "name": "WAREHOUSE_13", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_14", + "name": "WAREHOUSE_14", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_15", + "name": "WAREHOUSE_15", + "type": "STANDARD", + "size": "Medium", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_16", + "name": "WAREHOUSE_16", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_17", + "name": "WAREHOUSE_17", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_18", + "name": "WAREHOUSE_18", + "type": "STANDARD", + "size": "X-Large", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_19", + "name": "WAREHOUSE_19", + "type": "STANDARD", + "size": "Large", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_20", + "name": "WAREHOUSE_20", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_21", + "name": "WAREHOUSE_21", + "type": "STANDARD", + "size": "Large", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_22", + "name": "WAREHOUSE_22", + "type": "STANDARD", + "size": "Medium", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_23", + "name": "WAREHOUSE_23", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_24", + "name": "WAREHOUSE_24", + "type": "STANDARD", + "size": "Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_25", + "name": "WAREHOUSE_25", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_26", + "name": "WAREHOUSE_26", + "type": "STANDARD", + "size": "Medium", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_27", + "name": "WAREHOUSE_27", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_28", + "name": "WAREHOUSE_28", + "type": "STANDARD", + "size": "Medium", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_29", + "name": "WAREHOUSE_29", + "type": "STANDARD", + "size": "Medium", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_30", + "name": "WAREHOUSE_30", + "type": "STANDARD", + "size": "Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_31", + "name": "WAREHOUSE_31", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_32", + "name": "WAREHOUSE_32", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_33", + "name": "WAREHOUSE_33", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_34", + "name": "WAREHOUSE_34", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_35", + "name": "WAREHOUSE_35", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_36", + "name": "WAREHOUSE_36", + "type": "STANDARD", + "size": "Medium", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_37", + "name": "WAREHOUSE_37", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_38", + "name": "WAREHOUSE_38", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_39", + "name": "WAREHOUSE_39", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_40", + "name": "WAREHOUSE_40", + "type": "STANDARD", + "size": "X-Large", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_41", + "name": "WAREHOUSE_41", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_42", + "name": "WAREHOUSE_42", + "type": "STANDARD", + "size": "Medium", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_43", + "name": "WAREHOUSE_43", + "type": "STANDARD", + "size": "Medium", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_44", + "name": "WAREHOUSE_44", + "type": "STANDARD", + "size": "Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_45", + "name": "WAREHOUSE_45", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_46", + "name": "WAREHOUSE_46", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_47", + "name": "WAREHOUSE_47", + "type": "STANDARD", + "size": "Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_48", + "name": "WAREHOUSE_48", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_49", + "name": "WAREHOUSE_49", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_50", + "name": "WAREHOUSE_50", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_51", + "name": "WAREHOUSE_51", + "type": "STANDARD", + "size": "Large", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_52", + "name": "WAREHOUSE_52", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_53", + "name": "WAREHOUSE_53", + "type": "STANDARD", + "size": "Medium", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_54", + "name": "WAREHOUSE_54", + "type": "STANDARD", + "size": "Medium", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_55", + "name": "WAREHOUSE_55", + "type": "STANDARD", + "size": "Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_56", + "name": "WAREHOUSE_56", + "type": "STANDARD", + "size": "Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_57", + "name": "WAREHOUSE_57", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_58", + "name": "WAREHOUSE_58", + "type": "STANDARD", + "size": "X-Small", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_59", + "name": "WAREHOUSE_59", + "type": "STANDARD", + "size": "X-Large", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_60", + "name": "WAREHOUSE_60", + "type": "STANDARD", + "size": "X-Large", + "window_cost": 0 + }, + { + "id": "WAREHOUSE_61", + "name": "WAREHOUSE_61", + "type": "STANDARD", + "size": "X-Large", + "window_cost": 0 + } + ], + "report": { + "findings": [ + { + "check_id": "high_idle_time", + "daily_max": 9.378225778643243, + "daily_min": 6.56475804505027, + "evidence": { + "active_seconds": 48628, + "credits_used": 24.287380951000003, + "flagged_days": [ + "2026-11-11", + "2026-11-12", + "2026-11-13", + "2026-11-16", + "2026-11-17" + ], + "idle_ratio": 0.9009624084889364, + "idle_seconds": 43812, + "kind": "high_idle_time", + "price_per_credit": 3, + "wasted_cost": 65.6475804505027 + }, + "monthly_max": 281.3467733592973, + "monthly_min": 196.9427413515081, + "resource_id": "3003", + "resource_name": "DBT_INTEGRATION_TEST_WH", + "resource_type": "sql_warehouse", + "severity": "critical", + "title": "High Idle Time", + "workspace_id": null + }, + { + "check_id": "high_idle_time", + "daily_max": 4.294229484507595, + "daily_min": 3.005960639155316, + "evidence": { + "active_seconds": 26807, + "credits_used": 15.294370331999998, + "flagged_days": [ + "2026-11-11", + "2026-11-12", + "2026-11-13", + "2026-11-14", + "2026-11-15", + "2026-11-16", + "2026-11-17" + ], + "idle_ratio": 0.6562465027791249, + "idle_seconds": 17592, + "kind": "high_idle_time", + "price_per_credit": 3, + "wasted_cost": 30.05960639155316 + }, + "monthly_max": 128.82688453522783, + "monthly_min": 90.17881917465948, + "resource_id": "2863", + "resource_name": "NATIVE_APP_WH", + "resource_type": "sql_warehouse", + "severity": "high", + "title": "High Idle Time", + "workspace_id": null + }, + { + "check_id": "high_idle_time", + "daily_max": 1.3474941117907626, + "daily_min": 0.9432458782535338, + "evidence": { + "active_seconds": 4787, + "credits_used": 6.327360788, + "flagged_days": [ + "2026-11-11", + "2026-11-12", + "2026-11-13", + "2026-11-14", + "2026-11-15", + "2026-11-16", + "2026-11-17" + ], + "idle_ratio": 0.4973887612283267, + "idle_seconds": 2381, + "kind": "high_idle_time", + "price_per_credit": 3, + "wasted_cost": 9.432458782535338 + }, + "monthly_max": 40.42482335372288, + "monthly_min": 28.297376347606015, + "resource_id": "2240", + "resource_name": "SA_WH", + "resource_type": "sql_warehouse", + "severity": "medium", + "title": "High Idle Time", + "workspace_id": null + }, + { + "check_id": "high_idle_time", + "daily_max": 1.014339786828464, + "daily_min": 0.7100378507799248, + "evidence": { + "active_seconds": 4521, + "credits_used": 4.178750297, + "flagged_days": [ + "2026-11-11", + "2026-11-12", + "2026-11-13", + "2026-11-14", + "2026-11-15", + "2026-11-16", + "2026-11-17" + ], + "idle_ratio": 0.5857111258571113, + "idle_seconds": 2648, + "kind": "high_idle_time", + "price_per_credit": 3, + "wasted_cost": 7.100378507799249 + }, + "monthly_max": 30.430193604853923, + "monthly_min": 21.301135523397743, + "resource_id": "1", + "resource_name": "COMPUTE_WH", + "resource_type": "sql_warehouse", + "severity": "medium", + "title": "High Idle Time", + "workspace_id": null + }, + { + "check_id": "frequent_restart_overcharge", + "daily_max": 0.4385714285714286, + "daily_min": 0.2928571428571428, + "evidence": { + "bounces": 180, + "credits_per_hour": 1, + "double_billed_seconds": 2456, + "flagged_days": [ + "2026-11-11", + "2026-11-12", + "2026-11-13", + "2026-11-16", + "2026-11-17" + ], + "kind": "frequent_restart", + "price_per_credit": 3 + }, + "monthly_max": 13.157142857142858, + "monthly_min": 8.785714285714285, + "resource_id": "3003", + "resource_name": "DBT_INTEGRATION_TEST_WH", + "resource_type": "sql_warehouse", + "severity": "low", + "title": "Frequent Restart Overcharge", + "workspace_id": null + }, + { + "check_id": "high_idle_time", + "daily_max": 0.18161862307328921, + "daily_min": 0.12713303615130245, + "evidence": { + "active_seconds": 1185, + "credits_used": 0.450380554, + "flagged_days": [ + "2026-11-11", + "2026-11-12", + "2026-11-13", + "2026-11-14", + "2026-11-17" + ], + "idle_ratio": 0.9409282700421941, + "idle_seconds": 1115, + "kind": "high_idle_time", + "price_per_credit": 3, + "wasted_cost": 1.2713303615130245 + }, + "monthly_max": 5.448558692198676, + "monthly_min": 3.813991084539073, + "resource_id": "6223", + "resource_name": "TELEMETRY_DASHBOARD_WH", + "resource_type": "sql_warehouse", + "severity": "critical", + "title": "High Idle Time", + "workspace_id": null + }, + { + "check_id": "downsize_warehouse", + "daily_max": 0.1646368156714286, + "daily_min": 0.09878208940285715, + "evidence": { + "cost_basis": 2.3049154194000003, + "current_size": "Medium", + "kind": "downsize_warehouse", + "price_per_credit": 3, + "query_count": 2001, + "recommended_size": "Small", + "short_period_percent": null, + "sub_five_second_percent": 96.45177411294353 + }, + "monthly_max": 4.939104470142858, + "monthly_min": 2.963462682085715, + "resource_id": "2240", + "resource_name": "SA_WH", + "resource_type": "sql_warehouse", + "severity": "medium", + "title": "Downsize Warehouse", + "workspace_id": null + }, + { + "check_id": "high_idle_time", + "daily_max": 0.0685693842281775, + "daily_min": 0.04799856895972425, + "evidence": { + "active_seconds": 431, + "credits_used": 0.163020555, + "flagged_days": [ + "2026-11-11", + "2026-11-12", + "2026-11-13", + "2026-11-14", + "2026-11-15", + "2026-11-16", + "2026-11-17" + ], + "idle_ratio": 0.9814385150812065, + "idle_seconds": 423, + "kind": "high_idle_time", + "price_per_credit": 3, + "wasted_cost": 0.4799856895972425 + }, + "monthly_max": 2.057081526845325, + "monthly_min": 1.4399570687917276, + "resource_id": "6163", + "resource_name": "ALTIMATE_METRICS_WH", + "resource_type": "sql_warehouse", + "severity": "critical", + "title": "High Idle Time", + "workspace_id": null + }, + { + "check_id": "high_idle_time", + "daily_max": 0.009907259859484777, + "daily_min": 0.006935081901639343, + "evidence": { + "active_seconds": 61, + "credits_used": 0.023502222, + "flagged_days": [ + "2026-11-12" + ], + "idle_ratio": 0.9836065573770492, + "idle_seconds": 60, + "kind": "high_idle_time", + "price_per_credit": 3, + "wasted_cost": 0.06935081901639344 + }, + "monthly_max": 0.2972177957845433, + "monthly_min": 0.2080524570491803, + "resource_id": "2323", + "resource_name": "TEST_WH_A", + "resource_type": "sql_warehouse", + "severity": "critical", + "title": "High Idle Time", + "workspace_id": null + } + ], + "lookback_days": 7, + "price_per_credit": 3, + "total": { + "monthly_max": 488.83153286793043, + "monthly_min": 342.1820730075513, + "resources": 7 + }, + "what_if": [] + }, + "truncated": false + } +} diff --git a/plugins/altimate-code/hooks/features/savings.test.tsx b/plugins/altimate-code/hooks/features/savings.test.tsx index b3bef4f..b5ed233 100644 --- a/plugins/altimate-code/hooks/features/savings.test.tsx +++ b/plugins/altimate-code/hooks/features/savings.test.tsx @@ -1,7 +1,9 @@ import { expect, mock, test } from 'claude-code/testing' -import { SAVINGS_MIN_ALTIMATE_CODE, SIGNUP_URL, apiSize, checksNotRun, compared, dollars, errorText, evidenceLines, explain, fixRequest, isDatabricksConfig, mentions, runsDatabricksCompute, supportsSavings, toView as toViewOf } from './savings' -import { DATABRICKS_FACTS, DATABRICKS_REPORT } from './savings-core.testkit' +import { SNOWFLAKE_CAPTURE } from './savings-snowflake-capture.test-data' +import { skippedChecks } from '../savings-checks' +import { SAVINGS_MIN_ALTIMATE_CODE, SIGNUP_URL, SLIM_WIDTH, apiSize, compared, dollars, errorText, evidenceLines, explain, fitLine, fixRequest, isDatabricksConfig, mentions, runsDatabricksCompute, slimTitle, statusText, supportsSavings, toView } from './savings' +import { DATABRICKS_FACTS, DATABRICKS_REPORT, SNOWFLAKE_FACTS, SNOWFLAKE_REPORT } from './savings-core.testkit' const ROOT = '/repo' @@ -166,6 +168,55 @@ const ANSWER = { }, } +// `finops_snowflake_savings`'s answer, in the shape of that tool's own test report: a warehouse id that is +// a number, evidence of its four kinds, a rate-sheet price, and a finding with no dollar estimate. +const snowflakeFinding = (check_id: string, title: string, evidence: Record, monthly_min: number, monthly_max: number) => ({ + check_id, + title, + resource_type: 'sql_warehouse', + resource_id: '7', + resource_name: 'BI_WH', + workspace_id: null, + severity: 'medium', + daily_min: monthly_min / 30, + daily_max: monthly_max / 30, + monthly_min, + monthly_max, + evidence, +}) +const SNOWFLAKE_ANSWER = { + status: 'ok', + title: 'Snowflake Savings: $54.00–$90.00 a month on 1 warehouse', + output: 'Snowflake savings: 3 warehouses checked', + metadata: { + success: true, + window: { start: '2026-11-11', end: '2026-11-18' }, + warehouse: 'sfmega', + ran_on: 'BI_WH', + warehouses_checked: 3, + price: { per_credit: 3, source: 'rate_sheet', as_of: '2026-11-17' }, + skipped: [], + limited: [], + warehouses: [ + { id: '7', name: 'BI_WH', type: 'STANDARD', size: 'Large', window_cost: 42 }, + { id: '8', name: 'ETL_WH', type: 'STANDARD', size: 'Small', window_cost: 12 }, + { id: '9', name: 'OLD_WH', type: 'STANDARD', size: 'Small', window_cost: 0 }, + ], + report: { + lookback_days: 7, + price_per_credit: 3, + findings: [ + snowflakeFinding('downsize_warehouse', 'Downsize Warehouse', { kind: 'downsize_warehouse', current_size: 'Large', recommended_size: 'Medium', short_period_percent: 95, sub_five_second_percent: 91.5, query_count: 1200, cost_basis: 42, price_per_credit: 3 }, 54, 90), + snowflakeFinding('high_idle_time', 'High Idle Time', { kind: 'high_idle_time', idle_ratio: 0.6, idle_seconds: 7200, active_seconds: 12000, flagged_days: ['2026-11-11', '2026-11-12'], credits_used: 10, price_per_credit: 3, wasted_cost: 18 }, 54, 77.14), + snowflakeFinding('frequent_restart_overcharge', 'Frequent Restart Overcharge', { kind: 'frequent_restart', bounces: 12, double_billed_seconds: 300, credits_per_hour: 4, flagged_days: ['2026-11-11'], price_per_credit: 3 }, 4.29, 6.43), + snowflakeFinding('underutilized_cluster', 'Underutilized Cluster', { kind: 'underutilized_cluster', max_cluster_count: 2, recommended_max_cluster_count: 1, highest_idle_percent: 70, flagged_days: ['2026-11-13'] }, 0, 0), + ], + total: { monthly_min: 54, monthly_max: 90, resources: 1 }, + what_if: [], + }, + }, +} + /** The tool's failure as `tool run --json` prints it: `status: ok`, the reason in the metadata. */ function failure(error: string) { return { status: 'ok', title: 'Databricks Savings: FAILED', output: `The Databricks savings check failed: ${error}`, metadata: { success: false, error } } @@ -199,6 +250,30 @@ type Options = { store?: Record /** The tool run rejects with this, as `$.process.run` does on its timeout. */ runRejects?: string + /** What `warehouse_list` prints; without it the list cannot be read. */ + list?: string + /** What `finops_snowflake_savings` answers. */ + snowflake?: unknown + /** Environment variables `$.env` answers. */ + env?: Record + /** How the OS opener exits; 0 unless a test says otherwise. */ + openExit?: number + /** Opening a page in the browser waits for this. */ + openHold?: Promise + /** `$.fs.write` refuses with this. */ + writeRejects?: string + /** The session has nobody at a terminal. */ + headless?: boolean + /** `warehouse_list` answers with this failure in its metadata. */ + listError?: string + /** `$.store` refuses every write, as it does past its size limit. */ + storeFull?: boolean + /** `$.store` refuses the writes to these keys. */ + storeRefuses?: (key: string) => boolean + /** What `uname -sr` prints. */ + uname?: string + /** WSL without wslview installed. */ + noWslview?: boolean /** `altimate --version` rejects with this, as `$.process.run` does on its timeout. */ versionRejects?: string /** What `altimate --version` prints on stderr. */ @@ -207,19 +282,59 @@ type Options = { versionExit?: number } +// The clock of the test that is running: tests in a file run one at a time. +let testClock: { settle: () => Promise } | null = null + +/** Presses Show all when the pane offers it, so the full detail (every finding, what-ifs, checks not run, Run again) is drawn. */ +async function showAll(ui: any) { + if (!(await ui.find({ type: 'Button', key: 'more' }))) return + await ui.press({ key: 'more' }) + await testClock?.settle() +} + +/** The pane as Show all draws it: today's full detail. */ +async function mountFull($: any, surface: 'terminal' | 'desktop' = 'terminal') { + const ui = await $.ui.mount({ ...PANE, surface }) + await showAll(ui) + return ui +} + async function start($: any, on: any, options: Options = {}) { const clock = mock.clock(on, { now: options.now ?? Date.parse('2026-11-17T10:00:00Z') }) + testClock = clock const runs: { argv: string[]; env: Record | undefined }[] = [] const versionRuns: { env: Record | undefined }[] = [] const toasts: string[] = [] const fills: string[] = [] const store = new Map(Object.entries(options.store ?? {})) + const listRuns: { argv: string[]; env: Record | undefined }[] = [] + const snowflakeRuns: { argv: string[]; env: Record | undefined }[] = [] + const opened: string[] = [] + const written = new Map() + const statuses: (string | undefined)[] = [] + on('store.keys', () => ({ value: [...store.keys()] })) + on('store.delete', (_: unknown, e: { key: string }) => { + store.delete(e.key) + return { value: undefined } + }) + on('env.get', (_: unknown, e: { name: string }) => ({ value: options.env?.[e.name] })) + on('fs.write', (_: unknown, e: { path: string; text: string }) => { + if (options.writeRejects) return { deny: options.writeRejects } + written.set(e.path, e.text) + return { value: undefined } + }) + on('ui.status', (_: unknown, e: { text?: string }) => { + statuses.push(e.text) + return { value: undefined } + }) on('store.get', async (_: unknown, e: { key: string }) => { if (e.key.startsWith('savings-baseline:')) await options.onStep?.('baseline read') return { value: store.get(e.key) } }) on('store.set', async (_: unknown, e: { key: string; value: unknown }) => { if (e.key.startsWith('savings-baseline:')) await options.onStep?.('baseline write') + if (e.key.startsWith('savings-fix:')) await options.onStep?.('fix write') + if (options.storeFull || options.storeRefuses?.(e.key)) return { deny: 'the store is over its limit' } store.set(e.key, e.value) return { value: undefined } }) @@ -250,7 +365,7 @@ async function start($: any, on: any, options: Options = {}) { const { Box } = $$.ui.resolve(e) return }) - on('fs.exists', () => ({ value: false })) + on('fs.exists', (_: unknown, e: { path: string }) => ({ value: options.files?.[e.path] !== undefined })) const reads = new Map() on('fs.read', async (_: unknown, e: { path: string }) => { reads.set(e.path, (reads.get(e.path) ?? 0) + 1) @@ -260,14 +375,37 @@ async function start($: any, on: any, options: Options = {}) { on('tool.list', () => ({ value: [] })) on('mcp.connect', () => ({ value: { isConnected: false, reason: 'not_connected', message: 'off' } })) on('process.run', async (_: unknown, e: { argv: readonly string[]; init?: { env?: Record } }) => { - const [, command, , tool] = e.argv + const [bin, command, , tool] = e.argv + if (bin === 'uname') return { value: { exitCode: 0, stdout: `${options.uname ?? 'Darwin 24.6.0'}\n`, stderr: '' } } + if (bin === 'wslview' && options.noWslview) return { deny: 'spawn wslview ENOENT' } + if (bin === 'wslpath' || bin === 'wslview' || bin === 'xdg-open' || bin === 'explorer.exe') { + opened.push(`${bin} ${e.argv.slice(1).join(' ')}`) + return { value: { exitCode: 0, stdout: '', stderr: '' } } + } + if (bin === 'mkdir') return { value: { exitCode: 0, stdout: '', stderr: '' } } + if (bin === 'open') { + if (options.openHold) await options.openHold + opened.push(command!) + return { value: { exitCode: options.openExit ?? 0, stdout: '', stderr: '' } } + } if (command === '--version') { await options.onStep?.('version probe') if (options.missingCli) return { deny: 'spawn altimate ENOENT' } if (options.versionRejects) return { deny: options.versionRejects } - versionRuns.push({ env: e.init?.env }) + // The status line's own version check at session start runs without the switches: not the savings check's. + if (e.init?.env?.ALTIMATE_ASSESSMENT_MODE === 'true') versionRuns.push({ env: e.init?.env }) return { value: { exitCode: options.versionExit ?? 0, stdout: options.version === null ? '' : `${options.version ?? SAVINGS_MIN_ALTIMATE_CODE}\n`, stderr: options.versionStderr ?? '' } } } + if (command === 'tool' && tool === 'warehouse_list') { + listRuns.push({ argv: [...e.argv], env: e.init?.env }) + if (options.list === undefined) return { value: { exitCode: 1, stdout: '', stderr: 'no list here' } } + if (options.listError) return { value: { exitCode: 0, stdout: JSON.stringify({ status: 'ok', title: 'Warehouses: ERROR', output: 'Failed to list warehouses', metadata: { count: 0, error: options.listError } }), stderr: '' } } + return { value: { exitCode: 0, stdout: JSON.stringify({ status: 'ok', title: 'Warehouses', output: options.list, metadata: {} }), stderr: '' } } + } + if (command === 'tool' && tool === 'finops_snowflake_savings') { + snowflakeRuns.push({ argv: [...e.argv], env: e.init?.env }) + return { value: { exitCode: 0, stdout: JSON.stringify(options.snowflake ?? SNOWFLAKE_ANSWER), stderr: '' } } + } // The other halves of the plugin ask the CLI for other things at session start. if (command !== 'tool' || tool !== 'finops_databricks_savings') return { value: { exitCode: 1, stdout: '', stderr: 'not this test' } } runs.push({ argv: [...e.argv], env: e.init?.env }) @@ -280,11 +418,13 @@ async function start($: any, on: any, options: Options = {}) { return { value: { exitCode: 0, stdout: JSON.stringify(options.answer ?? ANSWER), stderr: '' } } }) on('tool.call', () => ({ result: { ok: true } })) - await $.session.start({ cwd: ROOT, surface: 'terminal', isInteractive: true }) + await $.session.start({ cwd: ROOT, surface: 'terminal', isInteractive: !options.headless }) await clock.settle() - // The session start's own version check (for the status line) is not the savings check's. + const atStart = { versionRuns: versionRuns.length, listRuns: listRuns.length, runs: runs.length } + // From here on the lists hold what the test itself caused. versionRuns.length = 0 - return { clock, runs, versionRuns, toasts, fills, store } + listRuns.length = 0 + return { clock, runs, versionRuns, listRuns, snowflakeRuns, atStart, toasts, fills, store, opened, written, statuses } } const composer = { origin: { kind: 'composer' }, presentation: { isFullscreen: false, columns: 200 } } @@ -308,7 +448,17 @@ test('/savings runs the altimate-code tool once with telemetry off and draws its expect(toasts.at(-1)).toBe('Databricks savings check: $80.64–$101 a month on 1 resource.') for (const surface of ['terminal', 'desktop'] as const) { - const ui = await $.ui.mount({ ...PANE, surface }) + // Slim first: the header, the total, each finding on one title line and one fact. + const slim = await $.ui.mount({ ...PANE, surface }) + expect(await slim.find({ type: 'Text', text: /^Savings check · last 7 days · dbxmega$/ })).toBeDefined() + expect(await slim.find({ type: 'Text', text: /^Read-only, on your own connection\. Nothing was sent to Altimate\.$/ })).toBeDefined() + expect(await slim.find({ type: 'Text', text: /^\$80\.64–\$101 a month$/ })).toBeDefined() + expect(await slim.find({ type: 'Text', text: /^Classic · Databricks · Migrate Classic\/Pro to Serverless · \$80\.64–\$101 a month$/ })).toBeDefined() + expect(await slim.find({ type: 'Text', text: /^CLASSIC SMALL warehouse, 95% idle over 11\.0 running hours \(3,107 queries\)$/ })).toBeDefined() + expect(await slim.find({ type: 'Text', text: /^Altimate runs 9 more checks on this platform\.$/ })).toBeDefined() + expect(await slim.find({ type: 'Text', text: /2X-SMALL is enough|What if|Not run here/ })).toBeUndefined() + await slim.unmount() + const ui = await mountFull($, surface) expect(await ui.find({ type: 'Text', text: /^\$80\.64–\$101 a month$/ })).toBeDefined() expect(await ui.find({ type: 'Text', text: /^Classic · Migrate Classic\/Pro to Serverless · \$80\.64–\$101 a month$/ })).toBeDefined() expect(await ui.find({ type: 'Text', text: /^Classic · Over-Sized Warehouse · \$31\.48–\$55\.09 a month$/ })).toBeDefined() @@ -316,7 +466,12 @@ test('/savings runs the altimate-code tool once with telemetry off and draws its expect(await ui.find({ type: 'Text', text: /^2X-SMALL is enough: 12 → 4 DBU an hour, on \$27\.54 spent over 7 days$/ })).toBeDefined() expect(await ui.find({ type: 'Text', text: /^5 SQL warehouses, 0 all-purpose clusters and 0 jobs · the 7 days to 2026-11-18 · connection dbxmega$/ })).toBeDefined() expect(await ui.find({ type: 'Text', text: /These were 4 of Altimate's 13 Databricks checks/ })).toBeDefined() - expect((await ui.find({ type: 'Link' }))?.props.href).toBe(SIGNUP_URL) + expect(await ui.find({ key: 'altimate' })).toBeDefined() + // Show fewer goes back to the slim view. + await ui.press({ key: 'fewer' }) + await clock.settle() + expect(await ui.find({ type: 'Text', text: /^Savings check · last 7 days · dbxmega$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /Not run here/ })).toBeUndefined() await ui.unmount() } }) @@ -343,7 +498,7 @@ test('an altimate-code without the tool says to update it', async ($, on) => { const { clock } = await start($, on, { error }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) expect(await ui.find({ type: 'Text', text: /^This altimate-code has no Databricks savings check\.$/ })).toBeDefined() expect(await ui.find({ type: 'Text', text: /altimate upgrade/ })).toBeDefined() await ui.unmount() @@ -356,7 +511,7 @@ test('with no Databricks connection the pane says how to add one, and gives no v const { clock, toasts } = await start($, on, { answer }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) expect(await ui.find({ type: 'Text', text: /^altimate-code has no Databricks connection\.$/ })).toBeDefined() expect(await ui.find({ type: 'Text', text: /connections\.json/ })).toBeDefined() expect(await ui.find({ type: 'Text', text: /No savings found|a month$/ })).toBeUndefined() @@ -371,7 +526,7 @@ test('a refused query says what to ask an admin for, and is no verdict', async ( const { clock } = await start($, on, { answer }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) expect(await ui.find({ type: 'Text', text: /^A query was refused: \[TABLE_OR_VIEW_NOT_FOUND\]/ })).toBeDefined() expect(await ui.find({ type: 'Text', text: /system\.query and system\.lakeflow: ask a workspace admin for SELECT/ })).toBeDefined() expect(await ui.find({ type: 'Text', text: /No savings found/ })).toBeUndefined() @@ -382,10 +537,11 @@ test('without altimate-code the pane says how to install it', async ($, on) => { const { clock } = await start($, on, { missingCli: true }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) expect(await ui.find({ type: 'Text', text: /^altimate-code is not installed\.$/ })).toBeDefined() - // The scoped package the CLI ships as, as the plugin's other install hints name it. - expect(await ui.find({ type: 'Text', text: /^Install it \(`npm i -g @altimateai\/altimate-code`\), add a Databricks connection/ })).toBeDefined() + // The scoped package the CLI ships as, as the plugin's other install hints name it. With no connection list read, + // no platform is named: it could be the wrong one. + expect(await ui.find({ type: 'Text', text: /^Install it \(`npm i -g @altimateai\/altimate-code`\), add a Databricks or Snowflake connection/ })).toBeDefined() await ui.unmount() }) @@ -395,9 +551,9 @@ test('checks that ran and found nothing say so, and still link to the rest', asy await savings($) await clock.settle() expect(toasts.at(-1)).toBe('Databricks savings check: no savings found on 5 SQL warehouses, 0 all-purpose clusters and 0 jobs.') - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) expect(await ui.find({ type: 'Text', text: /^No savings found by these 4 checks\.$/ })).toBeDefined() - expect((await ui.find({ type: 'Link' }))?.props.href).toBe(SIGNUP_URL) + expect(await ui.find({ key: 'altimate' })).toBeDefined() await ui.unmount() }) @@ -409,7 +565,7 @@ test('a run still waiting when the session ends never writes its report', async await $.session.end({ reason: 'clear' } as any) release() await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) expect(await ui.find({ type: 'Text', text: /a month/ })).toBeUndefined() expect(await ui.find({ type: 'Text', text: /Run \/savings/ })).toBeDefined() expect(toasts.filter(text => text.startsWith('Databricks savings check'))).toEqual([]) @@ -438,7 +594,7 @@ test('Run again checks the same connection again', async ($, on) => { const { clock, runs } = await start($, on) await savings($, 'prod_dbx') await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) await ui.press({ key: 'again' }) await clock.settle() expect(runs.map(one => JSON.parse(one.argv[5]!))).toEqual([{ warehouse: 'prod_dbx', confirm: true }, { warehouse: 'prod_dbx', confirm: true }]) @@ -482,6 +638,7 @@ test('each refusal altimate-code gives is explained in the person\'s terms', () `ALTIMATE_ASSESSMENT_MODE=true ALTIMATE_TELEMETRY_DISABLED=true altimate tool run finops_databricks_savings --args '{"warehouse":"prod_dbx","confirm":true}' --json --no-daemon`, ) expect(explain('socket hang up').recovery).toContain(`--args '{"confirm":true}'`) + expect(explain('socket hang up', 'sf', 'snowflake').recovery).toContain(`altimate tool run finops_snowflake_savings --args '{"warehouse":"sf","confirm":true}'`) // The resolver's words for a connection of another type, as altimate-code writes them. const other = explain('The Databricks savings check is not available for snowflake warehouses. Try one of: dbx.') expect(other.text).toBe('That connection is not a Databricks one.') @@ -489,6 +646,23 @@ test('each refusal altimate-code gives is explained in the person\'s terms', () expect(explain('No SQL warehouses were found for warehouse abc123 in system.compute.warehouses.').recovery).toContain('within a few hours') }) +test('Snowflake refusals name Snowflake and what to ask for', () => { + expect(explain('Unknown tool: finops_snowflake_savings. Run it', null, 'snowflake').text).toBe('This altimate-code has no Snowflake savings check.') + expect(explain('SQL access control error: Insufficient privileges to operate on schema ACCOUNT_USAGE', null, 'snowflake').recovery).toContain('IMPORTED PRIVILEGES') + expect(explain('The Snowflake savings check requires a configured warehouse', null, 'snowflake').recovery).toContain('type "snowflake"') + // The same words from Databricks are not read as Snowflake's permission error. + expect(explain('user is not authorized').text).toBe('The savings check failed: user is not authorized') +}) + +test('a run that answers nothing says so rather than failing silently', async ($, on) => { + const { clock } = await start($, on, { output: { exitCode: 1, stdout: '', stderr: '' } }) + await savings($) + await clock.settle() + const ui = await mountFull($) + expect(await ui.find({ type: 'Text', text: /^The savings check failed: no answer$/ })).toBeDefined() + await ui.unmount() +}) + test('dollars are whole from $100 and to the cent below it', () => { expect(dollars(106.46)).toBe('$106') expect(dollars(85.1699)).toBe('$85.17') @@ -513,7 +687,7 @@ test('Draft the fix puts a request for the change in the prompt box, and sends n const { clock, runs, toasts, fills } = await start($, on) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) await ui.press({ key: 'fix-0' }) await clock.settle() expect(fills.length).toBe(1) @@ -536,7 +710,7 @@ test('Draft the fix with no prompt box says so instead of claiming it filled one const { clock, toasts, fills } = await start($, on, { canFill: false }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) await ui.press({ key: 'fix-0' }) await clock.settle() expect(fills).toEqual([]) @@ -671,7 +845,7 @@ test('/savings typed after a band press decided to run is told that const settling = clock.settle() await writing const said = await savings($, 'prod_dbx') - expect(said.text).toBe('The Databricks savings check is already running in the side pane. Run /savings prod_dbx again when it finishes.') + expect(said.text).toBe('The savings check is already running in the side pane. Run /savings prod_dbx again when it finishes.') release() await settling await clock.settle() @@ -776,6 +950,40 @@ test('/savings that finds a check running, which ends while its pane opens, says await clock.settle() }) +test('a band press while a typed /savings reads its connection list starts nothing: the typed connection is read', async ($, on) => { + // Holds the command's read of the connection list, which comes after its claim: the band's press runs meanwhile. + let armed = false + let reached = () => {} + const reading = new Promise(resolve => (reached = resolve)) + let release = () => {} + const released = new Promise(resolve => (release = resolve)) + const hook = on as any + hook('state.get', async (_: unknown, e: { key: string }, next: (e: unknown) => Promise) => { + if (!armed || e.key !== 'savingsConnections') return next(e) + armed = false + const before = await next(e) + reached() + await released + return before + }) + const files = { [`${ROOT}/resources/warehouses.yml`]: 'resources:\n sql_warehouses:\n bi:\n cluster_size: Small\n' } + const { clock, runs } = await start($, on, { files }) + await $.tool.call({ tool: 'Edit', file_path: `${ROOT}/resources/warehouses.yml`, old_string: 'Small', new_string: 'Medium' }) + await clock.settle() + const band = await $.ui.mount(BAND) + await band.press({ key: 'savings-run' }) + await band.unmount() + armed = true + const saying = savings($, 'prod_dbx') + await reading + await clock.settle() + release() + expect((await saying).text).toMatch(/^Running the /) + await clock.settle() + expect(runs.length).toBe(1) + expect(runs[0]!.argv.join(' ')).toContain('prod_dbx') +}) + test('after a check, editing config that names a flagged warehouse puts its saving above the prompt', async ($, on) => { const files = { [`${ROOT}/infra/warehouses.tf`]: 'resource "databricks_sql_endpoint" "classic" {\n name = "Classic"\n cluster_size = "Small"\n}\n' } const { clock } = await start($, on, { files }) @@ -816,7 +1024,7 @@ test('pressing a what-if size shows what the warehouse would cost there and whet const { clock } = await start($, on) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) expect(await ui.find({ type: 'Text', text: /^What if Classic \(\$118 a month now\) were…$/ })).toBeDefined() expect(await ui.find({ type: 'Text', text: /^Press a size to see/ })).toBeDefined() // The choices, in core's order: serverless, then each smaller size. @@ -837,7 +1045,7 @@ test('a size too small for the queries is marked, and pressing it says they woul const { clock } = await start($, on, { answer }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) expect(((await ui.find({ key: 'whatif-0-2' })) as any)?.props.label).toBe('2X-SMALL $39.35 ⚠') await ui.press({ key: 'whatif-0-2' }) await clock.settle() @@ -855,7 +1063,7 @@ test('a flagged warehouse is remembered, and a later run that finds it resized s const { clock } = await start($, on, { answer: resized, store }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) const change = (await ui.find({ type: 'Text', text: /^Classic: SMALL CLASSIC → X-SMALL CLASSIC since 2026-11-10\./ })) as any expect(await ui.find({ type: 'Text', text: /^Classic: SMALL CLASSIC → X-SMALL CLASSIC since 2026-11-10\. Observed spend: \$118\.03 a month before, \$59\.01 after\.$/ })).toBeDefined() expect(await ui.find({ type: 'Text', text: /^Billed in different weeks, so a change in workload moves these too: not a measured saving\.$/ })).toBeDefined() @@ -874,9 +1082,9 @@ test('a resized warehouse that costs more in its later week shows both amounts t const { clock } = await start($, on, { answer: resized, store }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) expect(await ui.find({ type: 'Text', text: /^Classic: SMALL CLASSIC → X-SMALL CLASSIC since 2026-11-10\. Observed spend: \$118\.03 a month before, \$177\.04 after\.$/ })).toBeDefined() - expect(await ui.find({ type: 'Text', text: /saved|more/i })).toBeUndefined() + expect(await ui.find({ type: 'Text', text: /saved|a month more/i })).toBeUndefined() await ui.unmount() }) @@ -886,7 +1094,7 @@ test('the first run that flags a warehouse keeps what it is, and an unflagged on await clock.settle() expect(store.get('savings-baseline:dbxmega:wh-classic')).toEqual({ date: '2026-11-18', config: { size: 'SMALL', type: 'CLASSIC' }, windowCost: 27.544375, days: 7 }) expect(store.has('savings-baseline:dbxmega:wh-xs')).toBe(false) - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) expect(await ui.find({ type: 'Text', text: / since / })).toBeUndefined() await ui.unmount() }) @@ -928,7 +1136,7 @@ test('idle clusters and jobs on all-purpose compute get their own evidence and f const { clock, fills } = await start($, on, { answer }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) expect(await ui.find({ type: 'Text', text: /^5 SQL warehouses, 3 all-purpose clusters and 12 jobs · / })).toBeDefined() expect(await ui.find({ type: 'Text', text: /^nightly_orders · Job Running on All-Purpose Compute · \$1,870–\$2,805 a month$/ })).toBeDefined() expect(await ui.find({ type: 'Text', text: /^1,028 task runs \(periodic\), 181\.8 hours on all-purpose compute, about 1,818\.2 DBUs, most on cluster "shared analytics"$/ })).toBeDefined() @@ -973,7 +1181,7 @@ test('a control character in a workspace name does not blank the pane', async ($ const { clock } = await start($, on, { answer }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) expect(await ui.find({ type: 'Text', text: /^night \[2J ly FAKE · Job Running on All-Purpose Compute · / })).toBeDefined() expect(await ui.find({ type: 'Text', text: /^0101-abc · Idle Cluster Detection · / })).toBeDefined() expect(await ui.find({ type: 'Text', text: /^What if what if \(/ })).toBeDefined() @@ -1007,7 +1215,7 @@ test('when checks were skipped and none found anything, the verdict is only for await savings($) await clock.settle() expect(toasts.at(-1)).toBe('Databricks savings check: no savings found on 5 SQL warehouses, 0 all-purpose clusters and 0 jobs; 1 of the 4 checks could not run.') - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) expect(await ui.find({ type: 'Text', text: /^No savings found by the 3 of 4 checks that ran\.$/ })).toBeDefined() expect(await ui.find({ type: 'Text', text: /^No savings found by these 4 checks/ })).toBeUndefined() await ui.unmount() @@ -1019,7 +1227,7 @@ test('a query that read only its first 10,000 rows is named in the pane', async const { clock } = await start($, on, { answer }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) expect(await ui.find({ type: 'Text', text: /^Only the first 10,000 job task rows were read; any beyond them were not checked\.$/ })).toBeDefined() await ui.unmount() }) @@ -1032,7 +1240,7 @@ test('the band never starts a second run while one is going', async ($, on) => { // A second run that does not finish yet. let release = () => {} options.hold = new Promise(done => (release = done)) - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) await ui.press({ key: 'again' }) await clock.settle() expect(runs.length).toBe(2) @@ -1059,10 +1267,12 @@ test('the first baseline stays: a second run after a resize still says what chan const started = await start($, on, { answer: resized, store }) await savings($) await started.clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) await ui.press({ key: 'again' }) await started.clock.settle() expect(started.runs.length).toBe(2) + // A new run starts slim again. + await showAll(ui) expect(started.store.get('savings-baseline:dbxmega:wh-classic')).toEqual(store['savings-baseline:dbxmega:wh-classic']) expect(await ui.find({ type: 'Text', text: /^Classic: SMALL CLASSIC → X-SMALL CLASSIC since 2026-11-10\./ })).toBeDefined() await ui.unmount() @@ -1076,7 +1286,7 @@ test('a serverless choice that would cost more says so, in the warning colour', const { clock } = await start($, on, { answer }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) await ui.press({ key: 'whatif-0-0' }) await clock.settle() const line = (await ui.find({ type: 'Text', text: /^As serverless: \$300 a month instead of \$118, \$182 more: / })) as any @@ -1110,7 +1320,7 @@ test('across several workspaces the pane counts them and names each finding\'s w const { clock, fills } = await start($, on, { answer }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) expect(await ui.find({ type: 'Text', text: /^5 SQL warehouses, 0 all-purpose clusters and 0 jobs in 2 workspaces · / })).toBeDefined() expect(await ui.find({ type: 'Text', text: /^Classic \(workspace 2056943136844690\) · Migrate Classic\/Pro to Serverless · / })).toBeDefined() expect(await ui.find({ type: 'Text', text: /Databricks checks, on 2 workspaces\./ })).toBeDefined() @@ -1135,8 +1345,9 @@ test('an altimate-code older than the check is never started for it: only `--ver await clock.settle() expect(versionRuns.length).toBe(1) expect(runs).toEqual([]) - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) - expect(await ui.find({ type: 'Text', text: /^This altimate-code has no Databricks savings check\.$/ })).toBeDefined() + const ui = await mountFull($) + // No connection list was read, so no platform is named. + expect(await ui.find({ type: 'Text', text: /^This altimate-code has no savings check\.$/ })).toBeDefined() expect(toasts.at(-1)).toContain(`It is 0.12.11; update it to ${SAVINGS_MIN_ALTIMATE_CODE} or later`) await ui.unmount() }) @@ -1184,7 +1395,7 @@ test('an altimate-code too old to have `tool run` says to update, from what that const { clock, toasts } = await start($, on, { output: { exitCode: 1, stdout: '', stderr } }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) expect(await ui.find({ type: 'Text', text: /^This altimate-code has no Databricks savings check\.$/ })).toBeDefined() expect(toasts.at(-1)).toContain('altimate upgrade') await ui.unmount() @@ -1202,7 +1413,7 @@ test('a finding in a workspace with no SQL warehouse still counts that workspace const { clock } = await start($, on, { answer }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) expect(await ui.find({ type: 'Text', text: / in 2 workspaces · / })).toBeDefined() expect(await ui.find({ type: 'Text', text: /^Classic \(workspace 222\) · / })).toBeDefined() await ui.unmount() @@ -1219,7 +1430,7 @@ test('a workspace the CLI read with no SQL warehouse and nothing found is still const { clock } = await start($, on, { answer }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) expect(await ui.find({ type: 'Text', text: /^5 SQL warehouses, 2 all-purpose clusters and 4 jobs in 2 workspaces · / })).toBeDefined() // With two workspaces read, each finding says which one it is in. expect(await ui.find({ type: 'Text', text: /^Classic \(workspace 111\) · Migrate Classic\/Pro to Serverless · / })).toBeDefined() @@ -1236,202 +1447,1736 @@ for (const counted of [undefined, 1, 0, -3, 1.5, 'two']) { const { clock } = await start($, on, { answer }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) expect(await ui.find({ type: 'Text', text: / in 2 workspaces · / })).toBeDefined() await ui.unmount() }) } -test('a job whose evidence lacks its trigger, host cluster, hours or DBUs reads without "NaN", "undefined", empty quotes or "(id )"', () => { - const evidence = { kind: 'job_on_all_purpose', task_runs: 3, all_purpose_rate_per_dbu: 0.55, jobs_rate_per_dbu: 0.15 } - const [line] = evidenceLines(evidence) - expect(line).toBe('3 task runs, ? hours on all-purpose compute, ? DBUs') - const request = fixRequest({ ...JOB, evidence }) - expect(request).not.toMatch(/NaN|undefined|""|\(id \)/) - expect(request).toContain('sized like the cluster each task uses now.') - // Present values still read as before, and a tiny DBU figure is "under 0.1" without "about". - expect(evidenceLines({ ...JOB.evidence, estimated_dbus: 0.01 })[0]).toContain(', under 0.1 DBUs, most on cluster "shared analytics"') - expect(evidenceLines(JOB.evidence)[0]).toContain('(periodic), 181.8 hours on all-purpose compute, about 1,818.2 DBUs') +// --- The status line and the kept answer. + +const BOTH = 'Name | Type | Database\ndbxmega | databricks | -\nclassic | databricks | -\nsfmega | snowflake | ANALYTICS\nsfother | snowflake | ANALYTICS\nscratch | duckdb | scratch' +const DATABRICKS_ONLY = 'Name | Type | Database\ndbxmega | databricks | -' +const HOME = '/home/me' +const CONNECTIONS = JSON.stringify({ + dbxmega: { type: 'databricks', server_hostname: 'x', http_path: '/sql/1.0/warehouses/wh-xs', access_token: 'never-kept' }, + classic: { type: 'databricks', server_hostname: 'x', http_path: '/sql/1.0/warehouses/wh-classic', access_token: 'never-kept' }, + sfmega: { type: 'snowflake', account: 'ACME-SF', user: 'u', warehouse: 'BI_WH', private_key: 'never-kept' }, + sfother: { type: 'snowflake', account: 'other-sf', user: 'u', warehouse: 'BI_WH', private_key: 'never-kept' }, +}) +const CONNECTION_FILES = { [`${HOME}/.altimate-code/connections.json`]: CONNECTIONS } +const NOW = Date.parse('2026-11-17T10:00:00Z') +const HERE = `project:${ROOT}` +const KEPT_KEY = `savings-report:${HERE}/dbxmega` +const lastStatus = (statuses: (string | undefined)[]) => statuses.at(-1) + +test('before any run the status line names the platforms and /savings, and the check does not run', async ($, on) => { + const { atStart, runs, snowflakeRuns, statuses } = await start($, on, { list: BOTH }) + expect(lastStatus(statuses)).toBe('⚡ Altimate · Databricks + Snowflake · /savings') + expect(atStart).toEqual({ versionRuns: 1, listRuns: 1, runs: 0 }) + expect(runs).toEqual([]) + expect(snowflakeRuns).toEqual([]) }) -test('when no check could run, the pane and the notice say nothing was checked, not that nothing was found', async ($, on) => { - const answer = JSON.parse(JSON.stringify(ANSWER)) - const checks = ['Migrate Classic/Pro to Serverless', 'Over-Sized Warehouse', 'Idle Cluster Detection', 'Job Running on All-Purpose Compute'] - // A check listed twice is still one check. - answer.metadata.skipped = [...checks, checks[3]].map(check => ({ check, reason: 'INSUFFICIENT_PERMISSIONS' })) - answer.metadata.report = { lookback_days: 7, findings: [], total: { monthly_min: 0, monthly_max: 0, resources: 0 }, what_if: [] } - const { clock, toasts } = await start($, on, { answer }) +test('the connection list is read with telemetry off and outside the daemon', async ($, on) => { + const { clock, listRuns } = await start($, on, { list: BOTH }) await savings($) await clock.settle() - expect(toasts.at(-1)).toBe('Databricks savings check: none of the 4 checks could run, so nothing was checked.') - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) - expect(await ui.find({ type: 'Text', text: /^None of the 4 checks could run, so nothing was checked\.$/ })).toBeDefined() - expect(await ui.find({ type: 'Text', text: /No savings found|-?\d+ of 4 checks that ran/ })).toBeUndefined() - await ui.unmount() + expect(listRuns[0]!.argv.slice(1)).toEqual(['tool', 'run', 'warehouse_list', '--args', '{}', '--json', '--no-daemon']) + expect(listRuns[0]!.env).toEqual({ ALTIMATE_TELEMETRY_DISABLED: 'true', ALTIMATE_ASSESSMENT_MODE: 'true' }) }) -test('a check listed for two reasons counts once in the verdict', () => { - expect(checksNotRun({ skipped: ['Idle Cluster Detection (refused)', 'Idle Cluster Detection (time limit)'] })).toBe(1) +test('an altimate-code too old for assessment mode is not started to list connections', async ($, on) => { + const { atStart, statuses } = await start($, on, { list: BOTH, version: '0.12.11' }) + expect(atStart).toEqual({ versionRuns: 1, listRuns: 0, runs: 0 }) + expect(statuses.filter(Boolean)).toEqual([]) }) -for (const [name, options] of [ - ['prints no version', { version: '' }], - ['does not answer', { versionRejects: 'timed out after 15000 ms' }], -] as const) { - test(`a --version that ${name} says the version could not be read; nothing else runs`, async ($, on) => { - const { clock, runs, toasts } = await start($, on, options) - await savings($) - await clock.settle() - expect(runs).toEqual([]) - expect(toasts.at(-1)).toContain("altimate-code's version could not be read, so the savings check was not started.") - expect(toasts.at(-1)).not.toContain('It is ') - }) -} +test('a session nobody is at does not start the CLI to list connections', async ($, on) => { + const { atStart } = await start($, on, { list: BOTH, headless: true }) + expect(atStart).toEqual({ versionRuns: 0, listRuns: 0, runs: 0 }) +}) -test('a version printed with the CLI name in front still starts the check', async ($, on) => { - const { clock, runs } = await start($, on, { version: `altimate-code ${SAVINGS_MIN_ALTIMATE_CODE}` }) +test('no warehouse connection, no status entry', async ($, on) => { + const { statuses } = await start($, on, { list: 'Name | Type | Database\nlocal | postgres | app' }) + expect(statuses.filter(Boolean)).toEqual([]) +}) + +test('after a run the status line shows the monthly range, and the answer is kept per connection', async ($, on) => { + const { clock, statuses, store } = await start($, on, { list: DATABRICKS_ONLY }) await savings($) await clock.settle() - expect(runs.length).toBe(1) + expect(lastStatus(statuses)).toBe('⚡ Altimate · $80.64–$101/mo to save · /savings') + const kept = store.get(KEPT_KEY) as any + expect(kept.savedAt).toBe(NOW) + expect(kept.view.total.resources).toBe(1) }) -for (const command of ['echo databricks bundle deploy', 'grep databricks clusters notes.txt', 'git commit -m "databricks jobs"']) { - test(`a command that only names databricks (${command}) offers nothing`, async ($, on) => { - const { clock } = await start($, on) - await $.tool.call({ tool: 'Bash', command }) - await clock.settle() - const band = await $.ui.mount(BAND) - expect(await band.find({ type: 'Text', text: /Databricks compute in play/ })).toBeUndefined() - await band.unmount() - }) -} - -for (const command of ['databricks jobs list', 'ls; databricks clusters list', 'make build || databricks bundle validate', 'A=1 B=2 databricks warehouses list']) { - test(`a command that runs databricks (${command}) offers the check`, async ($, on) => { - const { clock } = await start($, on) - await $.tool.call({ tool: 'Bash', command }) - await clock.settle() - const band = await $.ui.mount(BAND) - expect(await band.find({ type: 'Text', text: /^Databricks compute in play/ })).toBeDefined() - await band.unmount() - }) -} +const keptAnswer = (identity = HERE) => ({ savedAt: NOW, view: { ...toView(ANSWER.metadata as any)!, identity } }) -test('the same warehouse id in two workspaces keeps two baselines, and only the flagged one is kept', async ($, on) => { - const answer = JSON.parse(JSON.stringify(ANSWER)) - const classic = answer.metadata.warehouses.find((one: any) => one.id === 'wh-classic') - classic.workspace_id = '111' - answer.metadata.warehouses.push({ ...classic, workspace_id: '222', name: 'Classic in 222', size: 'LARGE', window_cost: 500 }) - answer.metadata.report.findings.forEach((one: any) => (one.workspace_id = '111')) - const { clock, store } = await start($, on, { answer, now: Date.parse('2026-11-18T10:00:00Z') }) - await savings($) +test('a later session shows the kept answer without running anything, and says how old it is', async ($, on) => { + const { clock, runs, statuses } = await start($, on, { now: NOW + 3 * 86_400_000, store: { [KEPT_KEY]: keptAnswer() } }) await clock.settle() - expect(store.get('savings-baseline:dbxmega:111:wh-classic')).toEqual({ date: '2026-11-18', config: { size: 'SMALL', type: 'CLASSIC' }, windowCost: 27.544375, days: 7 }) - expect(store.has('savings-baseline:dbxmega:222:wh-classic')).toBe(false) - expect(store.has('savings-baseline:dbxmega:wh-classic')).toBe(false) + expect(runs).toEqual([]) + expect(lastStatus(statuses)).toBe('⚡ Altimate · $80.64–$101/mo to save (3d ago) · /savings') + const ui = await mountFull($) + expect(await ui.find({ type: 'Text', text: /^\$80\.64–\$101 a month$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^Kept from 2026-11-17: nothing is checked again until you run \/savings\.$/ })).toBeDefined() + await ui.unmount() }) -test('a baseline in one workspace is read for that workspace only, though another has a warehouse with its id', async ($, on) => { - // Workspace 111's Classic was SMALL and is X-SMALL now; workspace 222 has a LARGE warehouse with the same id. - const store = { 'savings-baseline:dbxmega:111:wh-classic': { date: '2026-11-10', config: { size: 'SMALL', type: 'CLASSIC' }, windowCost: 27.54 } } - const answer = JSON.parse(JSON.stringify(ANSWER)) - answer.metadata.warehouses = answer.metadata.warehouses.map((one: any) => ({ ...one, workspace_id: '111', size: one.id === 'wh-classic' ? 'X_SMALL' : one.size })) - const classic = answer.metadata.warehouses.find((one: any) => one.id === 'wh-classic') - answer.metadata.warehouses.push({ ...classic, workspace_id: '222', name: 'Other classic', size: 'LARGE' }) - const { clock } = await start($, on, { answer, store }) - await savings($) +test('after seven days the kept answer is gone and the status line offers /savings again', async ($, on) => { + const later = await start($, on, { now: NOW + 7 * 86_400_000, list: DATABRICKS_ONLY, store: { [KEPT_KEY]: keptAnswer() } }) + expect(later.store.has(KEPT_KEY)).toBe(false) + expect(lastStatus(later.statuses)).toBe('⚡ Altimate · Databricks · /savings') + expect(later.runs).toEqual([]) +}) + +test('another project\'s answer stays out of this one, though it stays in the store', async ($, on) => { + const elsewhere = `savings-report:project:/other/dbxmega` + const { statuses, store, clock } = await start($, on, { store: { [elsewhere]: keptAnswer('project:/other') } }) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) - const texts = ((await ui.findAll({ type: 'Text' })) as any[]).map(one => one.text) - expect(texts.filter(text => / → .* since 2026-11-10/.test(text))).toEqual([ - 'Classic (workspace 111): SMALL CLASSIC → X-SMALL CLASSIC since 2026-11-10. Observed spend: $118.03 a month before, $118.05 after.', - ]) - await ui.unmount() + expect(store.has(elsewhere)).toBe(true) + expect(statuses.filter(Boolean)).toEqual([]) + const note = await $.ui.mount(row(rowProps(SQL_TOOL, { warehouse: 'dbxmega', query: 'select 1' }))) + expect(await note.find({ type: 'Text', text: /→ \/savings/ })).toBeUndefined() + await note.unmount() }) -// Each setting, known or not before and after, the same or not: what the baseline keeps, and the line the pane draws. -// The other setting is either known and the same on both sides, or unknown before and read now. The baseline is one -// run's read: a run that reads every setting it knew, finds none changed and reads more replaces it whole, with its -// own date and cost; any other run leaves it as it was. -const SETTING_CASES = [ - { setting: 'size', a: 'SMALL', b: 'X_SMALL', other: 'type', otherValue: 'CLASSIC' }, - { setting: 'type', a: 'CLASSIC', b: 'PRO', other: 'size', otherValue: 'SMALL' }, -] as const -for (const { setting, a, b, other, otherValue } of SETTING_CASES) { - for (const otherBefore of ['known', 'unknown'] as const) { - for (const before of ['known', 'unknown'] as const) { - for (const after of ['known', 'unknown'] as const) { - for (const same of [true, false]) { - test(`baseline ${setting}: ${before} before, ${after} after, ${same ? 'same' : 'different'} value; ${other} ${otherBefore === 'known' ? 'known throughout' : 'read only now'}`, async ($, on) => { - const was = { [other]: otherBefore === 'known' ? otherValue : null, [setting]: before === 'known' ? a : null } as Record - const now = { [other]: otherValue, [setting]: after === 'known' ? (same ? a : b) : null } as Record - const key = 'savings-baseline:dbxmega:wh-classic' - const store = { [key]: { date: '2026-11-10', config: { size: was.size ?? null, type: was.type ?? null }, windowCost: 27.54 } } - const answer = JSON.parse(JSON.stringify(ANSWER)) - Object.assign(answer.metadata.warehouses.find((one: any) => one.id === 'wh-classic'), { size: now.size ?? null, type: now.type ?? null }) - const started = await start($, on, { answer, store }) - await savings($) - await started.clock.settle() - // Changed: only a setting known on both sides, with different values. - const changed = before === 'known' && after === 'known' && !same - const covered = before === 'unknown' || after === 'known' - const learned = (before === 'unknown' && after === 'known') || otherBefore === 'unknown' - const replaced = !changed && covered && learned - const kept = started.store.get(key) as any - expect(kept.config).toEqual(replaced ? { size: now.size ?? null, type: now.type ?? null } : { size: was.size ?? null, type: was.type ?? null }) - expect(kept.date === '2026-11-10').toBe(!replaced) - // The line names only the settings known on both sides. - const named = (['size', 'type'] as const).filter(one => was[one] !== null && now[one] !== null) - const label = (config: Record) => named.map(one => (one === 'size' ? config.size!.replace(/_/g, '-') : config.type!)).join(' ') - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) - const texts = ((await ui.findAll({ type: 'Text' })) as any[]).map(one => String(one.text)) - expect(texts.filter(text => / since 2026-11-10\./.test(text))).toEqual( - changed ? [`Classic: ${label(was)} → ${label(now)} since 2026-11-10. Observed spend: $118.03 a month before, $118.05 after.`] : [], - ) - expect(texts.filter(text => /\?|null|undefined/.test(text) && / since /.test(text))).toEqual([]) - await ui.unmount() - }) - } - } - } - } -} +test('a connection of the same name on another workspace does not pick up the answer', async ($, on) => { + const files = { [`${HOME}/.altimate-code/connections.json`]: JSON.stringify({ dbxmega: { type: 'databricks', server_hostname: 'https://b.example.com/', http_path: '/sql/1.0/warehouses/w' } }) } + const other = await start($, on, { env: { HOME }, files, store: { 'savings-report:databricks:a.example.com/dbxmega': keptAnswer('databricks:a.example.com') } }) + expect(other.statuses.filter(Boolean)).toEqual([]) +}) -test('a setting the baseline did not know is not filled from a read in which another setting changed', async ($, on) => { - // The baseline knew only the type. This run reads SMALL PRO: the type changed, so SMALL is the size after the - // change, not the size the baseline had. - const key = 'savings-baseline:dbxmega:wh-classic' - const answer = JSON.parse(JSON.stringify(ANSWER)) - Object.assign(answer.metadata.warehouses.find((one: any) => one.id === 'wh-classic'), { size: 'SMALL', type: 'PRO' }) - const { clock, store } = await start($, on, { answer, store: { [key]: { date: '2026-11-10', config: { size: null, type: 'CLASSIC' }, windowCost: 27.54 } } }) +test('the same workspace reached from any project shows its answer', async ($, on) => { + const files = { [`${HOME}/.altimate-code/connections.json`]: JSON.stringify({ dbxmega: { type: 'databricks', server_hostname: 'A.example.com', http_path: '/sql/1.0/warehouses/w' } }) } + const here = await start($, on, { env: { HOME }, files, store: { 'savings-report:databricks:a.example.com/dbxmega': keptAnswer('databricks:a.example.com') } }) + expect(lastStatus(here.statuses)).toContain('/mo to save') +}) + +test('a fix drafted under another project\'s connection of the same name is not read', async ($, on) => { + const { clock } = await start($, on, { store: { 'savings-fix:project:/other/dbxmega::sql_warehouse:wh-classic': FIX } }) await savings($) await clock.settle() - expect((store.get(key) as any).config).toEqual({ size: null, type: 'CLASSIC' }) - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) - const texts = ((await ui.findAll({ type: 'Text' })) as any[]).map(one => String(one.text)) - expect(texts.filter(text => / since 2026-11-10\./.test(text))).toEqual(['Classic: CLASSIC → PRO since 2026-11-10. Observed spend: $118.03 a month before, $118.05 after.']) + const ui = await mountFull($) + expect(await ui.find({ type: 'Text', text: /fix drafted|saved since/ })).toBeUndefined() await ui.unmount() }) -test('a run that reads every setting the baseline knew, with none changed, replaces it whole: date and spend too', async ($, on) => { - // Kept on 2026-11-10 with the size unknown. A resize in between could not be seen, so the size this run reads is - // the warehouse now: the baseline takes it with this run's date and spend, never the old week's. - const key = 'savings-baseline:dbxmega:wh-classic' - const answer = JSON.parse(JSON.stringify(ANSWER)) - const classic = answer.metadata.warehouses.find((one: any) => one.id === 'wh-classic') - Object.assign(classic, { size: 'MEDIUM', type: 'CLASSIC' }) - const { clock, store } = await start($, on, { answer, store: { [key]: { date: '2026-11-10', config: { size: null, type: 'CLASSIC' }, windowCost: 99, days: 7 } } }) +test('/clear keeps the answer: it belongs to the warehouse, not the conversation', async ($, on) => { + const { clock, runs, statuses } = await start($, on) await savings($) await clock.settle() - const kept = store.get(key) as any - expect(kept.config).toEqual({ size: 'MEDIUM', type: 'CLASSIC' }) - expect(kept.date).not.toBe('2026-11-10') - expect(kept.windowCost).toBe(Number(classic.window_cost)) + await $.session.end({ reason: 'clear' } as any) + await clock.settle() + expect(runs.length).toBe(1) + expect(lastStatus(statuses)).toContain('$80.64–$101/mo to save') + const ui = await mountFull($) + expect(await ui.find({ type: 'Text', text: /^\$80\.64–\$101 a month$/ })).toBeDefined() + await ui.unmount() }) -test('a run that misses a setting the baseline knew leaves it as it was, whatever else it reads', async ($, on) => { - const key = 'savings-baseline:dbxmega:wh-classic' - const answer = JSON.parse(JSON.stringify(ANSWER)) +test('a run that fails keeps showing the last answer, with the reason above it', async ($, on) => { + const options: Options = {} + const { clock } = await start($, on, options) + await savings($) + await clock.settle() + options.answer = failure('[TABLE_OR_VIEW_NOT_FOUND] gone') + await savings($) + await clock.settle() + const ui = await mountFull($) + expect(await ui.find({ type: 'Text', text: /^A query was refused: / })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^\$80\.64–\$101 a month$/ })).toBeDefined() + await ui.unmount() +}) + +test('a stored answer of an older shape is dropped rather than drawn', async ($, on) => { + const { store } = await start($, on, { store: { 'savings-report:old': { savedAt: NOW, view: { findings: [] } } } }) + expect(store.has('savings-report:old')).toBe(false) +}) + +test('statusText says nothing without a platform or an answer, and "checking" during a run', () => { + expect(statusText({}, null, false, NOW)).toBeNull() + expect(statusText({}, [{ name: 'p', platform: null, warehouse: null, account: null }], false, NOW)).toBeNull() + expect(statusText({}, [{ name: 'd', platform: 'databricks', warehouse: null, account: null }], true, NOW)).toBe('checking savings…') +}) + +test('a clean result on the status line says nothing was found', async ($, on) => { + const answer = { ...ANSWER, metadata: { ...ANSWER.metadata, report: { lookback_days: 7, findings: [], total: { monthly_min: 0, monthly_max: 0, resources: 0 }, what_if: [] } } } + const { clock, statuses } = await start($, on, { answer }) + await savings($) + await clock.settle() + expect(lastStatus(statuses)).toBe('⚡ Altimate · no savings found · /savings') +}) + +// --- The line under a tool row. + +const SQL_TOOL = 'mcp__plugin_altimate-code_altimate-code__sql_execute' +const rowProps = (tool: string, input: unknown, id = 'tu-1') => ({ tool_use_id: id, tool, input, isRunning: false, isErrored: false, isInterrupted: false }) +const row = (props: unknown) => ({ plugin: 'altimate-code', surface: 'terminal', component: 'ToolUse', props }) as any +const NOTE = /^ {2}⎿ {2}Classic: 95% idle · \$80\.64–\$101 a month → \/savings$/ + +const withFinding = async ($: any, on: any, extra: Options = {}) => { + const started = await start($, on, { list: BOTH, env: { HOME }, files: CONNECTION_FILES, ...extra }) + await savings($) + await started.clock.settle() + return started +} + +test('a SQL call on a connection whose warehouse has a finding gets one line, and queries nothing', async ($, on) => { + const { runs, listRuns, versionRuns } = await withFinding($, on) + const before = { runs: runs.length, lists: listRuns.length, versions: versionRuns.length } + const ui = await $.ui.mount(row(rowProps(SQL_TOOL, { warehouse: 'classic', query: 'select 1' }))) + expect(await ui.find({ type: 'Text', text: NOTE })).toBeDefined() + await ui.unmount() + expect({ runs: runs.length, lists: listRuns.length, versions: versionRuns.length }).toEqual(before) +}) + +test('no finding, no line: another warehouse, another tool, or no answer yet', async ($, on) => { + await withFinding($, on) + for (const props of [rowProps(SQL_TOOL, { warehouse: 'dbxmega', query: 'select 1' }), rowProps('Read', { file_path: '/x' }), rowProps('mcp__plugin_altimate-code_altimate-code__schema_inspect', { warehouse: 'classic' })]) { + const ui = await $.ui.mount(row(props)) + expect(await ui.find({ type: 'Text', text: /→ \/savings/ })).toBeUndefined() + await ui.unmount() + } +}) + +test('before any run a SQL call gets no line', async ($, on) => { + await start($, on, { list: BOTH, env: { HOME }, files: CONNECTION_FILES }) + const ui = await $.ui.mount(row(rowProps(SQL_TOOL, { warehouse: 'classic', query: 'select 1' }))) + expect(await ui.find({ type: 'Text', text: /→ \/savings/ })).toBeUndefined() + await ui.unmount() +}) + +test('a SQL call that names no connection runs on the first one', async ($, on) => { + const list = 'Name | Type | Database\nclassic | databricks | -\ndbxmega | databricks | -' + await withFinding($, on, { list }) + const ui = await $.ui.mount(row(rowProps(SQL_TOOL, { query: 'select 1' }))) + expect(await ui.find({ type: 'Text', text: NOTE })).toBeDefined() + await ui.unmount() +}) + +test('the same call through `altimate tool run` in a shell gets the line', async ($, on) => { + await withFinding($, on) + const command = `altimate tool run sql_execute --args '{"warehouse":"classic","query":"select 1"}' --json` + const ui = await $.ui.mount(row(rowProps('Bash', { command }))) + expect(await ui.find({ type: 'Text', text: NOTE })).toBeDefined() + await ui.unmount() +}) + +const DBT_FILES = { + ...CONNECTION_FILES, + [`${ROOT}/dbt_project.yml`]: 'name: acme\nprofile: acme\n', + [`${ROOT}/profiles.yml`]: + 'acme:\n target: dev\n outputs:\n dev:\n type: databricks\n http_path: /sql/1.0/warehouses/wh-classic\n token: "{{ env_var(\'T\') }}"\n other:\n type: databricks\n http_path: /sql/1.0/warehouses/wh-xs\n moved:\n type: databricks\n http_path: "{{ env_var(\'P\') }}"\n', +} + +test('dbt run gets the line through its target\'s warehouse; another target or an unstated path does not', async ($, on) => { + const { clock } = await withFinding($, on, { files: DBT_FILES }) + await $.tool.call({ tool: 'Bash', command: 'dbt run -s orders', tool_use_id: 'dbt-1' } as any) + await $.tool.call({ tool: 'Bash', command: 'dbt build --target other', tool_use_id: 'dbt-2' } as any) + await $.tool.call({ tool: 'Bash', command: 'dbt run -t moved', tool_use_id: 'dbt-3' } as any) + await $.tool.call({ tool: 'Bash', command: 'dbt test', tool_use_id: 'dbt-4' } as any) + await clock.settle() + const lineFor = async (command: string, id: string) => { + const ui = await $.ui.mount(row(rowProps('Bash', { command }, id))) + const found = await ui.find({ type: 'Text', text: NOTE }) + await ui.unmount() + return found + } + expect(await lineFor('dbt run -s orders', 'dbt-1')).toBeDefined() + expect(await lineFor('dbt build --target other', 'dbt-2')).toBeUndefined() + expect(await lineFor('dbt run -t moved', 'dbt-3')).toBeUndefined() + expect(await lineFor('dbt test', 'dbt-4')).toBeUndefined() +}) + +test('a dbt run whose profile is read across a /clear puts no line under its row in the new conversation', async ($, on) => { + let release = () => {} + let holding = false + const held = new Promise(done => (release = done)) + const { clock } = await withFinding($, on, { files: DBT_FILES, readHold: path => (holding && path.endsWith('/dbt_project.yml') ? held : undefined) }) + holding = true + const call = $.tool.call({ tool: 'Bash', command: 'dbt run -s orders', tool_use_id: 'dbt-1' } as any) + await clock.settle() + await $.session.end({ reason: 'clear' } as any) + release() + await call + await clock.settle() + const ui = await $.ui.mount(row(rowProps('Bash', { command: 'dbt run -s orders' }, 'dbt-1'))) + expect(await ui.find({ type: 'Text', text: NOTE })).toBeUndefined() + await ui.unmount() +}) + +test('dbt finds its profile the way dbt does: the flag, the environment, and an exported target', async ($, on) => { + const files = { + ...CONNECTION_FILES, + [`${ROOT}/dbt_project.yml`]: 'name: acme\nprofile: acme\n', + '/conf/profiles.yml': DBT_FILES[`${ROOT}/profiles.yml`]!, + '/env/profiles.yml': DBT_FILES[`${ROOT}/profiles.yml`]!, + } + const { clock } = await withFinding($, on, { files, env: { HOME, DBT_PROFILES_DIR: '/env', DBT_TARGET: 'other' } }) + await $.tool.call({ tool: 'Bash', command: 'dbt run --profiles-dir /conf --target dev', tool_use_id: 'dbt-f' } as any) + // DBT_TARGET in the environment picks `other`, which runs on a warehouse with no finding. + await $.tool.call({ tool: 'Bash', command: 'dbt run', tool_use_id: 'dbt-e' } as any) + await clock.settle() + const flagged = await $.ui.mount(row(rowProps('Bash', { command: 'dbt run --profiles-dir /conf --target dev' }, 'dbt-f'))) + expect(await flagged.find({ type: 'Text', text: NOTE })).toBeDefined() + await flagged.unmount() + const other = await $.ui.mount(row(rowProps('Bash', { command: 'dbt run' }, 'dbt-e'))) + expect(await other.find({ type: 'Text', text: /→ \/savings/ })).toBeUndefined() + await other.unmount() +}) + +test('a connection in the project\'s file replaces the global one of its name', async ($, on) => { + const files = { ...CONNECTION_FILES, [`${ROOT}/.altimate-code/connections.json`]: JSON.stringify({ classic: { type: 'databricks', server_hostname: 'x', http_path: '/sql/1.0/warehouses/wh-xs' } }) } + await withFinding($, on, { files }) + const ui = await $.ui.mount(row(rowProps(SQL_TOOL, { warehouse: 'classic', query: 'select 1' }))) + expect(await ui.find({ type: 'Text', text: /→ \/savings/ })).toBeUndefined() + await ui.unmount() +}) + +test('dbt with --project-dir still takes its default profile from the working folder', async ($, on) => { + const files = { ...DBT_FILES, '/repo/sub/dbt_project.yml': 'name: sub\nprofile: acme\n', '/repo/sub/profiles.yml': 'acme:\n target: dev\n outputs:\n dev:\n type: databricks\n http_path: /sql/1.0/warehouses/wh-xs\n' } + const { clock } = await withFinding($, on, { files }) + await $.tool.call({ tool: 'Bash', command: 'dbt run --project-dir sub', tool_use_id: 'dbt-p' } as any) + await clock.settle() + const ui = await $.ui.mount(row(rowProps('Bash', { command: 'dbt run --project-dir sub' }, 'dbt-p'))) + expect(await ui.find({ type: 'Text', text: NOTE })).toBeDefined() + await ui.unmount() +}) + +test('only the latest dbt rows are remembered', async ($, on) => { + const { clock } = await withFinding($, on, { files: DBT_FILES }) + for (let at = 0; at < 201; at++) await $.tool.call({ tool: 'Bash', command: 'dbt run', tool_use_id: `dbt-many-${at}` } as any) + await clock.settle() + const oldest = await $.ui.mount(row(rowProps('Bash', { command: 'dbt run' }, 'dbt-many-0'))) + expect(await oldest.find({ type: 'Text', text: /→ \/savings/ })).toBeUndefined() + await oldest.unmount() + const newest = await $.ui.mount(row(rowProps('Bash', { command: 'dbt run' }, 'dbt-many-200'))) + expect(await newest.find({ type: 'Text', text: NOTE })).toBeDefined() + await newest.unmount() +}) + +test('dbt after a `cd` on its own line gets no line, though the session\'s project would give one', async ($, on) => { + const { clock } = await withFinding($, on, { files: DBT_FILES }) + await $.tool.call({ tool: 'Bash', command: 'cd other && dbt run', tool_use_id: 'dbt-cd' } as any) + await clock.settle() + const ui = await $.ui.mount(row(rowProps('Bash', { command: 'cd other && dbt run' }, 'dbt-cd'))) + expect(await ui.find({ type: 'Text', text: /→ \/savings/ })).toBeUndefined() + await ui.unmount() +}) + +test('dbt gives no line when the line moves first, or a named profiles folder cannot be read', async ($, on) => { + const { [`${ROOT}/profiles.yml`]: profiles, ...rest } = DBT_FILES + const { clock } = await withFinding($, on, { files: { ...rest, '/inline/profiles.yml': profiles! } }) + await $.tool.call({ tool: 'Bash', command: 'cd other && dbt run', tool_use_id: 'dbt-c' } as any) + await $.tool.call({ tool: 'Bash', command: 'dbt run --profiles-dir /missing', tool_use_id: 'dbt-m' } as any) + await $.tool.call({ tool: 'Bash', command: `DBT_PROFILES_DIR=/inline dbt run`, tool_use_id: 'dbt-i' } as any) + await clock.settle() + for (const [command, id, shown] of [['cd other && dbt run', 'dbt-c', false], ['dbt run --profiles-dir /missing', 'dbt-m', false], [`DBT_PROFILES_DIR=/inline dbt run`, 'dbt-i', true]] as const) { + const ui = await $.ui.mount(row(rowProps('Bash', { command }, id))) + expect(!!(await ui.find({ type: 'Text', text: NOTE }))).toBe(shown) + await ui.unmount() + } +}) + +const groupCall = (tool: string, input: unknown, id: string) => ({ tool_use_id: id, tool, input, isRunning: false, isErrored: false, isInterrupted: false }) +const group = (calls: unknown[], isExpanded = false) => ({ plugin: 'altimate-code', surface: 'terminal', component: 'ToolGroup', props: { calls, isActive: false, isExpanded } }) as any + +test('a run of calls folded into one line gets one note, for the largest finding among them', async ($, on) => { + await withFinding($, on) + const calls = [ + groupCall('Read', { file_path: '/x' }, 'g-1'), + groupCall(SQL_TOOL, { warehouse: 'sfmega', query: 'select 1' }, 'g-2'), + groupCall(SQL_TOOL, { warehouse: 'classic', query: 'select 1' }, 'g-3'), + ] + const ui = await $.ui.mount(group(calls)) + expect(await ui.find({ type: 'Text', text: NOTE })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /COMPUTE_WH/ })).toBeUndefined() + await ui.unmount() +}) + +test('an unfolded group leaves the note to its rows, and a group on no finding gets none', async ($, on) => { + await withFinding($, on) + const unfolded = await $.ui.mount(group([groupCall(SQL_TOOL, { warehouse: 'classic', query: 'select 1' }, 'g-1')], true)) + expect(await unfolded.find({ type: 'Text', text: /→ \/savings/ })).toBeUndefined() + await unfolded.unmount() + const clean = await $.ui.mount(group([groupCall(SQL_TOOL, { warehouse: 'dbxmega', query: 'select 1' }, 'g-1'), groupCall('Read', { file_path: '/x' }, 'g-2')])) + expect(await clean.find({ type: 'Text', text: /→ \/savings/ })).toBeUndefined() + await clean.unmount() +}) + +test('a dbt run folded into a group gets the note through its target', async ($, on) => { + const { clock } = await withFinding($, on, { files: DBT_FILES }) + await $.tool.call({ tool: 'Bash', command: 'dbt run -s orders', tool_use_id: 'dbt-9' } as any) + await clock.settle() + const ui = await $.ui.mount(group([groupCall('Bash', { command: 'dbt run -s orders' }, 'dbt-9')])) + expect(await ui.find({ type: 'Text', text: NOTE })).toBeDefined() + await ui.unmount() +}) + +test('nothing the row hook needs is kept from the connection file but the warehouse', async ($, on) => { + const { store } = await withFinding($, on) + expect(JSON.stringify([...store.entries()])).not.toContain('never-kept') +}) + +// --- Saved since. + +const windowEnding = (end: string) => ({ start: new Date(Date.parse(end) - 7 * 86_400_000).toISOString().slice(0, 10), end }) + +function resizedAnswer(end: string, windowCost: number) { + const answer = JSON.parse(JSON.stringify(ANSWER)) + answer.metadata.window = windowEnding(end) + const classic = answer.metadata.warehouses.find((one: any) => one.id === 'wh-classic') + classic.size = 'X_SMALL' + classic.window_cost = windowCost + answer.metadata.report = { lookback_days: 7, findings: [], total: { monthly_min: 0, monthly_max: 0, resources: 0 }, what_if: [] } + return answer +} + +const FIX_KEY = `savings-fix:project:${ROOT}/dbxmega::sql_warehouse:wh-classic` +const FIX = { date: '2026-11-01', changedSeen: '2026-11-10', checkId: 'wh_oversized', platform: 'databricks', resourceType: 'sql_warehouse', resourceId: 'wh-classic', workspaceId: null, resourceName: 'Classic', title: 'Over-Sized Warehouse', config: { size: 'SMALL', type: 'CLASSIC' }, dailyCost: 3.94 } + +test('Draft the fix keeps the resource, its daily cost and the date; a second press keeps the first', async ($, on) => { + const { clock, store } = await start($, on) + await savings($) + await clock.settle() + const ui = await mountFull($) + await ui.press({ key: 'fix-0' }) + await clock.settle() + const kept = store.get(FIX_KEY) as any + expect(kept).toMatchObject({ date: '2026-11-17', resourceName: 'Classic', config: { size: 'SMALL', type: 'CLASSIC' } }) + expect(Math.abs(kept.dailyCost - 27.544375 / 7)).toBeLessThan(1e-9) + await clock.advance(86_400_000) + await ui.press({ key: 'fix-1' }) + await clock.settle() + expect((store.get(FIX_KEY) as any).date).toBe('2026-11-17') + await ui.unmount() +}) + +test('with no prompt box nothing was drafted, so nothing is kept', async ($, on) => { + const { clock, store } = await start($, on, { canFill: false }) + await savings($) + await clock.settle() + const ui = await mountFull($) + await ui.press({ key: 'fix-0' }) + await clock.settle() + expect(store.has(FIX_KEY)).toBe(false) + await ui.unmount() +}) + +/** An answer with a warehouse of one id in workspaces 111 and 222: 111's resized to X-SMALL at $2 a day, 222's still SMALL at $10 a day. */ +function sharedIdAnswer() { + const answer = resizedAnswer('2026-11-18', 14) + answer.metadata.workspaces_checked = 2 + answer.metadata.warehouses = answer.metadata.warehouses.map((one: any) => ({ ...one, workspace_id: '111' })) + const classic = answer.metadata.warehouses.find((one: any) => one.id === 'wh-classic') + answer.metadata.warehouses.push({ ...classic, workspace_id: '222', size: 'SMALL', window_cost: 70 }) + return answer +} + +test('a drafted fix on a warehouse id two workspaces share is followed on its own workspace\'s warehouse', async ($, on) => { + const key = `savings-fix:project:${ROOT}/dbxmega:222:sql_warehouse:wh-classic` + const store = { [key]: { ...FIX, workspaceId: '222', dailyCost: 10 } } + const { clock } = await start($, on, { now: Date.parse('2026-11-18T10:00:00Z'), answer: sharedIdAnswer(), store }) + await savings($) + await clock.settle() + const ui = await mountFull($) + const texts = ((await ui.findAll({ type: 'Text' })) as any[]).map(one => String(one.text)) + // Workspace 111's resize is not workspace 222's fix: 222's warehouse is still SMALL. + expect(texts.filter(text => /changed to X-SMALL/.test(text))).toEqual([]) + expect(texts.filter(text => text.startsWith('Classic (workspace 222): fix drafted 2026-11-01'))).toEqual([ + 'Classic (workspace 222): fix drafted 2026-11-01, but it is still SMALL CLASSIC: it is no longer flagged, and its size and type did not change, so no saving is claimed.', + ]) + await ui.unmount() +}) + +test('a fix drafted in one workspace is not followed on the other workspace\'s warehouse when a later run reads only that one', async ($, on) => { + const key = `savings-fix:project:${ROOT}/dbxmega:222:sql_warehouse:wh-classic` + // This run reads only workspace 111, whose warehouse of the same id was resized. + const answer = resizedAnswer('2026-11-18', 14) + answer.metadata.workspaces_checked = 1 + answer.metadata.warehouses = answer.metadata.warehouses.map((one: any) => ({ ...one, workspace_id: '111' })) + const { clock } = await start($, on, { now: Date.parse('2026-11-18T10:00:00Z'), answer, store: { [key]: { ...FIX, workspaceId: '222', dailyCost: 10 } } }) + await savings($) + await clock.settle() + const ui = await mountFull($) + const texts = ((await ui.findAll({ type: 'Text' })) as any[]).map(one => String(one.text)) + expect(texts.filter(text => /changed to X-SMALL/.test(text))).toEqual([]) + expect(texts).toContain('Classic: fix drafted 2026-11-01, and this run did not list it, so no amount is claimed.') + await ui.unmount() +}) + +test('Draft the fix on a warehouse id two workspaces share keeps its own workspace\'s cost and size', async ($, on) => { + const answer = sharedIdAnswer() + answer.metadata.report = JSON.parse(JSON.stringify(ANSWER.metadata.report)) + answer.metadata.report.findings = answer.metadata.report.findings.slice(0, 1).map((one: any) => ({ ...one, workspace_id: '222' })) + answer.metadata.report.what_if = [] + answer.metadata.report.total = { monthly_min: answer.metadata.report.findings[0].monthly_min, monthly_max: answer.metadata.report.findings[0].monthly_max, resources: 1 } + const { clock, store } = await start($, on, { now: Date.parse('2026-11-18T10:00:00Z'), answer }) + await savings($) + await clock.settle() + const ui = await mountFull($) + await ui.press({ key: 'fix-0' }) + await clock.settle() + const kept = store.get(`savings-fix:project:${ROOT}/dbxmega:222:sql_warehouse:wh-classic`) as any + expect(kept).toMatchObject({ workspaceId: '222', config: { size: 'SMALL', type: 'CLASSIC' } }) + expect(Math.abs(kept.dailyCost - 70 / 7)).toBeLessThan(1e-9) + await ui.unmount() +}) + +test('the run that first sees a change notes the day, and measuring counts from it', async ($, on) => { + const { date, changedSeen, ...drafted } = FIX + const { clock, store } = await start($, on, { now: Date.parse('2026-11-14T10:00:00Z'), answer: resizedAnswer('2026-11-14', 14), store: { [FIX_KEY]: { ...drafted, date: '2026-11-01' } } }) + await savings($) + await clock.settle() + expect((store.get(FIX_KEY) as any).changedSeen).toBe('2026-11-14') + const ui = await mountFull($) + expect(await ui.find({ type: 'Text', text: /^Classic: fix drafted 2026-11-01 · measuring \(0 of 7 days\)$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /saved since/ })).toBeUndefined() + await ui.unmount() +}) + +test('a changed warehouse is measured while the window still reaches back before the change was seen', async ($, on) => { + const { clock } = await start($, on, { now: Date.parse('2026-11-14T10:00:00Z'), answer: resizedAnswer('2026-11-14', 14), store: { [FIX_KEY]: FIX } }) + await savings($) + await clock.settle() + const ui = await mountFull($) + expect(await ui.find({ type: 'Text', text: /^Classic: fix drafted 2026-11-01 · measuring \(3 of 7 days\)$/ })).toBeDefined() + await ui.unmount() +}) + +test('once the whole window is after the change, its observed spend is stated from billing, never as saved, and replaces the older line', async ($, on) => { + const store = { [FIX_KEY]: FIX, 'savings-baseline:dbxmega:wh-classic': { date: '2026-11-01', config: { size: 'SMALL', type: 'CLASSIC' }, windowCost: 27.54 } } + const { clock } = await start($, on, { now: Date.parse('2026-11-18T10:00:00Z'), answer: resizedAnswer('2026-11-18', 14), store }) + await savings($) + await clock.settle() + const ui = await mountFull($) + expect( + await ui.find({ + type: 'Text', + text: /^Classic: changed to X-SMALL CLASSIC since 2026-11-10: observed spend \$3\.94 a day before, \$2\.00 a day now \(measured from Databricks billing\)\. Billed in different weeks, so a change in workload moves these too: not a measured saving\.$/, + }), + ).toBeDefined() + expect(await ui.find({ type: 'Text', text: /saved/i })).toBeUndefined() + expect(await ui.find({ type: 'Text', text: /→ X-SMALL CLASSIC since/ })).toBeUndefined() + await ui.unmount() +}) + +test('a warehouse that did not change is said to be unchanged, and a change that was undone starts over', async ($, on) => { + const { clock, store } = await start($, on, { now: Date.parse('2026-11-18T10:00:00Z'), store: { [FIX_KEY]: FIX } }) + await savings($) + await clock.settle() + const ui = await mountFull($) + expect(await ui.find({ type: 'Text', text: /^Classic: fix drafted 2026-11-01, but it is still SMALL CLASSIC and still flagged, so no saving is claimed\.$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /saved since/ })).toBeUndefined() + expect((store.get(FIX_KEY) as any).changedSeen).toBeUndefined() + await ui.unmount() +}) + +test('a fix record under another connection, or of another platform, is not read', async ($, on) => { + const store = { + [`savings-fix:project:${ROOT}/dbxmega:extra::sql_warehouse:wh-classic`]: FIX, + [`savings-fix:project:${ROOT}/dbxmega::sql_warehouse:wh-xs`]: { ...FIX, resourceId: 'wh-xs', platform: 'snowflake' }, + } + const { clock } = await start($, on, { store }) + await savings($) + await clock.settle() + const ui = await mountFull($) + expect(await ui.find({ type: 'Text', text: /fix drafted|saved since|did not fall/ })).toBeUndefined() + await ui.unmount() +}) + +test('old fix records and broken ones are dropped at session start, recent ones kept', async ($, on) => { + const { store } = await start($, on, { store: { [FIX_KEY]: { ...FIX, date: '2026-07-01' }, 'savings-fix:x::sql_warehouse:y': 'broken', 'savings-fix:x::sql_warehouse:z': { ...FIX, resourceId: 'z' } } }) + expect(store.has(FIX_KEY)).toBe(false) + expect(store.has('savings-fix:x::sql_warehouse:y')).toBe(false) + expect(store.has('savings-fix:x::sql_warehouse:z')).toBe(true) +}) + +// --- The checks that did not run, the report, and Altimate. + +test('the checks that did not run are named with counts from this run, and one button goes to Altimate', async ($, on) => { + const { clock, opened, runs } = await start($, on) + await savings($) + await clock.settle() + const ui = await mountFull($) + expect(await ui.find({ type: 'Text', text: /^Not run here: 9 more of Altimate's 13 Databricks checks$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^Stale\/Orphaned Warehouse: 3 of 5 SQL warehouses billed nothing in these 7 days, not checked further$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^Undersized Concurrency Capacity: 3,107 queries on CLASSIC not ranked for queueing$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^Hung & Long-Cancelled Job Runs: not read: this run counts only jobs on all-purpose compute, and saw none$/ })).toBeDefined() + await ui.press({ key: 'altimate' }) + await clock.settle() + expect(opened).toEqual([SIGNUP_URL]) + expect(runs.length).toBe(1) + await ui.unmount() +}) + +test('with no browser the Altimate button says where to go', async ($, on) => { + const { clock } = await start($, on, { openExit: 1 }) + await savings($) + await clock.settle() + const ui = await mountFull($) + await ui.press({ key: 'altimate' }) + await clock.settle() + expect(await ui.find({ type: 'Text', text: new RegExp(`Altimate is at ${SIGNUP_URL}`) })).toBeDefined() + await ui.unmount() +}) + +test('Share report writes one local page beside the plugin\'s other reports and opens it', async ($, on) => { + const { clock, opened, written, runs } = await start($, on, { files: { [`${ROOT}/dbt_project.yml`]: 'name: acme\n' } }) + await savings($) + await clock.settle() + const ui = await mountFull($) + await ui.press({ key: 'share' }) + await clock.settle() + const path = `${ROOT}/target/.altimate-lineage/savings-report.html` + expect([...written.keys()]).toEqual([path]) + expect(opened).toEqual([path]) + expect(written.get(path)).toContain('Migrate Classic/Pro to Serverless') + expect(await ui.find({ type: 'Text', text: new RegExp(`^Report opened: ${path}\\. It stays on this machine until you send it\\.$`) })).toBeDefined() + expect(runs.length).toBe(1) + await ui.unmount() +}) + +for (const button of ['share', 'altimate'] as const) { + test(`${button === 'share' ? 'Share report' : 'See every check in Altimate'} whose browser opens across a /clear says nothing in the new conversation`, async ($, on) => { + let release = () => {} + const openHold = new Promise(done => (release = done)) + // No browser: the sign-up button speaks only then. + const { clock, opened } = await start($, on, { files: { [`${ROOT}/dbt_project.yml`]: 'name: acme\n' }, openHold, openExit: 1 }) + await savings($) + await clock.settle() + let ui = await mountFull($) + await ui.press({ key: button }) + await clock.settle() + await ui.unmount() + await $.session.end({ reason: 'clear' } as any) + release() + await clock.settle() + expect(opened).toHaveLength(1) + ui = await mountFull($) + expect(await ui.find({ type: 'Text', text: /^Report opened|^No browser could be opened|^The report could not be written/ })).toBeUndefined() + await ui.unmount() + }) +} + +test('a report that cannot be written says why on one line, without the error\'s control characters', async ($, on) => { + const { clock, written } = await start($, on, { files: { [`${ROOT}/dbt_project.yml`]: 'name: acme\n' }, writeRejects: 'EACCES\u001b[2J: permission\u0007 denied\nat write' }) + await savings($) + await clock.settle() + const ui = await mountFull($) + await ui.press({ key: 'share' }) + await clock.settle() + expect(written.size).toBe(0) + const said = ((await ui.findAll({ type: 'Text', text: /^The report could not be written: / })) as any[]).map(one => String(one.text)) + expect(said.length).toBe(1) + expect(said[0]).toContain('permission denied at write') + expect(said[0]).not.toMatch(/[\u0000-\u001f\u007f]/) + await ui.unmount() +}) + +test('outside a dbt project the report goes in altimate-code\'s folder, and no browser is not an error', async ($, on) => { + const { clock, written } = await start($, on, { env: { HOME }, openExit: 1 }) + await savings($) + await clock.settle() + const ui = await mountFull($) + await ui.press({ key: 'share' }) + await clock.settle() + expect([...written.keys()]).toEqual([`${HOME}/.altimate-code/savings-report.html`]) + expect(await ui.find({ type: 'Text', text: /^No browser could be opened\. Report: / })).toBeDefined() + await ui.unmount() +}) + +test('before any answer there is nothing to share', async ($, on) => { + await start($, on) + const ui = await mountFull($) + expect(await ui.find({ key: 'share' })).toBeUndefined() + expect(await ui.find({ key: 'altimate' })).toBeUndefined() + await ui.unmount() +}) + +// --- Both platforms. + +test('with both platforms /savings runs each tool once and draws a section for each', async ($, on) => { + const { clock, runs, snowflakeRuns, toasts, statuses, store } = await start($, on, { list: BOTH }) + const said = await savings($) + expect(said.text).toContain('your own connections') + await clock.settle() + expect(runs.length).toBe(1) + expect(snowflakeRuns.length).toBe(1) + expect(JSON.parse(snowflakeRuns[0]!.argv[5]!)).toEqual({ confirm: true }) + expect(snowflakeRuns[0]!.env).toEqual({ ALTIMATE_TELEMETRY_DISABLED: 'true', ALTIMATE_ASSESSMENT_MODE: 'true' }) + expect(toasts.at(-1)).toBe('Databricks savings check: $80.64–$101 a month on 1 resource. Snowflake savings check: $54.00–$90.00 a month on 1 resource.') + expect(lastStatus(statuses)).toBe('⚡ Altimate · $135–$191/mo to save · /savings') + expect([...store.keys()].filter(key => key.startsWith('savings-report:')).sort()).toEqual([KEPT_KEY, `savings-report:${HERE}/sfmega`]) + const ui = await mountFull($) + expect(await ui.find({ type: 'Text', text: /^Databricks savings check$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^Snowflake savings check$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^3 warehouses · the 7 days to 2026-11-18 · connection sfmega$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^BI_WH · Downsize Warehouse · \$54\.00–\$90\.00 a month$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^BI_WH · Underutilized Cluster · no dollar estimate$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /at your account's \$3\.00 a credit and the last 7 days' rate.*; 1 more with no dollar estimate$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^Not run here: 7 more of Altimate's 11 Snowflake checks$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^High auto suspend: 3 warehouses: auto-suspend setting not read$/ })).toBeDefined() + // Each finding keeps its own button across the sections. + expect(await ui.find({ key: 'fix-5' })).toBeDefined() + await ui.unmount() +}) + +test('each kind of Snowflake finding says what it rests on, and what to change', async ($, on) => { + const { clock, fills } = await start($, on, { list: BOTH }) + await savings($, 'sfmega') + await clock.settle() + const ui = await mountFull($) + expect(await ui.find({ type: 'Text', text: /^Large could be Medium: 95\.0% of its active periods lasted 80 seconds or less; 91\.5% of 1,200 queries ran in 5 seconds or less$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^60% idle on 2 days above 40%: 2\.0 of 3\.3 active hours$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^12 suspend-and-resume bounces inside a billed minute on 1 day$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^The highest of its 2 clusters was barely needed on 1 day \(up to 70% idle\)$/ })).toBeDefined() + for (const key of ['fix-0', 'fix-1', 'fix-2', 'fix-3']) await ui.press({ key }) + await clock.settle() + expect(fills[0]).toContain('Draft the change for this Snowflake savings finding') + expect(fills[0]).toContain("$54.00–$90.00 a month at your account's $3.00 a credit.") + expect(fills[0]).toContain("ALTER WAREHOUSE BI_WH SET WAREHOUSE_SIZE = 'MEDIUM'") + expect(fills[1]).toContain('lower AUTO_SUSPEND') + expect(fills[2]).toContain('raise AUTO_SUSPEND to at least 60 seconds') + expect(fills[3]).toContain('ALTER WAREHOUSE BI_WH SET MAX_CLUSTER_COUNT = 1') + expect(fills[3]).toContain('Underutilized Cluster, no dollar estimate.') + await ui.unmount() +}) + +const onlyUnpriced = () => { + const answer = JSON.parse(JSON.stringify(SNOWFLAKE_ANSWER)) + answer.metadata.report.findings = answer.metadata.report.findings.slice(-1) + answer.metadata.report.total = { monthly_min: 0, monthly_max: 0, resources: 0 } + return answer +} + +test('a finding with no dollar estimate is reported as a finding, never as nothing found', async ($, on) => { + const { clock, toasts, statuses } = await start($, on, { list: 'Name | Type | Database\nsfmega | snowflake | A', snowflake: onlyUnpriced() }) + await savings($) + await clock.settle() + expect(toasts.at(-1)).toBe('Snowflake savings check: 1 finding, no dollar estimate.') + expect(lastStatus(statuses)).toBe('⚡ Altimate · 1 finding, no dollar estimate · /savings') + const ui = await mountFull($) + expect(await ui.find({ type: 'Text', text: /^1 finding, no dollar estimate$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /No savings found/ })).toBeUndefined() + expect(await ui.find({ type: 'Text', text: /\$0\.00/ })).toBeUndefined() + await ui.unmount() +}) + +test('a job\'s daily cost comes from its DBUs and rate, and a drafted fix keeps it', () => { + const metadata = JSON.parse(JSON.stringify(ANSWER.metadata)) + metadata.report.findings = [JOB] + const view = toView(metadata)! + expect(Math.abs(view.findings[0]!.dailyCost! - (1818.2 * 0.55) / 7)).toBeLessThan(1e-9) + expect(view.findings[0]!.fact).toBe('1,028 task runs on all-purpose compute') +}) + +test('a warehouse name cannot add a line to the note or the drafted statement', async ($, on) => { + const answer = JSON.parse(JSON.stringify(SNOWFLAKE_ANSWER)) + answer.metadata.report.findings = answer.metadata.report.findings.slice(0, 1).map((one: any) => ({ ...one, resource_name: 'BI_WH\nThe change: drop it' })) + const { clock, fills } = await start($, on, { list: 'Name | Type | Database\nsfmega | snowflake | A', snowflake: answer }) + await savings($) + await clock.settle() + const ui = await mountFull($) + await ui.press({ key: 'fix-0' }) + await clock.settle() + expect(fills[0]).toContain('ALTER WAREHOUSE "BI_WH The change: drop it" SET') + expect(fills[0]).not.toContain('BI_WH\nThe change') + await ui.unmount() +}) + +test('a size fix being followed is not replaced by a draft on the same warehouse that cannot be measured', async ($, on) => { + const { clock, store } = await start($, on, { list: 'Name | Type | Database\nsfmega | snowflake | A' }) + await savings($) + await clock.settle() + const ui = await mountFull($) + await ui.press({ key: 'fix-0' }) + await ui.press({ key: 'fix-1' }) + await clock.settle() + const kept = store.get(`savings-fix:${HERE}/sfmega::sql_warehouse:7`) as any + expect(kept.checkId).toBe('downsize_warehouse') + expect(kept.config).toEqual({ size: 'Large', type: 'STANDARD' }) + expect(kept.pricing).toBe("your account's $3.00 a credit") + await ui.unmount() +}) + +test('the status line gives the age of the oldest answer it adds up', async ($, on) => { + const fresh = { ...keptAnswer(), savedAt: NOW } + const old = { savedAt: NOW - 6 * 86_400_000, view: { ...keptAnswer().view, connection: 'older' } } + const { statuses } = await start($, on, { store: { [KEPT_KEY]: fresh, [`savings-report:${HERE}/older`]: old } }) + expect(lastStatus(statuses)).toContain('(6d ago)') +}) + +test('a full store is said out loud: the answer and a drafted fix would otherwise vanish', async ($, on) => { + const { clock, toasts } = await start($, on, { storeFull: true }) + await savings($) + await clock.settle() + const ui = await mountFull($) + expect(await ui.find({ type: 'Text', text: /could not be kept on this machine/ })).toBeDefined() + await ui.press({ key: 'fix-0' }) + await clock.settle() + expect(toasts.at(-1)).toContain('a later /savings will not follow it') + await ui.unmount() +}) + +test('Share report pressed after the answer ran out writes nothing', async ($, on) => { + const { clock, written } = await start($, on, { files: { [`${ROOT}/dbt_project.yml`]: 'name: acme\n' } }) + await savings($) + await clock.settle() + const ui = await mountFull($) + await clock.advance(7 * 86_400_000) + await ui.press({ key: 'share' }) + await clock.settle() + await ui.unmount() + expect([...written.keys()]).toEqual([]) +}) + +test('the band\'s Run button pressed twice starts one run', async ($, on) => { + const options: Options = { files: { [`${ROOT}/infra/w.tf`]: 'resource "databricks_sql_endpoint" "x" { name = "Classic" }' } } + const { clock, runs } = await start($, on, options) + await savings($) + await clock.settle() + await $.tool.call({ tool: 'Edit', file_path: `${ROOT}/infra/w.tf`, old_string: 'x', new_string: 'x' }) + await clock.settle() + let release = () => {} + options.hold = new Promise(done => (release = done)) + const band = await $.ui.mount(BAND) + await Promise.all([band.press({ key: 'savings-run' }), band.press({ key: 'savings-run' })]) + await clock.settle() + expect(runs.length).toBe(2) + release() + await clock.settle() + await band.unmount() +}) + +test('after /clear during a pressed run, Run again works at once', async ($, on) => { + const options: Options = {} + const { clock, runs } = await start($, on, options) + await savings($) + await clock.settle() + let release = () => {} + options.hold = new Promise(done => (release = done)) + const ui = await mountFull($) + await ui.press({ key: 'again' }) + await clock.settle() + await $.session.end({ reason: 'clear' } as any) + await clock.settle() + options.hold = undefined + await showAll(ui) + await ui.press({ key: 'again' }) + await clock.settle() + expect(runs.length).toBe(3) + release() + await clock.settle() + await ui.unmount() +}) + +test('a finding past its seven days no longer reaches the band', async ($, on) => { + const { clock } = await start($, on, { files: { [`${ROOT}/infra/w.tf`]: 'resource "databricks_sql_endpoint" "x" { name = "Classic" }' } }) + await savings($) + await clock.settle() + await clock.advance(7 * 86_400_000) + await $.tool.call({ tool: 'Edit', file_path: `${ROOT}/infra/w.tf`, old_string: 'x', new_string: 'x' }) + await clock.settle() + const band = await $.ui.mount(BAND) + expect(await band.find({ type: 'Text', text: /^Classic: / })).toBeUndefined() + await band.unmount() +}) + +test('Run again pressed again while its run is going starts no second one', async ($, on) => { + const options: Options = {} + const { clock, runs } = await start($, on, options) + await savings($) + await clock.settle() + let release = () => {} + options.hold = new Promise(done => (release = done)) + const ui = await mountFull($) + // Both presses land before the pane redraws without its buttons. + await Promise.all([ui.press({ key: 'again' }), ui.press({ key: 'again' })]) + await clock.settle() + expect(runs.length).toBe(2) + release() + await clock.settle() + await ui.unmount() +}) + +test('before the connections are known, /savings names no platform', async ($, on) => { + const { clock } = await start($, on) + const said = await savings($) + expect(said.text).toBe('Running the savings check in the side pane: read-only queries on your own connection. Nothing is sent to Altimate.') + await clock.settle() +}) + +test('a connection list that failed is not read as having no connections', async ($, on) => { + const options: Options = { list: BOTH } + const { clock, snowflakeRuns } = await start($, on, options) + options.listError = 'config unreadable' + await savings($) + await clock.settle() + expect(snowflakeRuns.length).toBe(1) +}) + +test('a number in a config file is not taken for a Snowflake warehouse or a job', async ($, on) => { + const files = { [`${ROOT}/infra/w.tf`]: 'resource "databricks_sql_endpoint" "other" {\n name = "other"\n min_num_clusters = 7\n}\n' } + const { clock } = await start($, on, { list: 'Name | Type | Database\nsfmega | snowflake | A', files }) + await savings($) + await clock.settle() + await $.tool.call({ tool: 'Edit', file_path: `${ROOT}/infra/w.tf`, old_string: 'other', new_string: 'other' }) + await clock.settle() + const band = await $.ui.mount(BAND) + expect(await band.find({ type: 'Text', text: /BI_WH/ })).toBeUndefined() + await band.unmount() +}) + +const CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f\u200b]/ + +/** Every text and button a mounted drawing shows. */ +async function drawnTexts(ui: any): Promise { + const found = [...(await ui.findAll({ type: 'Text' })), ...(await ui.findAll({ type: 'Button' }))] + return found.map((one: any) => String(one.text ?? one.props?.label ?? '')) +} + +test('a control character in a name, reason, failure or connection never reaches the pane', async ($, on) => { + const answer = JSON.parse(JSON.stringify(SNOWFLAKE_ANSWER)) + answer.metadata.warehouse = 'sf\u001b[2Jmega' + answer.metadata.report.findings[0].resource_name = 'BI\u001b[2J\u200b_WH' + answer.metadata.report.findings[0].title = 'Downsize\u0007 Warehouse' + answer.metadata.skipped = [{ check: 'Frequent Restart\u001b Overcharge', reason: 'driver\u001b[31m said no' }] + const failed = failure('connect\u001b[31m refused\u0007') + const { clock, toasts, statuses } = await start($, on, { list: BOTH, snowflake: answer, answer: failed }) + await savings($) + await clock.settle() + const ui = await mountFull($) + const texts = await drawnTexts(ui) + expect(texts.length).toBeGreaterThan(5) + expect(texts.filter(text => CONTROL.test(text))).toEqual([]) + expect(texts.some(text => text.includes('connection sf [2Jmega'))).toBe(true) + expect(texts.some(text => text.includes('The savings check failed: connect [31m refused'))).toBe(true) + expect(texts.some(text => text.includes('driver [31m said no'))).toBe(true) + expect(toasts.filter(text => CONTROL.test(text))).toEqual([]) + expect(statuses.filter(text => text && CONTROL.test(text))).toEqual([]) + await ui.unmount() +}) + +test('a kept answer holding a control character is drawn clean in the pane and the note', async ($, on) => { + const dirty = keptAnswer() + dirty.view.findings = dirty.view.findings.map(one => ({ ...one, resourceName: 'Cla\u001b[2Jssic', evidence: ['a\u0007b'] })) + const files = { [`${HOME}/.altimate-code/connections.json`]: JSON.stringify({ dbxmega: { type: 'databricks', http_path: '/sql/1.0/warehouses/wh-classic' } }) } + await start($, on, { list: DATABRICKS_ONLY, env: { HOME }, files, store: { [KEPT_KEY]: dirty } }) + const note = await $.ui.mount(row(rowProps(SQL_TOOL, { warehouse: 'dbxmega', query: 'select 1' }))) + expect(await note.find({ type: 'Text', text: /^ {2}⎿ {2}Cla \[2Jssic: 95% idle · / })).toBeDefined() + await note.unmount() + const ui = await mountFull($) + expect((await drawnTexts(ui)).filter(text => CONTROL.test(text))).toEqual([]) + await ui.unmount() +}) + +test('matching keeps the name as the warehouse spells it, whatever is shown', async ($, on) => { + const raw = 'BI\u200b_WH' + const answer = JSON.parse(JSON.stringify(SNOWFLAKE_ANSWER)) + answer.metadata.report.findings[0].resource_name = raw + const files = { [`${HOME}/.altimate-code/connections.json`]: JSON.stringify({ sfmega: { type: 'snowflake', account: 'a', warehouse: raw } }), [`${ROOT}/infra/w.tf`]: `resource "databricks_sql_endpoint" "x" {\n name = "${raw}"\n}\n` } + const { clock } = await start($, on, { list: 'Name | Type | Database\nsfmega | snowflake | A', snowflake: answer, env: { HOME }, files }) + await savings($) + await clock.settle() + const note = await $.ui.mount(row(rowProps(SQL_TOOL, { warehouse: 'sfmega', query: 'select 1' }))) + expect(await note.find({ type: 'Text', text: /^ {2}⎿ {2}BI_WH: Large could be Medium/ })).toBeDefined() + await note.unmount() + await $.tool.call({ tool: 'Edit', file_path: `${ROOT}/infra/w.tf`, old_string: 'x', new_string: 'x' }) + await clock.settle() + const band = await $.ui.mount(BAND) + expect(await band.find({ type: 'Text', text: /^BI_WH: Downsize Warehouse, / })).toBeDefined() + await band.unmount() +}) + +test('names and reasons from the answer cannot blank the pane or the note', async ($, on) => { + const answer = JSON.parse(JSON.stringify(SNOWFLAKE_ANSWER)) + answer.metadata.report.findings[0].resource_name = 'BI\u001b[2J_WH' + answer.metadata.warehouses[0].name = 'BI\u001b[2J_WH' + answer.metadata.skipped = [{ check: 'Frequent Restart Overcharge', reason: 'bad\u0007\nthing' }] + answer.metadata.limited = ['active\u001b periods'] + const { clock } = await start($, on, { list: BOTH, env: { HOME }, files: CONNECTION_FILES, snowflake: answer }) + await savings($, 'sfmega') + await clock.settle() + const ui = await mountFull($) + expect(await ui.find({ type: 'Text', text: /^BI \[2J_WH · Downsize Warehouse · / })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^Not checked: Frequent Restart Overcharge \(bad thing\)\.$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /rows of active periods were read/ })).toBeDefined() + await ui.unmount() +}) + +test('under WSL the Altimate address is opened as an address, not turned into a Windows path', async ($, on) => { + const { clock, opened } = await start($, on, { uname: 'Linux 5.15-microsoft-standard' }) + await savings($) + await clock.settle() + const ui = await mountFull($) + await ui.press({ key: 'altimate' }) + await clock.settle() + expect(opened).toEqual([`wslview ${SIGNUP_URL}`]) + await ui.unmount() +}) + +test('under WSL without wslview the Altimate address goes to explorer.exe as it is', async ($, on) => { + const { clock, opened } = await start($, on, { uname: 'Linux 5.15-microsoft-standard', noWslview: true }) + await savings($) + await clock.settle() + const ui = await mountFull($) + await ui.press({ key: 'altimate' }) + await clock.settle() + expect(opened).toEqual([`explorer.exe ${SIGNUP_URL}`]) + await ui.unmount() +}) + +test('/savings with a name the connection list does not hold runs no check, and names the ones it has', async ($, on) => { + const { clock, runs, snowflakeRuns, toasts } = await start($, on, { list: BOTH }) + await savings($, 'sf_prod') + await clock.settle() + expect(runs).toEqual([]) + expect(snowflakeRuns).toEqual([]) + expect(toasts.at(-1)).toBe('Savings check: altimate-code has no connection named sf_prod. Run /savings for every connection, or /savings with one of: dbxmega, classic, sfmega, sfother.') +}) + +test('/savings with a listed connection of another kind runs no check and says what it is not', async ($, on) => { + const { clock, runs, snowflakeRuns, toasts } = await start($, on, { list: BOTH }) + await savings($, 'scratch') + await clock.settle() + expect(runs).toEqual([]) + expect(snowflakeRuns).toEqual([]) + expect(toasts.at(-1)).toBe("Savings check: altimate-code's connection scratch is neither a Databricks nor a Snowflake one. Run /savings for every connection, or /savings with one of: dbxmega, classic, sfmega, sfother.") +}) + +test('a name missing from the list read at session start still runs when this run cannot read the list', async ($, on) => { + const options: any = { list: DATABRICKS_ONLY } + const { clock, runs } = await start($, on, options) + // The connection was added after the session started, and this run's list read fails. + options.listError = 'Failed to list warehouses' + await savings($, 'newdbx') + await clock.settle() + expect(runs.length).toBe(1) + expect(runs[0]!.argv.join(' ')).toContain('newdbx') +}) + +test('without altimate-code, with both kinds of connection, the install message names neither one', async ($, on) => { + const { clock, toasts } = await start($, on, { list: BOTH, missingCli: true }) + await savings($) + await clock.settle() + const ui = await mountFull($) + expect(await ui.find({ type: 'Text', text: /add a Databricks or Snowflake connection, then run \/savings again\.$/ })).toBeDefined() + await ui.unmount() + expect(toasts.at(-1)).toMatch(/^Savings check: altimate-code is not installed\./) +}) + +test('a connection the list could not tell the kind of, refused as not Databricks, is not sent to a Databricks one', async ($, on) => { + const { clock } = await start($, on, { answer: failure('The Databricks savings check is not available for snowflake warehouses. Try one of: dbx.') }) + await savings($, 'sf_prod') + await clock.settle() + const ui = await mountFull($) + expect(await ui.find({ type: 'Text', text: /^That connection is not a Databricks one, and altimate-code's connection list could not be read to tell its kind\.$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^Run \/savings with no connection to check each of yours/ })).toBeDefined() + await ui.unmount() +}) + +test('"already running" names the check that is running, not the one just asked for', async ($, on) => { + let finish = () => {} + const { clock, runs } = await start($, on, { list: BOTH, hold: new Promise(resolve => (finish = resolve)) }) + await savings($, 'dbxmega') + await clock.settle() + expect(runs.length).toBe(1) + expect((await savings($, 'sfmega')).text).toBe('The Databricks savings check is already running in the side pane. Run /savings sfmega again when it finishes.') + finish() + await clock.settle() +}) + +test('a warehouse name that is no plain identifier is quoted in the drafted statement', async ($, on) => { + const answer = JSON.parse(JSON.stringify(SNOWFLAKE_ANSWER)) + answer.metadata.report.findings = answer.metadata.report.findings.slice(0, 1).map((one: any) => ({ ...one, resource_name: 'my "wh"' })) + const { clock, fills } = await start($, on, { list: 'Name | Type | Database\nsfmega | snowflake | A', snowflake: answer }) + await savings($) + await clock.settle() + const ui = await mountFull($) + await ui.press({ key: 'fix-0' }) + await clock.settle() + expect(fills[0]).toContain(`ALTER WAREHOUSE "my ""wh""" SET WAREHOUSE_SIZE = 'MEDIUM'`) + await ui.unmount() +}) + +test('a version-gate refusal before the connection list is read is filed under no platform in the report', async ($, on) => { + const options: any = { files: { [`${ROOT}/dbt_project.yml`]: 'name: acme\n' } } + const { clock, written } = await start($, on, options) + await savings($) + await clock.settle() + options.version = '0.12.11' + await savings($) + await clock.settle() + const ui = await mountFull($) + await ui.press({ key: 'share' }) + await clock.settle() + const page = [...written.values()].at(-1)! + expect(page).toContain('The last check did not finish: This altimate-code has no savings check.') + expect(page).not.toContain('The last Databricks check did not finish') + await ui.unmount() +}) + +test('a version-gate refusal for a name the list read at session start lacks names no platform', async ($, on) => { + const options: any = { list: BOTH } + const { clock, toasts } = await start($, on, options) + options.version = '0.12.11' + await savings($, 'newsf') + await clock.settle() + expect(toasts.at(-1)).toMatch(/^Savings check: This altimate-code has no savings check\. /) +}) + +test('a failure for a name the list read at session start lacks names no platform', async ($, on) => { + const options: any = { list: BOTH } + const { clock, toasts } = await start($, on, options) + options.missingCli = true + await savings($, 'newsf') + await clock.settle() + expect(toasts.at(-1)).toMatch(/^Savings check: altimate-code is not installed\. Install it .*, add a Databricks or Snowflake connection/) +}) + +test('the shared report names a platform that could not be checked', async ($, on) => { + const missing = { status: 'error', title: 'Unknown tool', output: 'Unknown tool: finops_snowflake_savings. Run it', metadata: {} } + const { clock, written } = await start($, on, { list: BOTH, snowflake: missing, files: { [`${ROOT}/dbt_project.yml`]: 'name: acme\n' } }) + await savings($) + await clock.settle() + const ui = await mountFull($) + await ui.press({ key: 'share' }) + await clock.settle() + expect([...written.values()][0]).toContain('The last Snowflake check did not finish: This altimate-code has no Snowflake savings check.') + await ui.unmount() +}) + +test('a Snowflake answer with its checks skipped claims nothing wider than what ran', async ($, on) => { + const answer = JSON.parse(JSON.stringify(SNOWFLAKE_ANSWER)) + answer.metadata.report = { lookback_days: 7, price_per_credit: 3, findings: [], total: { monthly_min: 0, monthly_max: 0, resources: 0 }, what_if: [] } + answer.metadata.skipped = [{ check: 'High Idle Time, Underutilized Cluster and the short-period signal of Downsize Warehouse', reason: 'Insufficient privileges' }, { check: '3 warehouses that billed credits', reason: "the connection's role cannot list A" }] + answer.metadata.limited = ['active periods'] + const { clock, statuses } = await start($, on, { list: 'Name | Type | Database\nsfmega | snowflake | A', snowflake: answer }) + await savings($) + await clock.settle() + expect(lastStatus(statuses)).toBe('⚡ Altimate · nothing found by the checks that ran · /savings') + const ui = await mountFull($) + expect(await ui.find({ type: 'Text', text: /^No savings found by the checks that ran\.$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^Not checked: High Idle Time, .*\(Insufficient privileges\); 3 warehouses that billed credits \(/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^Only the first 100,000 rows of active periods were read; any beyond them were not checked\.$/ })).toBeDefined() + await ui.unmount() +}) + +test('a Snowflake finding gets the note under a tool row, in its own account only', async ($, on) => { + await withFinding($, on) + const ui = await $.ui.mount(row(rowProps(SQL_TOOL, { warehouse: 'sfmega', query: 'select 1' }))) + expect(await ui.find({ type: 'Text', text: /^ {2}⎿ {2}BI_WH: Large could be Medium · \$54\.00–\$90\.00 a month → \/savings$/ })).toBeDefined() + await ui.unmount() + // Another account's warehouse of the same name has no kept finding. + const other = await $.ui.mount(row(rowProps(SQL_TOOL, { warehouse: 'sfother', query: 'select 1' }))) + expect(await other.find({ type: 'Text', text: /→ \/savings/ })).toBeUndefined() + await other.unmount() +}) + +test('the Snowflake tool\'s live answer is drawn as it is: its total, evidence, price and note', async ($, on) => { + const files = { [`${HOME}/.altimate-code/connections.json`]: JSON.stringify({ snowflake: { type: 'snowflake', account: 'acct', warehouse: 'COMPUTE_WH' } }) } + const { clock, toasts, statuses, fills } = await start($, on, { list: 'Name | Type | Database\nsnowflake | snowflake | A', snowflake: SNOWFLAKE_CAPTURE, env: { HOME }, files }) + await savings($) + await clock.settle() + expect(toasts.at(-1)).toBe('Snowflake savings check: $342–$489 a month on 7 resources.') + expect(lastStatus(statuses)).toBe('⚡ Altimate · $342–$489/mo to save · /savings') + const ui = await mountFull($) + expect(await ui.find({ type: 'Text', text: /^69 warehouses · the 7 days to 2026-11-18 · connection snowflake$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^on 7 resources, at your account's \$3\.00 a credit and the last 7 days' rate/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^DBT_INTEGRATION_TEST_WH · High Idle Time · \$197–\$281 a month$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^90% idle on 5 days above 40%: 12\.2 of 13\.5 active hours$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^180 suspend-and-resume bounces inside a billed minute on 5 days$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^2,456 seconds billed twice at 1 credit an hour$/ })).toBeDefined() + // Short active times are in the unit they fill, not "0.3 of 0.3 active hours". + expect(await ui.find({ type: 'Text', text: /^94% idle on 5 days above 40%: 19 of 20 active minutes$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^High auto suspend: 69 warehouses: auto-suspend setting not read$/ })).toBeDefined() + await ui.press({ key: 'fix-0' }) + await clock.settle() + expect(fills[0]).toContain('ALTER WAREHOUSE DBT_INTEGRATION_TEST_WH SET AUTO_SUSPEND = 60') + await ui.unmount() + const note = await $.ui.mount(row(rowProps(SQL_TOOL, { warehouse: 'snowflake', query: 'select 1' }))) + expect(await note.find({ type: 'Text', text: /^ {2}⎿ {2}COMPUTE_WH: 59% idle · \$21\.30–\$30\.43 a month → \/savings$/ })).toBeDefined() + await note.unmount() +}) + +test('one platform failing does not lose the other, and says why', async ($, on) => { + const missing = { status: 'error', title: 'Unknown tool', output: 'Unknown tool: finops_snowflake_savings. Run `altimate-code tool list` to see the available tools.', metadata: {} } + const { clock } = await start($, on, { list: BOTH, snowflake: missing }) + await savings($) + await clock.settle() + const ui = await mountFull($) + expect(await ui.find({ type: 'Text', text: /^This altimate-code has no Snowflake savings check\.$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^\$80\.64–\$101 a month$/ })).toBeDefined() + await ui.unmount() +}) + +test('/savings checks only that connection, on its own platform', async ($, on) => { + const { clock, runs, snowflakeRuns } = await start($, on, { list: BOTH }) + await savings($, 'sfmega') + await clock.settle() + expect(runs).toEqual([]) + expect(JSON.parse(snowflakeRuns[0]!.argv[5]!)).toEqual({ warehouse: 'sfmega', confirm: true }) +}) + +test('a connection added since the session started is checked', async ($, on) => { + const options: Options = { list: DATABRICKS_ONLY } + const { clock, snowflakeRuns } = await start($, on, options) + options.list = BOTH + await savings($) + await clock.settle() + expect(snowflakeRuns.length).toBe(1) +}) + +test('a subagent working on its own does not hold a finished run\'s notice back', async ($, on) => { + const { clock, toasts } = await start($, on) + await $.turn.start({ text: 'sub', turnId: 's1', agentId: 'a1' } as any) + await savings($) + await clock.settle() + expect(toasts.at(-1)).toBe('Databricks savings check: $80.64–$101 a month on 1 resource.') +}) + +test('the next run after a draft says it is measuring, and that nothing has changed yet', async ($, on) => { + const { clock } = await start($, on) + await savings($) + await clock.settle() + const ui = await mountFull($) + await ui.press({ key: 'fix-0' }) + await clock.settle() + await ui.press({ key: 'again' }) + await clock.settle() + await showAll(ui) + expect(await ui.find({ type: 'Text', text: /^Classic: fix drafted 2026-11-17 · measuring \(0 of 7 days\): still SMALL CLASSIC, no change seen yet$/ })).toBeDefined() + await ui.unmount() +}) + +test('a subagent finishing is not the turn ending, and notices held meanwhile all arrive', async ($, on) => { + const { clock, toasts } = await start($, on) + await $.turn.start({ text: 'go', turnId: 't1' } as any) + await savings($) + await clock.settle() + const ui = await mountFull($) + await ui.press({ key: 'fix-0' }) + await clock.settle() + await ui.unmount() + await $.turn.start({ text: 'sub', turnId: 's1', agentId: 'a1' } as any) + await $.turn.complete({ answer: 'sub done', durationMs: 5, isAborted: false, reason: 'answer', turnId: 's1', agentId: 'a1' } as any) + expect(toasts).toEqual([]) + await $.turn.complete({ answer: 'done', durationMs: 5, isAborted: false, reason: 'answer', turnId: 't1' } as any) + expect(toasts.length).toBe(1) + expect(toasts[0]).toContain('$80.64–$101 a month on 1 resource.') + expect(toasts[0]).toContain('in your prompt box') +}) + +test('an answer that passes seven days during a session stops being shown', async ($, on) => { + const { clock, statuses } = await start($, on, { list: BOTH, env: { HOME }, files: CONNECTION_FILES }) + await savings($) + await clock.settle() + await clock.advance(7 * 86_400_000) + await $.turn.start({ text: 'later', turnId: 't9' } as any) + expect(lastStatus(statuses)).toBe('⚡ Altimate · Databricks + Snowflake · /savings') + const note = await $.ui.mount(row(rowProps(SQL_TOOL, { warehouse: 'classic', query: 'select 1' }))) + expect(await note.find({ type: 'Text', text: /→ \/savings/ })).toBeUndefined() + await note.unmount() + const ui = await mountFull($) + expect(await ui.find({ type: 'Text', text: /a month$/ })).toBeUndefined() + await ui.unmount() +}) + +test('while Claude is working a finished run raises no notice; it comes when the turn ends', async ($, on) => { + const { clock, toasts, statuses } = await start($, on) + await $.turn.start({ text: 'go', turnId: 't1' } as any) + await savings($) + await clock.settle() + expect(toasts).toEqual([]) + expect(lastStatus(statuses)).toContain('$80.64–$101/mo to save') + await $.turn.complete({ answer: 'done', durationMs: 5, isAborted: false, reason: 'answer', turnId: 't1' } as any) + expect(toasts).toEqual(['Databricks savings check: $80.64–$101 a month on 1 resource.']) +}) + +// --- The slim view: the largest findings first, the rest behind Show all. + +/** A Databricks answer whose findings are these, each its own warehouse. */ +const databricksWith = (findings: { name: string; min: number; max: number }[]) => { + const answer = JSON.parse(JSON.stringify(ANSWER)) + const base = answer.metadata.report.findings[0] + answer.metadata.report.findings = findings.map((one, at) => ({ ...base, resource_id: `wh-d${at}`, resource_name: one.name, monthly_min: one.min, monthly_max: one.max })) + answer.metadata.report.what_if = [] + answer.metadata.report.total = { monthly_min: 0, monthly_max: 0, resources: 0 } + return answer +} + +/** A Snowflake answer whose findings are these, each its own warehouse. */ +const snowflakeWith = (findings: { name: string; min: number; max: number }[]) => { + const answer = JSON.parse(JSON.stringify(SNOWFLAKE_ANSWER)) + const base = answer.metadata.report.findings[1] + answer.metadata.report.findings = findings.map((one, at) => ({ ...base, resource_id: `s${at}`, resource_name: one.name, monthly_min: one.min, monthly_max: one.max })) + answer.metadata.report.total = { monthly_min: 0, monthly_max: 0, resources: 0 } + return answer +} + +// Ranked by the high end, then the low end, then the name: Zeta, Alpha, Beta, then Mid, Small and NoDollar. +const SIX = { + answer: databricksWith([ + { name: 'Mid', min: 10, max: 30 }, + { name: 'Zeta', min: 100, max: 200 }, + { name: 'Alpha', min: 50, max: 200 }, + ]), + snowflake: snowflakeWith([ + { name: 'Small', min: 1, max: 5 }, + { name: 'Beta', min: 50, max: 200 }, + { name: 'NoDollar', min: 0, max: 0 }, + ]), +} + +const titles = async (ui: any) => ((await ui.findAll({ type: 'Text', text: / · (Databricks|Snowflake) · / })) as any[]).map(one => one.text) + +test('the slim view shows the three largest findings across both platforms, largest first, ties by low end then name', async ($, on) => { + const { clock } = await start($, on, { list: BOTH, ...SIX }) + await savings($) + await clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + expect(await ui.find({ type: 'Text', text: /^Savings check · last 7 days · dbxmega, sfmega$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^Read-only, on your own connections\. Nothing was sent to Altimate\.$/ })).toBeDefined() + expect(await titles(ui)).toEqual([ + 'Zeta · Databricks · Migrate Classic/Pro to Serverless · $100–$200 a month', + 'Alpha · Databricks · Migrate Classic/Pro to Serverless · $50.00–$200 a month', + 'Beta · Snowflake · High Idle Time · $50.00–$200 a month', + ]) + // One fact under each, and no platform section headers. + expect(await ui.findAll({ type: 'Text', text: /^CLASSIC SMALL warehouse, 95% idle/ })).toHaveLength(2) + expect(await ui.find({ type: 'Text', text: /^60% idle/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /savings check$/ })).toBeUndefined() + // Each keeps the Draft the fix key it has in the full view: Zeta and Alpha are the Databricks answer's 2nd and 3rd, Beta the Snowflake one's 2nd. + expect((await ui.findAll({ type: 'Button', text: 'Draft the fix' })).map((one: any) => one.key)).toEqual(['fix-1', 'fix-2', 'fix-4']) + await ui.unmount() +}) + +test('the +N line counts the findings behind Show all, and the total is the three shown plus what it adds', async ($, on) => { + const { clock } = await start($, on, { list: BOTH, ...SIX }) + await savings($) + await clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + // Mid $10–$30, Small $1–$5 and NoDollar with none: three findings, adding $11–$35. + expect(await ui.find({ type: 'Text', text: /^\+ 3 more findings, adding \$11\.00–\$35\.00 a month to the total$/ })).toBeDefined() + // Zeta $100–$200, Alpha $50–$200 and Beta $50–$200 shown, plus $11–$35: $211–$635, each resource once. + expect(await ui.find({ type: 'Text', text: /^\$211–\$635 a month$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^each resource counted once, at its largest saving$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^(Mid|Small|NoDollar) · / })).toBeUndefined() + // The checks not run, across both platforms: 9 Databricks and 7 Snowflake. + expect(await ui.find({ type: 'Text', text: /^Altimate runs 16 more checks on these platforms\.$/ })).toBeDefined() + expect(await ui.find({ key: 'altimate', type: 'Button' })).toBeDefined() + expect(await ui.find({ key: 'again' })).toBeUndefined() + // Show all draws all six, with each platform's section; Show fewer goes back. + await ui.press({ key: 'more' }) + await clock.settle() + for (const name of ['Zeta', 'Alpha', 'Beta', 'Mid', 'Small', 'NoDollar']) expect(await ui.find({ type: 'Text', text: new RegExp(`^${name} · `) })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^Databricks savings check$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^Not run here: 7 more of Altimate's 11 Snowflake checks$/ })).toBeDefined() + expect(await ui.find({ key: 'again' })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^\+ 3 more/ })).toBeUndefined() + await ui.press({ key: 'fewer' }) + await clock.settle() + expect(await titles(ui)).toHaveLength(3) + await ui.unmount() +}) + +test('a new run starts slim again, after Show all', async ($, on) => { + const { clock, runs } = await start($, on, { list: BOTH, ...SIX }) + await savings($) + await clock.settle() + const ui = await mountFull($) + expect(await ui.find({ type: 'Text', text: /^Mid · / })).toBeDefined() + await ui.press({ key: 'again' }) + await clock.settle() + expect(runs.length).toBe(2) + expect(await ui.find({ type: 'Text', text: /^Mid · / })).toBeUndefined() + expect(await ui.find({ key: 'more' })).toBeDefined() + await ui.unmount() + // So does /savings typed again. + const full = await mountFull($) + await savings($) + await clock.settle() + expect(await full.find({ type: 'Text', text: /^Mid · / })).toBeUndefined() + await full.unmount() +}) + +test('when every finding is shown there is no +N line, and Show all still opens the detail', async ($, on) => { + const answer = databricksWith([ + { name: 'Zeta', min: 100, max: 200 }, + { name: 'Alpha', min: 50, max: 200 }, + { name: 'Mid', min: 10, max: 30 }, + ]) + answer.metadata.report.total = { monthly_min: 160, monthly_max: 430, resources: 3 } + answer.metadata.report.what_if = JSON.parse(JSON.stringify(ANSWER)).metadata.report.what_if + const { clock } = await start($, on, { answer }) + await savings($) + await clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + expect(await titles(ui)).toHaveLength(3) + expect(await ui.find({ type: 'Text', text: /^\+ / })).toBeUndefined() + await ui.press({ key: 'more' }) + await clock.settle() + expect(await ui.find({ type: 'Text', text: /^What if Classic/ })).toBeDefined() + await ui.unmount() +}) + +test('a shown resource\'s other findings are behind Show all, and already in the total', async ($, on) => { + // Classic has two findings; the total counts it once, at its larger one. + const { clock } = await start($, on) + await savings($) + await clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + expect(await titles(ui)).toEqual(['Classic · Databricks · Migrate Classic/Pro to Serverless · $80.64–$101 a month']) + expect(await ui.find({ type: 'Text', text: /^\$80\.64–\$101 a month$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^\+ 1 more finding, already in the total$/ })).toBeDefined() + await ui.press({ key: 'more' }) + await clock.settle() + expect(await ui.find({ type: 'Text', text: /^Classic · Over-Sized Warehouse · / })).toBeDefined() + await ui.unmount() +}) + +test('Share report from the slim view still lists every finding', async ($, on) => { + const { clock, written } = await start($, on, { list: BOTH, ...SIX, files: { [`${ROOT}/dbt_project.yml`]: 'name: acme\n' } }) + await savings($) + await clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + await ui.press({ key: 'share' }) + await clock.settle() + const html = written.get(`${ROOT}/target/.altimate-lineage/savings-report.html`) ?? '' + for (const name of ['Zeta', 'Alpha', 'Beta', 'Mid', 'Small', 'NoDollar']) expect(html).toContain(`${name} · `) + expect(html).toContain('CLASSIC SMALL warehouse, 95% idle') + await ui.unmount() +}) + +test('on the live Snowflake answer the slim view shows its three largest, the rest summed, and no line wider than the pane', async ($, on) => { + const files = { [`${HOME}/.altimate-code/connections.json`]: JSON.stringify({ snowflake: { type: 'snowflake', account: 'acct', warehouse: 'COMPUTE_WH' } }) } + const { clock } = await start($, on, { list: 'Name | Type | Database\nsnowflake | snowflake | A', snowflake: SNOWFLAKE_CAPTURE, env: { HOME }, files }) + await savings($) + await clock.settle() + // From the capture itself: each warehouse at its largest finding, largest first. + const raw = [...(SNOWFLAKE_CAPTURE.metadata.report.findings as any[])].sort( + (a, b) => b.monthly_max - a.monthly_max || b.monthly_min - a.monthly_min || String(a.resource_name).localeCompare(String(b.resource_name)), + ) + const largest = raw.filter((one, at) => raw.findIndex(other => other.resource_id === one.resource_id) === at) + const rest = largest.slice(3) + const sum = (rows: any[], key: 'monthly_min' | 'monthly_max') => rows.reduce((total, one) => total + one[key], 0) + const total = SNOWFLAKE_CAPTURE.metadata.report.total + // The three shown and what the +N line adds are the whole total, to the cent. + expect(Math.abs(sum(largest.slice(0, 3), 'monthly_min') + sum(rest, 'monthly_min') - total.monthly_min)).toBeLessThan(0.005) + expect(Math.abs(sum(largest.slice(0, 3), 'monthly_max') + sum(rest, 'monthly_max') - total.monthly_max)).toBeLessThan(0.005) + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + expect((await titles(ui)).map((one: string) => one.split(' · ')[0])).toEqual(largest.slice(0, 3).map(one => one.resource_name)) + expect(await ui.find({ type: 'Text', text: /^\$342–\$489 a month$/ })).toBeDefined() + const smaller = (await ui.find({ type: 'Text', text: /^\+ 6 more findings, / })) as any + expect(smaller?.text).toBe(`+ 6 more findings, adding ${dollars(sum(rest, 'monthly_min'))}–${dollars(sum(rest, 'monthly_max'))} a month to the total`) + expect(await ui.find({ type: 'Text', text: /^Altimate runs 7 more checks on this platform\.$/ })).toBeDefined() + for (const line of (await ui.findAll({ type: 'Text' })) as any[]) expect({ line: line.text, fits: line.text.length <= SLIM_WIDTH }).toEqual({ line: line.text, fits: true }) + await ui.unmount() +}) + +test('a long fact is cut at a clause, a long name is shortened, so the slim lines do not wrap', async ($, on) => { + const answer = JSON.parse(JSON.stringify(ANSWER)) + answer.metadata.report = { lookback_days: 7, findings: [{ ...JOB, resource_name: 'nightly_orders_rollup_with_a_very_long_name_from_the_workspace_ui' }, IDLE_CLUSTER], total: { monthly_min: 1870.2, monthly_max: 2805.3, resources: 2 }, what_if: [] } + const { clock } = await start($, on, { answer }) + await savings($) + await clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + expect(await ui.find({ type: 'Text', text: /^1,028 task runs \(periodic\), 181\.8 hours on all-purpose compute, about 1,818\.2 DBUs$/ })).toBeDefined() + const title = (await ui.find({ type: 'Text', text: /^nightly_o… · Databricks · Job Running on All-Purpose Compute · \$1,870–\$2,805 a month$/ })) as any + expect(title?.text.length).toBe(SLIM_WIDTH) + for (const line of (await ui.findAll({ type: 'Text' })) as any[]) expect({ line: line.text, fits: line.text.length <= SLIM_WIDTH }).toEqual({ line: line.text, fits: true }) + // The full view keeps the whole fact. + await ui.press({ key: 'more' }) + await clock.settle() + expect(await ui.find({ type: 'Text', text: /about 1,818\.2 DBUs, most on cluster "shared analytics"$/ })).toBeDefined() + await ui.unmount() +}) + +test('fitLine keeps a line that fits, cuts at the last clause that fits, else at a word with an ellipsis', () => { + expect(fitLine('short', 10)).toBe('short') + expect(fitLine('one thing, two things, three things', 25)).toBe('one thing, two things') + // A clause that ends exactly at the width is kept whole. + expect(fitLine('one thing, two things, three things', 21)).toBe('one thing, two things') + expect(fitLine('averyveryverylongword and more words here', 20)).toBe('averyveryverylongwo…') + expect(fitLine('a b c d e f g h i j k l m n o', 10)).toBe('a b c d…') +}) + +test('in the slim view a drafted fix\'s line shows once, under the first top finding on its warehouse', async ($, on) => { + // Classic is still SMALL and has two findings, both in the top three. + const { clock } = await start($, on, { now: Date.parse('2026-11-18T10:00:00Z'), store: { [FIX_KEY]: FIX } }) + await savings($) + await clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const texts = ((await ui.findAll({ type: 'Text' })) as any[]).map(one => one.text) + const line = 'Classic: fix drafted 2026-11-01, but it is still SMALL CLASSIC and still flagged, so no saving is claimed.' + expect(texts.filter(text => text === line)).toHaveLength(1) + expect(texts.indexOf(line)).toBe(texts.indexOf('CLASSIC SMALL warehouse, 95% idle over 11.0 running hours (3,107 queries)') + 1) + await ui.unmount() +}) + +test('in the slim view a drafted fix whose finding has cleared still shows its line', async ($, on) => { + const { clock } = await start($, on, { now: Date.parse('2026-11-18T10:00:00Z'), answer: resizedAnswer('2026-11-18', 14), store: { [FIX_KEY]: FIX } }) + await savings($) + await clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + expect(await ui.find({ key: 'more' })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^No savings found by these 4 checks\.$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^Classic: changed to X-SMALL CLASSIC since 2026-11-10: observed spend / })).toBeDefined() + await ui.unmount() +}) + +test('a session end, and a run that is refused, open the pane slim again', async ($, on) => { + const options: any = {} + const { clock } = await start($, on, options) + await savings($) + await clock.settle() + const ui = await mountFull($) + expect(await ui.find({ type: 'Text', text: /^Not run here/ })).toBeDefined() + await $.session.end({ reason: 'clear' } as any) + await clock.settle() + expect(await ui.find({ type: 'Text', text: /^Not run here/ })).toBeUndefined() + expect(await ui.find({ key: 'more' })).toBeDefined() + // Open the detail again, then a run the tool refuses. + await showAll(ui) + expect(await ui.find({ type: 'Text', text: /^Not run here/ })).toBeDefined() + options.answer = failure('[INSUFFICIENT_PERMISSIONS] User does not have USE SCHEMA on Schema system.billing') + await ui.press({ key: 'again' }) + await clock.settle() + expect(await ui.find({ type: 'Text', text: /^Not run here/ })).toBeUndefined() + expect(await ui.find({ type: 'Text', text: /^A query was refused/ })).toBeDefined() + await ui.unmount() +}) + +// --- Missing values, checks that did not run, the version, the command match and per-workspace baselines. + +test('a job whose evidence lacks its trigger, host cluster, hours or DBUs reads without "NaN", "undefined", empty quotes or "(id )"', () => { + const evidence = { kind: 'job_on_all_purpose', task_runs: 3, all_purpose_rate_per_dbu: 0.55, jobs_rate_per_dbu: 0.15 } + const [line] = evidenceLines(evidence) + expect(line).toBe('3 task runs, ? hours on all-purpose compute, ? DBUs') + const request = fixRequest({ ...JOB, evidence }) + expect(request).not.toMatch(/NaN|undefined|""|\(id \)/) + expect(request).toContain('sized like the cluster each task uses now.') + // Present values still read as before, and a tiny DBU figure is "under 0.1" without "about". + expect(evidenceLines({ ...JOB.evidence, estimated_dbus: 0.01 })[0]).toContain(', under 0.1 DBUs, most on cluster "shared analytics"') + expect(evidenceLines(JOB.evidence)[0]).toContain('(periodic), 181.8 hours on all-purpose compute, about 1,818.2 DBUs') +}) + +test('when no check could run, the pane, the notice and the status line say nothing was checked, not that nothing was found', async ($, on) => { + const answer = JSON.parse(JSON.stringify(ANSWER)) + const checks = ['Migrate Classic/Pro to Serverless', 'Over-Sized Warehouse', 'Idle Cluster Detection', 'Job Running on All-Purpose Compute'] + // A check listed twice is still one check. + answer.metadata.skipped = [...checks, checks[3]].map(check => ({ check, reason: 'INSUFFICIENT_PERMISSIONS' })) + answer.metadata.report = { lookback_days: 7, findings: [], total: { monthly_min: 0, monthly_max: 0, resources: 0 }, what_if: [] } + const { clock, toasts, statuses } = await start($, on, { answer }) + await savings($) + await clock.settle() + expect(toasts.at(-1)).toBe('Databricks savings check: none of the 4 checks could run, so nothing was checked.') + expect(String(statuses.at(-1) ?? '')).toContain('nothing was checked') + for (const full of [false, true]) { + const ui = full ? await mountFull($) : await $.ui.mount({ ...PANE, surface: 'terminal' }) + expect(await ui.find({ type: 'Text', text: /^None of the 4 checks could run, so nothing was checked\.$/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /No savings found|-?\d+ of 4 checks that ran/ })).toBeUndefined() + await ui.unmount() + } +}) + +test('a check listed for two reasons counts once in the verdict', () => { + expect(skippedChecks({ skipped: ['Idle Cluster Detection (refused)', 'Idle Cluster Detection (time limit)'] })).toBe(1) +}) + +for (const [name, options] of [ + ['prints no version', { version: '' }], + ['does not answer', { versionRejects: 'timed out after 15000 ms' }], +] as const) { + test(`a --version that ${name} says the version could not be read; nothing else runs`, async ($, on) => { + const { clock, runs, toasts } = await start($, on, options) + await savings($) + await clock.settle() + expect(runs).toEqual([]) + expect(toasts.at(-1)).toContain("altimate-code's version could not be read, so the savings check was not started.") + expect(toasts.at(-1)).not.toContain('It is ') + }) +} + +test('a version printed with the CLI name in front still starts the check', async ($, on) => { + const { clock, runs } = await start($, on, { version: `altimate-code ${SAVINGS_MIN_ALTIMATE_CODE}` }) + await savings($) + await clock.settle() + expect(runs.length).toBe(1) +}) + +for (const command of ['echo databricks bundle deploy', 'grep databricks clusters notes.txt', 'git commit -m "databricks jobs"']) { + test(`a command that only names databricks (${command}) offers nothing`, async ($, on) => { + const { clock } = await start($, on) + await $.tool.call({ tool: 'Bash', command }) + await clock.settle() + const band = await $.ui.mount(BAND) + expect(await band.find({ type: 'Text', text: /Databricks compute in play/ })).toBeUndefined() + await band.unmount() + }) +} + +for (const command of ['databricks jobs list', 'ls; databricks clusters list', 'make build || databricks bundle validate', 'A=1 B=2 databricks warehouses list']) { + test(`a command that runs databricks (${command}) offers the check`, async ($, on) => { + const { clock } = await start($, on) + await $.tool.call({ tool: 'Bash', command }) + await clock.settle() + const band = await $.ui.mount(BAND) + expect(await band.find({ type: 'Text', text: /^Databricks compute in play/ })).toBeDefined() + await band.unmount() + }) +} + +test('the same warehouse id in two workspaces keeps two baselines, and only the flagged one is kept', async ($, on) => { + const answer = JSON.parse(JSON.stringify(ANSWER)) + const classic = answer.metadata.warehouses.find((one: any) => one.id === 'wh-classic') + classic.workspace_id = '111' + answer.metadata.warehouses.push({ ...classic, workspace_id: '222', name: 'Classic in 222', size: 'LARGE', window_cost: 500 }) + answer.metadata.report.findings.forEach((one: any) => (one.workspace_id = '111')) + const { clock, store } = await start($, on, { answer, now: Date.parse('2026-11-18T10:00:00Z') }) + await savings($) + await clock.settle() + expect(store.get('savings-baseline:dbxmega:111:wh-classic')).toEqual({ date: '2026-11-18', config: { size: 'SMALL', type: 'CLASSIC' }, windowCost: 27.544375, days: 7 }) + expect(store.has('savings-baseline:dbxmega:222:wh-classic')).toBe(false) + expect(store.has('savings-baseline:dbxmega:wh-classic')).toBe(false) +}) + +test('a baseline in one workspace is read for that workspace only, though another has a warehouse with its id', async ($, on) => { + // Workspace 111's Classic was SMALL and is X-SMALL now; workspace 222 has a LARGE warehouse with the same id. + const store = { 'savings-baseline:dbxmega:111:wh-classic': { date: '2026-11-10', config: { size: 'SMALL', type: 'CLASSIC' }, windowCost: 27.54 } } + const answer = JSON.parse(JSON.stringify(ANSWER)) + answer.metadata.warehouses = answer.metadata.warehouses.map((one: any) => ({ ...one, workspace_id: '111', size: one.id === 'wh-classic' ? 'X_SMALL' : one.size })) + const classic = answer.metadata.warehouses.find((one: any) => one.id === 'wh-classic') + answer.metadata.warehouses.push({ ...classic, workspace_id: '222', name: 'Other classic', size: 'LARGE' }) + const { clock } = await start($, on, { answer, store }) + await savings($) + await clock.settle() + const ui = await mountFull($) + const texts = ((await ui.findAll({ type: 'Text' })) as any[]).map(one => one.text) + expect(texts.filter(text => / → .* since 2026-11-10/.test(text))).toEqual([ + 'Classic (workspace 111): SMALL CLASSIC → X-SMALL CLASSIC since 2026-11-10. Observed spend: $118.03 a month before, $118.05 after.', + ]) + await ui.unmount() +}) + +// Each setting, known or not before and after, the same or not: what the baseline keeps, and the line the pane draws. +// The other setting is either known and the same on both sides, or unknown before and read now. The baseline is one +// run's read: a run that reads every setting it knew, finds none changed and reads more replaces it whole, with its +// own date and cost; any other run leaves it as it was. +const SETTING_CASES = [ + { setting: 'size', a: 'SMALL', b: 'X_SMALL', other: 'type', otherValue: 'CLASSIC' }, + { setting: 'type', a: 'CLASSIC', b: 'PRO', other: 'size', otherValue: 'SMALL' }, +] as const +for (const { setting, a, b, other, otherValue } of SETTING_CASES) { + for (const otherBefore of ['known', 'unknown'] as const) { + for (const before of ['known', 'unknown'] as const) { + for (const after of ['known', 'unknown'] as const) { + for (const same of [true, false]) { + test(`baseline ${setting}: ${before} before, ${after} after, ${same ? 'same' : 'different'} value; ${other} ${otherBefore === 'known' ? 'known throughout' : 'read only now'}`, async ($, on) => { + const was = { [other]: otherBefore === 'known' ? otherValue : null, [setting]: before === 'known' ? a : null } as Record + const now = { [other]: otherValue, [setting]: after === 'known' ? (same ? a : b) : null } as Record + const key = 'savings-baseline:dbxmega:wh-classic' + const store = { [key]: { date: '2026-11-10', config: { size: was.size ?? null, type: was.type ?? null }, windowCost: 27.54 } } + const answer = JSON.parse(JSON.stringify(ANSWER)) + Object.assign(answer.metadata.warehouses.find((one: any) => one.id === 'wh-classic'), { size: now.size ?? null, type: now.type ?? null }) + const started = await start($, on, { answer, store }) + await savings($) + await started.clock.settle() + // Changed: only a setting known on both sides, with different values. + const changed = before === 'known' && after === 'known' && !same + const covered = before === 'unknown' || after === 'known' + const learned = (before === 'unknown' && after === 'known') || otherBefore === 'unknown' + const replaced = !changed && covered && learned + const kept = started.store.get(key) as any + expect(kept.config).toEqual(replaced ? { size: now.size ?? null, type: now.type ?? null } : { size: was.size ?? null, type: was.type ?? null }) + expect(kept.date === '2026-11-10').toBe(!replaced) + // The line names only the settings known on both sides. + const named = (['size', 'type'] as const).filter(one => was[one] !== null && now[one] !== null) + const label = (config: Record) => named.map(one => (one === 'size' ? config.size!.replace(/_/g, '-') : config.type!)).join(' ') + const ui = await mountFull($) + const texts = ((await ui.findAll({ type: 'Text' })) as any[]).map(one => String(one.text)) + expect(texts.filter(text => / since 2026-11-10\./.test(text))).toEqual( + changed ? [`Classic: ${label(was)} → ${label(now)} since 2026-11-10. Observed spend: $118.03 a month before, $118.05 after.`] : [], + ) + expect(texts.filter(text => /\?|null|undefined/.test(text) && / since /.test(text))).toEqual([]) + await ui.unmount() + }) + } + } + } + } +} + +test('a change a fix saw is kept when a later run does not read the setting that changed', async ($, on) => { + // Seen resized on 2026-11-10; this run reads no size, so it cannot say the resize was undone. + const answer = resizedAnswer('2026-11-18', 14) + answer.metadata.warehouses.find((one: any) => one.id === 'wh-classic').size = null + const { clock, store } = await start($, on, { now: Date.parse('2026-11-18T10:00:00Z'), answer, store: { [FIX_KEY]: FIX } }) + await savings($) + await clock.settle() + expect((store.get(FIX_KEY) as any).changedSeen).toBe('2026-11-10') +}) + +test('a change a fix saw is cleared when a later run reads every setting and finds it undone', async ($, on) => { + const answer = resizedAnswer('2026-11-18', 14) + answer.metadata.warehouses.find((one: any) => one.id === 'wh-classic').size = 'SMALL' + const { clock, store } = await start($, on, { now: Date.parse('2026-11-18T10:00:00Z'), answer, store: { [FIX_KEY]: FIX } }) + await savings($) + await clock.settle() + expect((store.get(FIX_KEY) as any).changedSeen).toBeUndefined() +}) + +test('a fix drafted before the size was read never takes a later run\'s size, and its line compares only the type', async ($, on) => { + // The size this run reads may be the fix itself, applied since: it is not what the fix was drafted against. + const { clock, store } = await start($, on, { now: Date.parse('2026-11-18T10:00:00Z'), store: { [FIX_KEY]: { ...FIX, changedSeen: undefined, config: { size: null, type: 'CLASSIC' } } } }) + await savings($) + await clock.settle() + expect((store.get(FIX_KEY) as any).config).toEqual({ size: null, type: 'CLASSIC' }) + const ui = await mountFull($) + const lines = ((await ui.findAll({ type: 'Text' })) as any[]).map(one => String(one.text)).filter(text => text.startsWith('Classic: fix drafted')) + expect(lines).toEqual(['Classic: fix drafted 2026-11-01, but it is still CLASSIC and still flagged, so no saving is claimed.']) + await ui.unmount() +}) + +test('a setting the baseline did not know is not filled from a read in which another setting changed', async ($, on) => { + // The baseline knew only the type. This run reads SMALL PRO: the type changed, so SMALL is the size after the + // change, not the size the baseline had. + const key = 'savings-baseline:dbxmega:wh-classic' + const answer = JSON.parse(JSON.stringify(ANSWER)) + Object.assign(answer.metadata.warehouses.find((one: any) => one.id === 'wh-classic'), { size: 'SMALL', type: 'PRO' }) + const { clock, store } = await start($, on, { answer, store: { [key]: { date: '2026-11-10', config: { size: null, type: 'CLASSIC' }, windowCost: 27.54 } } }) + await savings($) + await clock.settle() + expect((store.get(key) as any).config).toEqual({ size: null, type: 'CLASSIC' }) + const ui = await mountFull($) + const texts = ((await ui.findAll({ type: 'Text' })) as any[]).map(one => String(one.text)) + expect(texts.filter(text => / since 2026-11-10\./.test(text))).toEqual(['Classic: CLASSIC → PRO since 2026-11-10. Observed spend: $118.03 a month before, $118.05 after.']) + await ui.unmount() +}) + +test('a run that reads every setting the baseline knew, with none changed, replaces it whole: date and spend too', async ($, on) => { + // Kept on 2026-11-10 with the size unknown. A resize in between could not be seen, so the size this run reads is + // the warehouse now: the baseline takes it with this run's date and spend, never the old week's. + const key = 'savings-baseline:dbxmega:wh-classic' + const answer = JSON.parse(JSON.stringify(ANSWER)) + const classic = answer.metadata.warehouses.find((one: any) => one.id === 'wh-classic') + Object.assign(classic, { size: 'MEDIUM', type: 'CLASSIC' }) + const { clock, store } = await start($, on, { answer, store: { [key]: { date: '2026-11-10', config: { size: null, type: 'CLASSIC' }, windowCost: 99, days: 7 } } }) + await savings($) + await clock.settle() + const kept = store.get(key) as any + expect(kept.config).toEqual({ size: 'MEDIUM', type: 'CLASSIC' }) + expect(kept.date).not.toBe('2026-11-10') + expect(kept.windowCost).toBe(Number(classic.window_cost)) +}) + +test('a run that misses a setting the baseline knew leaves it as it was, whatever else it reads', async ($, on) => { + const key = 'savings-baseline:dbxmega:wh-classic' + const answer = JSON.parse(JSON.stringify(ANSWER)) Object.assign(answer.metadata.warehouses.find((one: any) => one.id === 'wh-classic'), { size: null, type: 'PRO' }) const stored = { date: '2026-11-10', config: { size: 'SMALL', type: null }, windowCost: 27.54 } const { clock, store } = await start($, on, { answer, store: { [key]: stored } }) @@ -1456,7 +3201,7 @@ test('Draft the fix pressed just before a run starts still fills the prompt box test('Draft the fix whose prompt box is filled across a /clear says nothing in the new conversation', async ($, on) => { let release = () => {} const fillHold = new Promise(done => (release = done)) - const { clock, fills, toasts } = await start($, on, { fillHold }) + const { clock, fills, toasts, store } = await start($, on, { fillHold }) await savings($) await clock.settle() const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) @@ -1467,6 +3212,94 @@ test('Draft the fix whose prompt box is filled across a /clear says nothing in t await clock.settle() expect(fills).toHaveLength(1) expect(toasts.filter(text => /prompt box/.test(text))).toEqual([]) + // The /clear replaced the box's text: the request is not followed by a later run. + expect([...store.keys()].filter(key => key.startsWith('savings-fix:'))).toEqual([]) + await ui.unmount() +}) + +test('Draft the fix whose record is written across a /clear says nothing in the new conversation', async ($, on) => { + let release = () => {} + const held = new Promise(done => (release = done)) + const { clock, toasts } = await start($, on, { onStep: async step => (step === 'fix write' ? held : undefined) }) + await savings($) + await clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + await ui.press({ key: 'fix-0' }) + await clock.settle() + await $.session.end({ reason: 'clear' } as any) + release() + await clock.settle() + expect(toasts.filter(text => /prompt box/.test(text))).toEqual([]) + await ui.unmount() +}) + +test('with two connections on one workspace, a fix drafted from the one listed second stays under the finding the slim view shows', async ($, on) => { + // A second, smaller finding on another warehouse puts a line listed on its own after both titles. + const answer = JSON.parse(JSON.stringify(ANSWER)) + const classic = answer.metadata.report.findings.find((one: any) => one.resource_id === 'wh-classic') + answer.metadata.report.findings.push({ ...classic, resource_id: 'wh-xs', resource_name: 'ALTIMATE_WH', monthly_min: 5, monthly_max: 10 }) + // The answers are listed by connection name, so `dbxmega` comes after `classic`: its copy is the one to prefer. + const store = { [`savings-fix:project:${ROOT}/dbxmega::sql_warehouse:wh-classic`]: FIX } + const { clock } = await start($, on, { list: BOTH, answer, now: Date.parse('2026-11-18T10:00:00Z'), store }) + await savings($, 'dbxmega') + await clock.settle() + answer.metadata.warehouse = 'classic' + await savings($, 'classic') + await clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const texts = ((await ui.findAll({ type: 'Text' })) as any[]).map(one => String(one.text)) + const lines = texts.filter(text => /^Classic: fix drafted /.test(text)) + expect(lines).toHaveLength(1) + const titles = texts.map((text, at) => (text.includes(' · Databricks · ') ? at : -1)).filter(at => at >= 0) + expect(titles).toHaveLength(2) + expect(texts[titles[0]!]).toContain('Classic') + expect(texts.indexOf(lines[0]!)).toBe(titles[0]! + 2) + await ui.unmount() +}) + +test('with two connections on one workspace, a fix drafted from one stays under the finding when the other connection\'s copy ranks higher', async ($, on) => { + const answer = JSON.parse(JSON.stringify(ANSWER)) + const classic = answer.metadata.report.findings.find((one: any) => one.resource_id === 'wh-classic') + answer.metadata.report.findings.push({ ...classic, resource_id: 'wh-xs', resource_name: 'ALTIMATE_WH', monthly_min: 5, monthly_max: 10 }) + const store = { [`savings-fix:project:${ROOT}/dbxmega::sql_warehouse:wh-classic`]: FIX } + const { clock } = await start($, on, { list: BOTH, answer, now: Date.parse('2026-11-18T10:00:00Z'), store }) + await savings($, 'dbxmega') + await clock.settle() + // The other connection ran on another day and reads a larger saving for the same finding. + classic.monthly_max += 50 + answer.metadata.warehouse = 'classic' + await savings($, 'classic') + await clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const texts = ((await ui.findAll({ type: 'Text' })) as any[]).map(one => String(one.text)) + const lines = texts.filter(text => /^Classic: fix drafted /.test(text)) + expect(lines).toHaveLength(1) + const titles = texts.map((text, at) => (text.includes(' · Databricks · ') ? at : -1)).filter(at => at >= 0) + expect(texts[titles[0]!]).toContain('Classic') + expect(texts.indexOf(lines[0]!)).toBe(titles[0]! + 2) + await ui.unmount() +}) + +test('with two connections on one workspace that both drafted the fix, its line shows once, under the finding', async ($, on) => { + const answer = JSON.parse(JSON.stringify(ANSWER)) + const classic = answer.metadata.report.findings.find((one: any) => one.resource_id === 'wh-classic') + answer.metadata.report.findings.push({ ...classic, resource_id: 'wh-xs', resource_name: 'ALTIMATE_WH', monthly_min: 5, monthly_max: 10 }) + const store = { + [`savings-fix:project:${ROOT}/dbxmega::sql_warehouse:wh-classic`]: FIX, + [`savings-fix:project:${ROOT}/classic::sql_warehouse:wh-classic`]: { ...FIX, date: '2026-11-02' }, + } + const { clock } = await start($, on, { list: BOTH, answer, now: Date.parse('2026-11-18T10:00:00Z'), store }) + await savings($, 'dbxmega') + await clock.settle() + answer.metadata.warehouse = 'classic' + await savings($, 'classic') + await clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const texts = ((await ui.findAll({ type: 'Text' })) as any[]).map(one => String(one.text)) + const lines = texts.filter(text => /^Classic: fix drafted /.test(text)) + expect(lines).toHaveLength(1) + const titles = texts.map((text, at) => (text.includes(' · Databricks · ') ? at : -1)).filter(at => at >= 0) + expect(texts.indexOf(lines[0]!)).toBe(titles[0]! + 2) await ui.unmount() }) @@ -1487,12 +3320,14 @@ test('an answer whose window has no end, or whose connection name carries a line const { clock } = await start($, on, { answer }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const slim = await $.ui.mount({ ...PANE, surface: 'terminal' }) + expect(await slim.find({ type: 'Text', text: /^Savings check · last 7 days · dbx mega$/ })).toBeDefined() + await slim.unmount() + const ui = await mountFull($) const texts = ((await ui.findAll({ type: 'Text' })) as any[]).map(one => String(one.text)) - const line = texts.find(text => / days/.test(text) && /connection/.test(text)) + const line = texts.find(text => / · the 7 days/.test(text)) expect(line).toBeDefined() - expect(line).not.toMatch(/undefined|\n/) - expect(line).toContain('connection dbx mega') + expect(texts.filter(text => /undefined|\n/.test(text))).toEqual([]) await ui.unmount() }) @@ -1533,7 +3368,7 @@ test('a config edit whose file is read across a /clear puts no line above the ne await band.unmount() }) -test('a warehouse the answer gives no cost for draws no change line and keeps no baseline from it', async ($, on) => { +test('a warehouse the answer gives no cost for draws no change line', async ($, on) => { const key = 'savings-baseline:dbxmega:wh-classic' const answer = JSON.parse(JSON.stringify(ANSWER)) const classic = answer.metadata.warehouses.find((one: any) => one.id === 'wh-classic') @@ -1542,7 +3377,7 @@ test('a warehouse the answer gives no cost for draws no change line and keeps no const resized = await start($, on, { answer, store: { [key]: { date: '2026-11-10', config: { size: 'SMALL', type: 'CLASSIC' }, windowCost: 27.54 } } }) await savings($) await resized.clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) const texts = ((await ui.findAll({ type: 'Text' })) as any[]).map(one => String(one.text)) expect(texts.filter(text => / since 2026-11-10/.test(text))).toEqual([]) expect(texts.filter(text => /NaN|\?/.test(text))).toEqual([]) @@ -1556,12 +3391,20 @@ test('a cost sent as a numeric string is a cost: the change line is drawn', asyn const { clock } = await start($, on, { answer, store: { [key]: { date: '2026-11-10', config: { size: 'SMALL', type: 'CLASSIC' }, windowCost: 27.54 } } }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) const texts = ((await ui.findAll({ type: 'Text' })) as any[]).map(one => String(one.text)) expect(texts.filter(text => / since 2026-11-10\./.test(text))).toEqual(['Classic: SMALL CLASSIC → X-SMALL CLASSIC since 2026-11-10. Observed spend: $118.03 a month before, $118.05 after.']) await ui.unmount() }) +test('a warehouse cost sent as a numeric string is the cost a draft keeps', () => { + const answer = JSON.parse(JSON.stringify(ANSWER)) + answer.metadata.warehouses.find((one: any) => one.id === 'wh-classic').window_cost = '27.544375' + const view = toView(answer.metadata)! + expect(view.inventory.find(one => one.id === 'wh-classic')?.windowCost).toBe(27.544375) + expect(Math.abs(view.findings.find(one => one.resourceId === 'wh-classic')!.dailyCost! - 27.544375 / 7)).toBeLessThan(1e-9) +}) + test('a flagged warehouse whose cost is a numeric string keeps a baseline with that cost', async ($, on) => { const fresh = JSON.parse(JSON.stringify(ANSWER)) fresh.metadata.warehouses.find((one: any) => one.id === 'wh-classic').window_cost = '27.544375' @@ -1571,13 +3414,34 @@ test('a flagged warehouse whose cost is a numeric string keeps a baseline with t expect((store.get('savings-baseline:dbxmega:wh-classic') as any)?.windowCost).toBe(27.544375) }) -test('a flagged warehouse the answer gives no cost for keeps no baseline', async ($, on) => { +test('a cost kept unknown is not filled from a run after a change: the line stays unremarked and the baseline keeps no cost', async ($, on) => { + const key = 'savings-baseline:dbxmega:wh-classic' const answer = JSON.parse(JSON.stringify(ANSWER)) - delete answer.metadata.warehouses.find((one: any) => one.id === 'wh-classic').window_cost - const { clock, store } = await start($, on, { answer }) + Object.assign(answer.metadata.warehouses.find((one: any) => one.id === 'wh-classic'), { size: 'X_SMALL', window_cost: 100 }) + const { clock, store } = await start($, on, { answer, store: { [key]: { date: '2026-11-10', config: { size: 'SMALL', type: 'CLASSIC' }, windowCost: null } } }) await savings($) await clock.settle() - expect(store.has('savings-baseline:dbxmega:wh-classic')).toBe(false) + expect((store.get(key) as any).windowCost).toBeNull() + const ui = await mountFull($) + expect(await ui.find({ type: 'Text', text: / since 2026-11-10\./ })).toBeUndefined() + await ui.unmount() +}) + +test('in one workspace, a fix that names another workspace does not hide this workspace\'s change line', async ($, on) => { + const answer = resizedAnswer('2026-11-18', 14) + answer.metadata.workspaces_checked = 1 + answer.metadata.warehouses = answer.metadata.warehouses.map((one: any) => ({ ...one, workspace_id: '111' })) + const store = { + [`savings-fix:project:${ROOT}/dbxmega:222:sql_warehouse:wh-classic`]: { ...FIX, workspaceId: '222' }, + 'savings-baseline:dbxmega:111:wh-classic': { date: '2026-11-01', config: { size: 'SMALL', type: 'CLASSIC' }, windowCost: 27.54 }, + } + const { clock } = await start($, on, { now: Date.parse('2026-11-18T10:00:00Z'), answer, store }) + await savings($) + await clock.settle() + const ui = await mountFull($) + const texts = ((await ui.findAll({ type: 'Text' })) as any[]).map(one => String(one.text)) + expect(texts.filter(text => /^Classic: SMALL CLASSIC → X-SMALL CLASSIC since 2026-11-01\./.test(text))).toHaveLength(1) + await ui.unmount() }) test('a baseline an older version kept as strings loads as fully unknown: no line, and this run replaces it', async ($, on) => { @@ -1588,7 +3452,7 @@ test('a baseline an older version kept as strings loads as fully unknown: no lin const { clock, store: kept } = await start($, on, { answer, store }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) expect(await ui.find({ type: 'Text', text: / since 2026-11-10\./ })).toBeUndefined() await ui.unmount() // This run's read, with its own date and spend: nothing of the string baseline is kept. @@ -1598,7 +3462,7 @@ test('a baseline an older version kept as strings loads as fully unknown: no lin expect(now.windowCost).toBe(Number(answer.metadata.warehouses.find((one: any) => one.id === 'wh-classic').window_cost)) }) -test('after a run that failed, the band does not quote the answer the pane no longer shows', async ($, on) => { +test('after a run that failed, the pane keeps the earlier answer beside why, and the band quotes that answer', async ($, on) => { const files = { [`${ROOT}/infra/warehouses.tf`]: 'resource "databricks_sql_endpoint" "classic" {\n name = "Classic"\n cluster_size = "Small"\n}\n' } const answer: { value: unknown } = { value: ANSWER } const started = await start($, on, { files, get answer() { return answer.value } } as any) @@ -1607,10 +3471,14 @@ test('after a run that failed, the band does not quote the answer the pane no lo answer.value = failure('[INSUFFICIENT_PERMISSIONS] no access to system.billing') await savings($) await started.clock.settle() + const ui = await mountFull($) + expect(await ui.find({ type: 'Text', text: /^A query was refused: \[INSUFFICIENT_PERMISSIONS\]/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /^Classic · Migrate Classic\/Pro to Serverless · / })).toBeDefined() + await ui.unmount() await $.tool.call({ tool: 'Edit', file_path: `${ROOT}/infra/warehouses.tf`, old_string: 'Small', new_string: 'Medium' }) await started.clock.settle() const band = await $.ui.mount(BAND) - expect(await band.find({ type: 'Text', text: /^Classic: .*a month to save/ })).toBeUndefined() + expect(await band.find({ type: 'Text', text: /^Classic: Migrate Classic\/Pro to Serverless, .*a month to save/ })).toBeDefined() await band.unmount() }) @@ -1624,7 +3492,7 @@ test('two resized warehouses draw the observed-spend note once, after both lines const { clock } = await start($, on, { answer: resized, store }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) const texts = ((await ui.findAll({ type: 'Text' })) as any[]).map(one => one.text) const changes = texts.filter(text => / since 2026-11-10\. Observed spend: /.test(text)) expect(changes).toHaveLength(2) @@ -1634,8 +3502,74 @@ test('two resized warehouses draw the observed-spend note once, after both lines await ui.unmount() }) +// --- What a resize line claims, how wide a slim title is, and which change line a drafted fix replaces. + +for (const [when, costNow, costThen] of [ + ['now', null, 27.54], + ['when it was flagged', 13.77, null], +] as const) { + test(`a resized warehouse whose cost the answer did not give ${when} gets no "$0" spend line`, async ($, on) => { + const answer = JSON.parse(JSON.stringify(ANSWER)) + const classic = answer.metadata.warehouses.find((one: any) => one.id === 'wh-classic') + classic.size = 'X_SMALL' + if (costNow === null) delete classic.window_cost + else classic.window_cost = costNow + const store = { 'savings-baseline:dbxmega:wh-classic': { date: '2026-11-10', config: { size: 'SMALL', type: 'CLASSIC' }, windowCost: costThen } } + const { clock } = await start($, on, { answer, store }) + await savings($) + await clock.settle() + const ui = await mountFull($) + expect(await ui.find({ type: 'Text', text: /→ X-SMALL CLASSIC since 2026-11-10/ })).toBeUndefined() + expect(await ui.find({ type: 'Text', text: /\$0(\.00)? (a month )?(before|after)/ })).toBeUndefined() + await ui.unmount() + }) +} + +test('a flagged warehouse the answer gives no cost for is remembered without one', async ($, on) => { + const answer = JSON.parse(JSON.stringify(ANSWER)) + delete answer.metadata.warehouses.find((one: any) => one.id === 'wh-classic').window_cost + const { clock, store } = await start($, on, { answer, now: Date.parse('2026-11-18T10:00:00Z') }) + await savings($) + await clock.settle() + expect(store.get('savings-baseline:dbxmega:wh-classic')).toEqual({ date: '2026-11-18', config: { size: 'SMALL', type: 'CLASSIC' }, windowCost: null, days: 7 }) +}) + +test('a slim title with a long check name stays within the slim width, keeping the platform and the amount', () => { + const view = { platform: 'databricks' } as any + const finding = { resourceName: 'analytics-shared-warehouse-for-the-finance-team', title: 'Migrate Classic/Pro to Serverless, with a much longer check title than any today', monthlyMin: 1200, monthlyMax: 3400 } as any + for (const width of [SLIM_WIDTH, 60]) { + const line = slimTitle(view, finding, width) + expect(line.length).toBeLessThanOrEqual(width) + expect(line).toContain(' · Databricks · ') + expect(line).toMatch(/\$1,200–\$3,400/) + expect(line.startsWith('analytic')).toBe(true) + } + // A short title and name read whole, as before. + expect(slimTitle(view, { ...finding, resourceName: 'Classic', title: 'Over-Sized Warehouse' })).toMatch(/^Classic · Databricks · Over-Sized Warehouse · /) +}) + +test('a drafted fix replaces the change line of its own warehouse only, not of another with the same name', async ($, on) => { + const store = { + [FIX_KEY]: FIX, + 'savings-baseline:dbxmega:wh-classic': { date: '2026-11-01', config: { size: 'SMALL', type: 'CLASSIC' }, windowCost: 27.54 }, + 'savings-baseline:dbxmega:wh-classic-2': { date: '2026-11-01', config: { size: 'SMALL', type: 'CLASSIC' }, windowCost: 27.54 }, + } + const answer = resizedAnswer('2026-11-18', 14) + const classic = answer.metadata.warehouses.find((one: any) => one.id === 'wh-classic') + answer.metadata.warehouses.push({ ...classic, id: 'wh-classic-2' }) + const { clock } = await start($, on, { now: Date.parse('2026-11-18T10:00:00Z'), answer, store }) + await savings($) + await clock.settle() + const ui = await mountFull($) + const texts = ((await ui.findAll({ type: 'Text' })) as any[]).map(one => one.text) + // The fixed one has its fix line instead; the other, also called Classic, keeps its change line. + expect(texts.filter(text => /^Classic: changed to X-SMALL CLASSIC since /.test(text))).toHaveLength(1) + expect(texts.filter(text => /^Classic: SMALL CLASSIC → X-SMALL CLASSIC since 2026-11-01\./.test(text))).toHaveLength(1) + await ui.unmount() +}) + test('evidence with none of its figures reads "?" where a figure goes, never NaN or "undefined"', () => { - for (const kind of ['serverless', 'over_sized', 'idle_cluster', 'job_on_all_purpose']) { + for (const kind of ['serverless', 'over_sized', 'idle_cluster', 'job_on_all_purpose', 'high_idle_time', 'downsize_warehouse']) { const lines = evidenceLines({ kind }) expect(lines.length).toBeGreaterThan(0) for (const line of lines) expect(line).not.toMatch(/NaN|undefined|null|\b0 (queries|task runs|active days)/) @@ -1671,18 +3605,6 @@ for (const command of ['echo databricks -p prod clusters list', 'grep -r databri }) } -test('Run again pressed twice starts one run', async ($, on) => { - const { clock, runs } = await start($, on) - await savings($) - await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) - await ui.press({ key: 'again' }) - await ui.press({ key: 'again' }) - await clock.settle() - expect(runs.length).toBe(2) - await ui.unmount() -}) - test('a baseline read over a longer window is scaled by its own length, not this run\'s', async ($, on) => { // Two weeks at $55.08 is the same $118.03 a month as one week at $27.54. const store = { 'savings-baseline:dbxmega:wh-classic': { date: '2026-11-10', config: { size: 'SMALL', type: 'CLASSIC' }, windowCost: 55.08, days: 14 } } @@ -1691,7 +3613,7 @@ test('a baseline read over a longer window is scaled by its own length, not this const { clock } = await start($, on, { answer: resized, store }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) expect(await ui.find({ type: 'Text', text: /^Classic: SMALL CLASSIC → X-SMALL CLASSIC since 2026-11-10\. Observed spend: \$118\.03 a month before, / })).toBeDefined() await ui.unmount() }) @@ -1705,19 +3627,6 @@ test('a preview build is named as one, not told to update', async ($, on) => { expect(toasts.at(-1)).not.toContain('update it to') }) -test('the band\'s Run /savings pressed twice starts one run', async ($, on) => { - const { clock, runs } = await start($, on) - await $.tool.call({ tool: 'Bash', command: 'databricks warehouses list' }) - await clock.settle() - const band = await $.ui.mount(BAND) - expect(await band.find({ key: 'savings-run' })).toBeDefined() - await band.press({ key: 'savings-run' }) - await band.press({ key: 'savings-run' }) - await clock.settle() - expect(runs.length).toBe(1) - await band.unmount() -}) - test('an over-sized finding with no target size asks for a smaller size, with no empty quotes', () => { const finding = { title: 'Over-Sized Warehouse', resource_type: 'sql_warehouse', resource_id: 'wh-1', resource_name: 'Classic', monthly_min: 10, monthly_max: 20, evidence: { kind: 'over_sized', current_size: 'SMALL' } } const request = fixRequest(finding as any) @@ -1751,7 +3660,7 @@ test('a size that fits but costs more says how much more', async ($, on) => { const { clock } = await start($, on, { answer }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) await ui.press({ key: 'whatif-0-1' }) await clock.settle() expect(await ui.find({ type: 'Text', text: /^At X-SMALL: \$150\.00 a month instead of \$118\.05, \$31\.95 more\. / })).toBeDefined() @@ -1815,7 +3724,7 @@ test('a press queued when the session ends does not hold the next session\'s Run await clock.settle() // A run that does not finish before the session ends. options.hold = new Promise(() => {}) - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) await ui.press({ key: 'again' }) await clock.settle() await ui.unmount() @@ -1824,7 +3733,7 @@ test('a press queued when the session ends does not hold the next session\'s Run options.hold = undefined await savings($) await clock.settle() - const again = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const again = await mountFull($) await again.press({ key: 'again' }) await clock.settle() expect(runs.length).toBe(4) @@ -1844,7 +3753,7 @@ test('across several workspaces a warehouse with no workspace id is not compared await clock.settle() // Classic has no workspace id in a two-workspace answer: no baseline is kept for it under any key. expect([...kept.keys()].filter(key => key.includes('wh-classic'))).toEqual([]) - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) const texts = ((await ui.findAll({ type: 'Text' })) as any[]).map(one => one.text) expect(texts.filter(text => / since 2026-11-10\. Observed spend: /.test(text))).toHaveLength(1) await ui.unmount() @@ -1858,7 +3767,7 @@ test('a what-if row without its choices, or a choice without its figures, is lef const { clock } = await start($, on, { answer }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) expect(await ui.find({ type: 'Text', text: /^What if Classic / })).toBeDefined() expect(await ui.find({ type: 'Text', text: /^What if Other / })).toBeUndefined() expect(await ui.find({ key: 'whatif-0-2' })).toBeUndefined() @@ -1874,6 +3783,148 @@ test('auto-termination core sends as null reads "off", as core and the CLI count expect(evidenceLines({ ...evidence, auto_termination_minutes: 120 })[1]).toMatch(/^Auto-termination 120 minutes; /) }) +// --- The merged head's review: the startup probe, saving every answer, slim fix lines, Snowflake gaps, baseline costs. + +test('at session start a source build is not listed from, whatever its stderr names', async ($, on) => { + // A version before `local` on stdout too: only the source-build check keeps this one out. + const { atStart } = await start($, on, { list: BOTH, version: `${SAVINGS_MIN_ALTIMATE_CODE}\nlocal`, versionStderr: 'warning: node v22.1.0 is deprecated\n' }) + expect(atStart.listRuns).toBe(0) +}) + +test('an answer the store refuses does not keep the next one from being saved', async ($, on) => { + const { clock, store } = await start($, on, { list: BOTH, storeRefuses: key => key.startsWith('savings-report:') && /dbxmega|classic/.test(key) }) + await savings($) + await clock.settle() + expect([...store.keys()].filter(key => key.startsWith('savings-report:'))).toHaveLength(1) +}) + +test('in the slim view a drafted fix in another workspace is not drawn under a finding with the same id', async ($, on) => { + const key = `savings-fix:project:${ROOT}/dbxmega:222:sql_warehouse:wh-classic` + // A second, smaller finding on another warehouse, so the slim view shows two titles: Classic's first. + const answer = JSON.parse(JSON.stringify(ANSWER)) + const classic = answer.metadata.report.findings.find((one: any) => one.resource_id === 'wh-classic') + answer.metadata.report.findings.push({ ...classic, resource_id: 'wh-xs', resource_name: 'ALTIMATE_WH', monthly_min: 5, monthly_max: 10 }) + // This run read workspace 111 alone, and says so; the fix was drafted in 222. + answer.metadata.warehouses.forEach((one: any) => (one.workspace_id = '111')) + answer.metadata.report.findings.forEach((one: any) => (one.workspace_id = '111')) + const { clock } = await start($, on, { answer, now: Date.parse('2026-11-18T10:00:00Z'), store: { [key]: { ...FIX, workspaceId: '222' } } }) + await savings($) + await clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const texts = ((await ui.findAll({ type: 'Text' })) as any[]).map(one => one.text) + const lines = texts.filter(text => /^Classic: fix drafted /.test(text)) + expect(lines).toHaveLength(1) + // Listed on its own, after every finding shown, not under the first Classic one. + const titles = texts.map((text, at) => (text.includes(' · Databricks · ') ? at : -1)).filter(at => at >= 0) + expect(titles.length).toBeGreaterThan(1) + expect(texts.indexOf(lines[0])).toBeGreaterThan(titles.at(-1)!) + await ui.unmount() +}) + +test('in the slim view a drafted fix stays under its finding when a later single-workspace answer omits the workspace id', async ($, on) => { + // Drafted while the finding said workspace 1001; this run reads one workspace and names none. A second, smaller + // finding on another warehouse puts a line listed on its own after both titles. + const later = JSON.parse(JSON.stringify(ANSWER)) + const classic = later.metadata.report.findings.find((one: any) => one.resource_id === 'wh-classic') + later.metadata.report.findings.push({ ...classic, resource_id: 'wh-xs', resource_name: 'ALTIMATE_WH', monthly_min: 5, monthly_max: 10 }) + const drafted = JSON.parse(JSON.stringify(later)) + drafted.metadata.warehouses.forEach((one: any) => (one.workspace_id = '1001')) + drafted.metadata.report.findings.forEach((one: any) => (one.workspace_id = '1001')) + const options: any = { answer: drafted } + const { clock, store } = await start($, on, options) + await savings($) + await clock.settle() + let ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + await ui.press({ key: 'fix-0' }) + await clock.settle() + await ui.unmount() + expect([...store.keys()].filter(key => key.startsWith('savings-fix:') && key.includes(':1001:'))).toHaveLength(1) + options.answer = later + await savings($) + await clock.settle() + ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const texts = ((await ui.findAll({ type: 'Text' })) as any[]).map(one => String(one.text)) + const lines = texts.filter(text => /^Classic: fix drafted /.test(text)) + expect(lines).toHaveLength(1) + const titles = texts.map((text, at) => (text.includes(' · Databricks · ') ? at : -1)).filter(at => at >= 0) + expect(titles).toHaveLength(2) + // Under the first finding: its title, its one fact, then the fix's line, before the next title. + expect(texts[titles[0]!]).toContain('Classic') + expect(texts.indexOf(lines[0]!)).toBe(titles[0]! + 2) + await ui.unmount() +}) + +test('in the slim view a drafted Snowflake fix stays under its finding when the warehouse id changes from its name to a number', async ($, on) => { + // A warehouse with no usage has its name for an id; once it has usage it has its number. A smaller finding on + // ETL_WH puts a line listed on its own after both titles. + const later = JSON.parse(JSON.stringify(SNOWFLAKE_ANSWER)) + const bi = later.metadata.report.findings[0] + later.metadata.report.findings.push({ ...bi, resource_id: '8', resource_name: 'ETL_WH', monthly_min: 1, monthly_max: 2 }) + const drafted = JSON.parse(JSON.stringify(later)) + drafted.metadata.report.findings.filter((one: any) => one.resource_id === '7').forEach((one: any) => (one.resource_id = 'BI_WH')) + drafted.metadata.warehouses[0].id = 'BI_WH' + const options: any = { list: 'Name | Type | Database\nsfmega | snowflake | A', snowflake: drafted } + const { clock, store } = await start($, on, options) + await savings($) + await clock.settle() + let ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + await ui.press({ key: 'fix-0' }) + await clock.settle() + await ui.unmount() + expect([...store.keys()].filter(key => key.startsWith('savings-fix:') && key.endsWith(':BI_WH'))).toHaveLength(1) + options.snowflake = later + await savings($) + await clock.settle() + ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const texts = ((await ui.findAll({ type: 'Text' })) as any[]).map(one => String(one.text)) + const lines = texts.filter(text => /^BI_WH: fix drafted /.test(text)) + expect(lines).toHaveLength(1) + const titles = texts.map((text, at) => (text.includes(' · Snowflake · ') ? at : -1)).filter(at => at >= 0) + expect(titles).toHaveLength(2) + expect(texts[titles[0]!]).toContain('BI_WH') + expect(texts.indexOf(lines[0]!)).toBe(titles[0]! + 2) + await ui.unmount() +}) + +test('Snowflake evidence and requests with a figure missing read "?" or ask for the value, never "undefined"', () => { + for (const kind of ['underutilized_cluster', 'frequent_restart', 'downsize_warehouse']) { + for (const line of evidenceLines({ kind })) expect(line).not.toMatch(/undefined|NaN/) + const request = fixRequest({ title: 'Check', resource_type: 'warehouse', resource_id: 'BI_WH', resource_name: 'BI_WH', monthly_min: 0, monthly_max: 0, evidence: { kind } } as any, 7, 'snowflake') + expect(request).not.toMatch(/undefined|UNDEFINED|NaN/) + } +}) + +test('a baseline kept without a cost is replaced by the first run that gives one, while the warehouse is unchanged', async ($, on) => { + // The cost and the date come from the same run: the spend is never paired with another week's date. + const store = { 'savings-baseline:dbxmega:wh-classic': { date: '2026-11-10', config: { size: 'SMALL', type: 'CLASSIC' }, windowCost: null } } + const { clock, store: kept } = await start($, on, { store }) + await savings($) + await clock.settle() + expect(kept.get('savings-baseline:dbxmega:wh-classic')).toEqual({ date: '2026-11-17', config: { size: 'SMALL', type: 'CLASSIC' }, windowCost: 27.544375, days: 7 }) +}) + +test('a drafted fix hides the change line of its own workspace\'s warehouse, not of the same id in another', async ($, on) => { + const key = `savings-fix:project:${ROOT}/dbxmega:111:sql_warehouse:wh-classic` + const store = { + [key]: { ...FIX, workspaceId: '111' }, + 'savings-baseline:dbxmega:111:wh-classic': { date: '2026-11-01', config: { size: 'SMALL', type: 'CLASSIC' }, windowCost: 27.54 }, + 'savings-baseline:dbxmega:222:wh-classic': { date: '2026-11-01', config: { size: 'SMALL', type: 'CLASSIC' }, windowCost: 27.54 }, + } + const answer = resizedAnswer('2026-11-18', 14) + answer.metadata.workspaces_checked = 2 + answer.metadata.warehouses = answer.metadata.warehouses.map((one: any) => ({ ...one, workspace_id: '111' })) + const classic = answer.metadata.warehouses.find((one: any) => one.id === 'wh-classic') + answer.metadata.warehouses.push({ ...classic, workspace_id: '222', name: 'Classic in 222' }) + const { clock } = await start($, on, { now: Date.parse('2026-11-18T10:00:00Z'), answer, store }) + await savings($) + await clock.settle() + const ui = await mountFull($) + const texts = ((await ui.findAll({ type: 'Text' })) as any[]).map(one => one.text) + expect(texts.filter(text => /^Classic in 222 \(workspace 222\): SMALL CLASSIC → X-SMALL CLASSIC since 2026-11-01\./.test(text))).toHaveLength(1) + expect(texts.filter(text => /^Classic( \(workspace 111\))?: SMALL CLASSIC → X-SMALL CLASSIC since /.test(text))).toHaveLength(0) + await ui.unmount() +}) + test('the command reader reads past every wrapper, its flags\' values and assignments, and the remaining keywords', () => { for (const line of [ 'env FOO=1 databricks bundle deploy', @@ -1897,10 +3948,10 @@ test('the command reader reads past every wrapper, its flags\' values and assign test('an answer without a total is no report rather than a failed run', () => { const answer = JSON.parse(JSON.stringify(ANSWER)) delete answer.metadata.report.total - expect(toViewOf(answer.metadata)).toBeNull() + expect(toView(answer.metadata)).toBeNull() }) -test('a total missing its amounts or count still draws its findings, with ? for the amounts', async ($, on) => { +test('a total missing its amounts or count is the findings\' own, and still draws them', async ($, on) => { const answer = JSON.parse(JSON.stringify(ANSWER)) delete answer.metadata.report.total.monthly_min delete answer.metadata.report.total.monthly_max @@ -1908,8 +3959,9 @@ test('a total missing its amounts or count still draws its findings, with ? for const { clock, toasts } = await start($, on, { answer }) await savings($) await clock.settle() - expect(toasts.at(-1)).toBe('Databricks savings check: ? a month on 1 resource.') - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + // The fixture's one priced finding, counted once at its largest saving. + expect(toasts.at(-1)).toMatch(/^Databricks savings check: \$80\.64–\$101 a month on 1 resource/) + const ui = await mountFull($) expect(await ui.find({ type: 'Text', text: /^Classic · Migrate Classic\/Pro to Serverless · / })).toBeDefined() expect(await ui.find({ type: 'Text', text: /failed/ })).toBeUndefined() await ui.unmount() @@ -1932,15 +3984,16 @@ test('a finding without evidence, amounts or a name is still drawn, with ? for w delete finding.monthly_min delete finding.monthly_max expect(evidenceLines(undefined)).toEqual([]) - const view = toViewOf(answer.metadata) + const view = toView(answer.metadata) expect(view?.findings[0]?.evidence).toEqual([]) const { clock } = await start($, on, { answer }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) const texts = ((await ui.findAll({ type: 'Text' })) as any[]).map(one => String(one.text)) expect(texts.some(text => text.includes('NaN'))).toBe(false) - expect(texts.some(text => /^Classic · .* · \? a month$/.test(text))).toBe(true) + // A finding the answer gives no amounts for is one with no dollar estimate. + expect(texts.some(text => /^Classic · .* · no dollar estimate$/.test(text))).toBe(true) await ui.unmount() }) @@ -1963,7 +4016,7 @@ test('a serverless choice the CLI says does not fit is still marked', async ($, const { clock } = await start($, on, { answer }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) expect(((await ui.find({ key: 'whatif-0-0' })) as any)?.props.label).toBe('SERVERLESS $17.24 ⚠') await ui.press({ key: 'whatif-0-0' }) await clock.settle() @@ -1977,7 +4030,7 @@ test('a serverless choice without a fit is not marked as one that does not fit', const { clock } = await start($, on, { answer }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) expect(((await ui.find({ key: 'whatif-0-0' })) as any)?.props.label).toBe('SERVERLESS $17.24') await ui.press({ key: 'whatif-0-0' }) await clock.settle() @@ -2011,7 +4064,7 @@ test('a sized what-if choice without its cores or fit is left out', async ($, on const { clock } = await start($, on, { answer }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) expect(((await ui.find({ key: 'whatif-0-0' })) as any)?.props.label).toBe('SERVERLESS $17.24') expect(await ui.find({ key: 'whatif-0-1' })).toBeUndefined() expect(await ui.find({ type: 'Text', text: /undefined/ })).toBeUndefined() @@ -2026,7 +4079,7 @@ test('the checked line says one warehouse, cluster or job in the singular', asyn const { clock } = await start($, on, { answer }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) expect(await ui.find({ type: 'Text', text: /^1 SQL warehouse, 0 all-purpose clusters and 1 job · / })).toBeDefined() await ui.unmount() }) @@ -2037,12 +4090,27 @@ test('a what-if row whose every choice lacks its figures is left out, not drawn const { clock } = await start($, on, { answer }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) expect(await ui.find({ type: 'Text', text: /^What if Classic / })).toBeUndefined() expect(await ui.find({ type: 'Text', text: /^Press a size to see/ })).toBeUndefined() await ui.unmount() }) +test('in one workspace a drafted fix hides its warehouse\'s change line though only the warehouse names the workspace', async ($, on) => { + const store = { [FIX_KEY]: FIX, 'savings-baseline:dbxmega:111:wh-classic': { date: '2026-11-01', config: { size: 'SMALL', type: 'CLASSIC' }, windowCost: 27.54 } } + const answer = resizedAnswer('2026-11-18', 14) + // The warehouses carry the workspace id; the fix (from a finding) does not. + answer.metadata.warehouses = answer.metadata.warehouses.map((one: any) => ({ ...one, workspace_id: '111' })) + const { clock } = await start($, on, { now: Date.parse('2026-11-18T10:00:00Z'), answer, store }) + await savings($) + await clock.settle() + const ui = await mountFull($) + const texts = ((await ui.findAll({ type: 'Text' })) as any[]).map(one => one.text) + expect(texts.filter(text => /^Classic: changed to X-SMALL CLASSIC since /.test(text))).toHaveLength(1) + expect(texts.filter(text => /^Classic: SMALL CLASSIC → X-SMALL CLASSIC since /.test(text))).toHaveLength(0) + await ui.unmount() +}) + test('heredoc bodies, comments and shifts are read as the shell reads them', () => { // A body is text, whatever its terminator or however many a line opens; what follows it is read. for (const line of [ @@ -2079,19 +4147,71 @@ test('editing a Terraform file that is not Databricks config names no finding, e await band.unmount() }) +test('a drafted job fix that shares a resized warehouse\'s id does not hide that warehouse\'s change line', async ($, on) => { + const jobFix = { ...FIX, resourceType: 'job', checkId: 'job_on_all_purpose', title: 'Job on all-purpose compute', config: null } + const store = { [FIX_KEY.replace(':sql_warehouse:', ':job:')]: jobFix, 'savings-baseline:dbxmega:wh-classic': { date: '2026-11-01', config: { size: 'SMALL', type: 'CLASSIC' }, windowCost: 27.54 } } + const { clock } = await start($, on, { now: Date.parse('2026-11-18T10:00:00Z'), answer: resizedAnswer('2026-11-18', 14), store }) + await savings($) + await clock.settle() + const ui = await mountFull($) + const texts = ((await ui.findAll({ type: 'Text' })) as any[]).map(one => one.text) + expect(texts.filter(text => /^Classic: SMALL CLASSIC → X-SMALL CLASSIC since /.test(text))).toHaveLength(1) + await ui.unmount() +}) + +test('a finding the answer gives no amounts for is one with no dollar estimate, never a missing figure', () => { + const answer = JSON.parse(JSON.stringify(ANSWER)) + delete answer.metadata.report.findings[0].monthly_min + answer.metadata.report.findings[0].monthly_max = 'n/a' + const finding = toView(answer.metadata)?.findings[0] + expect(finding?.monthlyMin).toBe(0) + expect(finding?.monthlyMax).toBe(0) +}) + +test('a drafted job fix that shares a warehouse finding\'s id is not drawn under that finding', async ($, on) => { + const jobFix = { ...FIX, resourceType: 'job', checkId: 'job_on_all_purpose', title: 'Job on all-purpose compute', config: null } + const { clock } = await start($, on, { now: Date.parse('2026-11-18T10:00:00Z'), store: { [FIX_KEY.replace(':sql_warehouse:', ':job:')]: jobFix } }) + await savings($) + await clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + // The job's line is listed on its own, after the findings, not inside the warehouse finding's box. + expect(String(((await ui.find({ key: 'finding-0' })) as any)?.text)).not.toContain('no longer flagged') + expect(((await ui.findAll({ type: 'Text' })) as any[]).filter(one => /^Classic: no longer flagged since /.test(one.text))).toHaveLength(1) + await ui.unmount() +}) + test('a finding without a title is drawn with a plain one, not "undefined"', async ($, on) => { const answer = JSON.parse(JSON.stringify(ANSWER)) delete answer.metadata.report.findings[0].title - expect(toViewOf(answer.metadata)?.findings[0]?.title).toBe('Savings opportunity') + expect(toView(answer.metadata)?.findings[0]?.title).toBe('Savings opportunity') const { clock } = await start($, on, { answer }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) expect(await ui.find({ type: 'Text', text: /^Classic · Savings opportunity · / })).toBeDefined() expect(await ui.find({ type: 'Text', text: /undefined/ })).toBeUndefined() await ui.unmount() }) +test('a finding without a title is drawn in the slim view too, with a plain one', async ($, on) => { + const answer = JSON.parse(JSON.stringify(ANSWER)) + for (const one of answer.metadata.report.findings) delete one.title + const { clock } = await start($, on, { answer }) + await savings($) + await clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + expect(await ui.find({ type: 'Text', text: /^Classic · Databricks · Savings opportunity · / })).toBeDefined() + await ui.unmount() +}) + +test('a total without its count, over findings with no dollar estimate, is never "$0 a month"', () => { + const answer = JSON.parse(JSON.stringify(ANSWER)) + answer.metadata.report.total = { monthly_min: 0, monthly_max: 0 } + const second = { ...answer.metadata.report.findings[0], resource_id: 'wh-other', resource_name: 'Other' } + answer.metadata.report.findings = [answer.metadata.report.findings[0], second].map((one: any) => ({ ...one, monthly_min: 0, monthly_max: 0 })) + expect(toView(answer.metadata)?.total).toEqual({ min: 0, max: 0, resources: 0 }) +}) + test('what-if figures sent as numeric strings are drawn as numbers when a size is pressed', async ($, on) => { const answer = JSON.parse(JSON.stringify(ANSWER)) const choice = answer.metadata.report.what_if[0].choices[1] @@ -2099,7 +4219,7 @@ test('what-if figures sent as numeric strings are drawn as numbers when a size i const { clock } = await start($, on, { answer }) await savings($) await clock.settle() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) await ui.press({ key: 'whatif-0-1' }) await clock.settle() expect(await ui.find({ type: 'Text', text: /^At X-SMALL: \$59\.02 a month instead of \$118\.05, \$59\.03 less\. Its 16 cores cover the 7 its queries need/ })).toBeDefined() @@ -2138,6 +4258,26 @@ test('a job figure the answer leaves blank reads ?, not "under 0.1"', () => { expect(line).toContain('? hours on all-purpose compute, ? DBUs') }) +test('a finding missing either end of its range is one with no dollar estimate, never "$0–$X"', () => { + const answer = JSON.parse(JSON.stringify(ANSWER)) + delete answer.metadata.report.findings[0].monthly_min + const finding = toView(answer.metadata)?.findings[0] + expect(finding?.monthlyMin).toBe(0) + expect(finding?.monthlyMax).toBe(0) + const blank = JSON.parse(JSON.stringify(ANSWER)) + blank.metadata.report.findings[0].monthly_min = ' ' + expect(toView(blank.metadata)?.findings[0]?.monthlyMax).toBe(0) +}) + +test('the fix request for a finding missing an end of its range asks with no dollar estimate, as the pane shows it', () => { + const answer = JSON.parse(JSON.stringify(ANSWER)) + delete answer.metadata.report.findings[0].monthly_min + const request = toView(answer.metadata)?.findings[0]?.fixRequest ?? '' + expect(request).toContain('no dollar estimate') + expect(request).toContain('Migrate Classic/Pro to Serverless, no dollar estimate.') + expect(request).not.toContain('?–$') +}) + test('/savings gives no note for a shell -c script behind a word its reader does not take for an option', async ($, on) => { for (const command of ["bash 2>/dev/null -c 'databricks bundle deploy'", "zsh --emulate sh -c 'databricks bundle deploy'", "bash -oc pipefail 'databricks bundle deploy'"]) { expect(runsDatabricksCompute(command)).toBe(false) @@ -2170,7 +4310,7 @@ test('a /clear in the same tick as /savings drops that run: nothing lands in the test('a skipped check whose reason is not text, or carries control characters, is drawn on one line without failing the run', async ($, on) => { const answer = JSON.parse(JSON.stringify(ANSWER)) answer.metadata.skipped = [{ check: 'Idle Cluster Detection', reason: 42 }, { check: 'Over-Sized Warehouse', reason: 'refused\n\u001b[2J by the warehouse.' }, { reason: 'no name' }] - const view = toViewOf(answer.metadata) + const view = toView(answer.metadata) expect(view?.skipped).toEqual(['Idle Cluster Detection (42)', 'Over-Sized Warehouse (refused [2J by the warehouse)', '? (no name)']) const { clock } = await start($, on, { answer }) await savings($) @@ -2186,7 +4326,7 @@ test('Run again pressed in the same tick as a /clear starts nothing, and /saving await savings($) await clock.settle() expect(runs.length).toBe(1) - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const ui = await mountFull($) await ui.press({ key: 'again' }) // The press is scheduled but has not started when the session ends. await $.session.end({ reason: 'clear' } as any) @@ -2250,7 +4390,7 @@ for (const step of ['pane open', 'version probe', 'tool run', 'baseline read', ' }) } -/** What `tool run` prints around core's own report for the testkit's synthetic facts. */ +/** What `finops_databricks_savings` prints around core's own report for the testkit's synthetic facts. */ function coreAnswer() { return { status: 'ok', @@ -2259,7 +4399,7 @@ function coreAnswer() { metadata: { success: true, window: { start: '2026-11-10', end: '2026-11-17' }, - warehouse: 'synth_conn', + warehouse: 'dbxmega', ran_on: 'wh-synth-pro', warehouses_checked: DATABRICKS_FACTS.warehouses.length, clusters_checked: DATABRICKS_FACTS.clusters.length, @@ -2272,47 +4412,110 @@ function coreAnswer() { } } +/** What `finops_snowflake_savings` prints around core's own report for the testkit's synthetic facts. */ +function coreSnowflakeAnswer() { + const price = SNOWFLAKE_FACTS.price_per_credit + return { + status: 'ok', + title: 'Snowflake Savings', + output: 'Snowflake savings', + metadata: { + success: true, + window: { start: '2026-11-10', end: '2026-11-17' }, + warehouse: 'sfmega', + ran_on: 'SYNTH_MULTI', + warehouses_checked: SNOWFLAKE_FACTS.warehouses.length, + price: { per_credit: price, source: 'rate_sheet', as_of: '2026-11-16' }, + skipped: [], + limited: [], + warehouses: SNOWFLAKE_FACTS.warehouses.map(one => ({ + id: one.warehouse_id, + name: one.warehouse_name, + type: one.warehouse_type, + size: one.warehouse_size, + window_cost: one.usage_days.reduce((sum, day) => sum + day.credits_used, 0) * price, + })), + report: JSON.parse(JSON.stringify(SNOWFLAKE_REPORT)), + }, + } +} + /** What the pane draws in place of a value it lacks, or a value read from a field core does not send. */ const UNREAL = /\?|undefined|NaN/ +const kindsOf = (report: { findings: readonly { evidence: { kind: string } }[] }) => [...new Set(report.findings.map(one => one.evidence.kind))].sort() +const drawnOf = async (ui: any) => [ + ...((await ui.findAll({ type: 'Text' })) as any[]).map(one => String(one.text)), + ...((await ui.findAll({ type: 'Button' })) as any[]).map(one => String(one.props.label)), +] + +test('every finding kind core returns is drawn from its own fields: no "?", "undefined" or "NaN" on the slim pane, Show all, a fix draft, a what-if, the report page, the notice, the status line or the band', async ($, on) => { + // Core's answers hold every kind each platform has; Underutilized Cluster carries no dollar estimate. + expect(kindsOf(DATABRICKS_REPORT)).toEqual(['idle_cluster', 'job_on_all_purpose', 'over_sized', 'serverless']) + expect(kindsOf(SNOWFLAKE_REPORT)).toEqual(['downsize_warehouse', 'frequent_restart', 'high_idle_time', 'underutilized_cluster']) + expect(SNOWFLAKE_REPORT.findings.find(one => one.check_id === 'underutilized_cluster')).toMatchObject({ monthly_min: 0, monthly_max: 0 }) + + // Each finding's evidence, the one fact the slim pane and the tool-row note quote, and its fix request. + for (const [metadata, platform] of [ + [coreAnswer().metadata, 'databricks'], + [coreSnowflakeAnswer().metadata, 'snowflake'], + ] as const) { + const view = toView(metadata as any, platform)! + expect(view.findings.length).toBe(metadata.report.findings.length) + expect(view.findings.flatMap(one => [one.title, one.fact, one.fixRequest, ...one.evidence]).filter(line => UNREAL.test(line))).toEqual([]) + } -test('every finding kind core returns is drawn from its own fields: no "?", "undefined" or "NaN" in the pane, a fix draft, a what-if, the notice or the band', async ($, on) => { - const files = { [`${ROOT}/infra/warehouses.tf`]: 'resource "databricks_sql_endpoint" "pro" {\n name = "synth_pro"\n cluster_size = "Large"\n}\n' } - const { clock, toasts, fills } = await start($, on, { answer: coreAnswer(), files }) + const files = { + [`${ROOT}/dbt_project.yml`]: 'name: acme\n', + [`${ROOT}/infra/warehouses.tf`]: 'resource "databricks_sql_endpoint" "pro" {\n name = "synth_pro"\n cluster_size = "Large"\n}\n', + } + const { clock, toasts, fills, written, statuses } = await start($, on, { list: BOTH, answer: coreAnswer(), snowflake: coreSnowflakeAnswer(), files }) await savings($) await clock.settle() - expect([...new Set(DATABRICKS_REPORT.findings.map(one => one.evidence.kind))].sort()).toEqual(['idle_cluster', 'job_on_all_purpose', 'over_sized', 'serverless']) + const slim = await $.ui.mount({ ...PANE, surface: 'terminal' }) + expect((await drawnOf(slim)).filter(text => UNREAL.test(text))).toEqual([]) + await slim.unmount() - const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) - const drawn = async () => [ - ...((await ui.findAll({ type: 'Text' })) as any[]).map(one => String(one.text)), - ...((await ui.findAll({ type: 'Button' })) as any[]).map(one => String(one.props.label)), - ] - const pane = await drawn() - for (const one of DATABRICKS_REPORT.findings) { - expect(pane.some(text => text.startsWith(`${one.resource_name} (workspace ${one.workspace_id}) · ${one.title} · $`))).toBe(true) - } - expect(pane).toContain('All-purpose cluster 100% idle across 5 active days (zombie), average worker CPU 3%, peak 10%') + const ui = await mountFull($) + const full = await drawnOf(ui) + expect(full).toContain('SYNTH_MULTI · Underutilized Cluster · no dollar estimate') + expect(full).toContain('The highest of its 2 clusters was barely needed on 7 days (up to 80% idle)') + expect(full).toContain('All-purpose cluster 100% idle across 5 active days (zombie), average worker CPU 3%, peak 10%') // Core's nulls: no auto-termination setting is off, no size is left out, and a pattern core names `unknown` is not shown. - expect(pane).toContain('All-purpose cluster 50% idle across 4 active days, average worker CPU 20%, peak 70%') - expect(pane).toContain('Auto-termination off; $400.00 billed on all-purpose compute over 7 days') - expect(pane).toContain('PRO warehouse, 92% idle over 5.6 running hours (900 queries)') - expect(pane).toContain('$0.750 a DBU now; a job cluster would be about $0.450 (estimated: the workspace billed no jobs compute)') - expect(pane.filter(text => UNREAL.test(text))).toEqual([]) + expect(full).toContain('All-purpose cluster 50% idle across 4 active days, average worker CPU 20%, peak 70%') + expect(full).toContain('Auto-termination off; $400.00 billed on all-purpose compute over 7 days') + expect(full).toContain('PRO warehouse, 92% idle over 5.6 running hours (900 queries)') + expect(full).toContain('$0.750 a DBU now; a job cluster would be about $0.450 (estimated: the workspace billed no jobs compute)') + expect(full.filter(text => UNREAL.test(text))).toEqual([]) - for (let at = 0; at < DATABRICKS_REPORT.findings.length; at++) await ui.press({ key: `fix-${at}` }) + const findings = DATABRICKS_REPORT.findings.length + SNOWFLAKE_REPORT.findings.length + for (let at = 0; at < findings; at++) await ui.press({ key: `fix-${at}` }) await clock.settle() - expect(fills.length).toBe(DATABRICKS_REPORT.findings.length) + expect(fills.length).toBe(findings) expect(fills.filter(text => UNREAL.test(text))).toEqual([]) for (const [row, one] of DATABRICKS_REPORT.what_if.entries()) { for (let k = 0; k < one.choices.length; k++) { await ui.press({ key: `whatif-${row}-${k}` }) await clock.settle() - expect((await drawn()).filter(text => UNREAL.test(text))).toEqual([]) + expect((await drawnOf(ui)).filter(text => UNREAL.test(text))).toEqual([]) } } + + await ui.press({ key: 'share' }) + await clock.settle() + const page = written.get(`${ROOT}/target/.altimate-lineage/savings-report.html`)! + expect(page).toContain('The highest of its 2 clusters was barely needed') + expect(page).toContain('What if synth_classic in workspace 1002 (') + const shown = page + .replace(/ +
+

Warehouse savings report

+
Built ${escape(builtAt)} on this machine from read-only checks on your own connections. Nothing was sent to Altimate.
+

${total.resources > 0 ? `${escape(range(total.min, total.max))} a month` : findings > 0 ? `${findings} finding${findings === 1 ? '' : 's'}, no dollar estimate` : nothingChecked ? 'Nothing was checked' : 'No savings found'}

+
${total.resources > 0 ? `on ${total.resources} resource${total.resources === 1 ? '' : 's'}, ${priced} and the last ${windows.join(' and ')} days' rate, each counted once at its largest saving` : findings > 0 ? 'see each finding below' : nothingChecked ? 'none of the checks could run: see why below' : 'by the checks that ran'}${partial && !nothingChecked ? '. Some checks did not run in full: see below.' : ''}
+${failed.map(one => `

The last ${one.platform ? `${escape(PLATFORM_NAME[one.platform])} ` : ''}check did not finish: ${escape(one.text)}

`).join('\n')} +${sections.join('\n')} +

See every check in Altimate

+
+` +} diff --git a/plugins/altimate-code/hooks/savings-rows.test.ts b/plugins/altimate-code/hooks/savings-rows.test.ts new file mode 100644 index 0000000..b41571c --- /dev/null +++ b/plugins/altimate-code/hooks/savings-rows.test.ts @@ -0,0 +1,232 @@ +import { expect, test } from 'claude-code/testing' + +import type { SavingsConnection, SavingsFinding, SavingsKept, SavingsView } from '../types' +import { + dbtFlag, + dbtInline, + dbtMovesFirst, + dbtRunOf, + factsOfConnections, + findingOn, + identityOf, + parseWarehouseList, + readYaml, + refOfConnection, + refOfProfile, + rowNote, + sqlCallOf, + scopeOf, + warehouseOfHttpPath, + withFacts, +} from './savings-rows' + +const finding = (over: Partial): SavingsFinding => ({ + checkId: 'wh_oversized', + title: 'Over-Sized Warehouse', + resourceType: 'sql_warehouse', + resourceId: 'wh-1', + resourceName: 'Classic', + matchName: 'Classic', + workspace: null, + workspaceId: null, + monthlyMin: 10, + monthlyMax: 20, + evidence: [], + fact: '95% idle', + dailyCost: 1, + config: { size: 'SMALL', type: 'CLASSIC' }, + fixRequest: '', + ...over, +}) + +const kept = (platform: SavingsView['platform'], findings: SavingsFinding[], ranOn: string | null = null, scope: string | null = null, connection: string | null = null): SavingsKept => ({ savedAt: 0, view: { platform, connection, scope, ranOn, findings } as SavingsView }) + +test('the connection list is read from warehouse_list\'s table, in its order', () => { + expect(parseWarehouseList('Name | Type | Database\n-----|------|--------\ndbx | databricks | -\nsf | Snowflake | DB\npg | postgres | app\n\nTables:\nx | y | z')).toEqual([ + { name: 'dbx', platform: 'databricks' }, + { name: 'sf', platform: 'snowflake' }, + { name: 'pg', platform: null }, + ]) + // A shadowed connection adds a column. + expect(parseWarehouseList('Name | Type | Database | Served by\ndbx | databricks | - | local')).toEqual([{ name: 'dbx', platform: 'databricks' }]) + expect(parseWarehouseList('No warehouse connections configured.')).toEqual([]) +}) + +test('only a SQL warehouse path names a warehouse', () => { + expect(warehouseOfHttpPath('/sql/1.0/warehouses/abc123')).toBe('abc123') + expect(warehouseOfHttpPath('sql/1.0/endpoints/abc123/')).toBe('abc123') + expect(warehouseOfHttpPath('/sql/protocolv1/o/1/0101-abc')).toBeNull() + expect(warehouseOfHttpPath(undefined)).toBeNull() +}) + +test('a connections file gives up where each connection runs and nothing else', () => { + const file = JSON.stringify({ + d: { type: 'databricks', server_hostname: 'https://H.example.com/', http_path: '/sql/1.0/warehouses/w1', access_token: 'SECRET' }, + alias: { type: 'databricks', httpPath: '/sql/1.0/warehouses/w2' }, + s: { type: 'snowflake', warehouse: 'WH', account: 'AB123.snowflakecomputing.com', password: 'SECRET' }, + c: { type: 'databricks', http_path: '/sql/protocolv1/o/1/2' }, + p: { type: 'postgres', host: 'h', warehouse: 'not-this', account: 'not-this' }, + bad: 'text', + }) + const facts = factsOfConnections(file) + expect(facts).toEqual({ + d: { warehouse: 'w1', account: null, place: 'h.example.com' }, + alias: { warehouse: 'w2', account: null, place: null }, + s: { warehouse: 'WH', account: 'ab123', place: 'ab123' }, + c: { warehouse: null, account: null, place: null }, + p: { warehouse: null, account: null, place: null }, + }) + expect(JSON.stringify(facts)).not.toContain('SECRET') + expect(factsOfConnections('{not json')).toEqual({}) + expect(factsOfConnections('[1]')).toEqual({}) + expect(withFacts([{ name: 'd', platform: 'databricks' }, { name: 'x', platform: null }], facts)).toEqual([ + { name: 'd', platform: 'databricks', warehouse: 'w1', account: null }, + { name: 'x', platform: null, warehouse: null, account: null }, + ]) +}) + +test('a project connection replaces the global one of its name whole', () => { + const merged = { ...factsOfConnections('{"s":{"type":"snowflake","warehouse":"GLOBAL_WH","account":"a"}}'), ...factsOfConnections('{"s":{"type":"snowflake","account":"b"}}') } + expect(merged.s).toEqual({ warehouse: null, account: 'b', place: 'b' }) +}) + +test('an answer belongs to the workspace or account, else to the project', () => { + expect(identityOf('databricks', { warehouse: 'w', account: null, place: 'h' }, '/repo')).toBe('databricks:h') + expect(identityOf('snowflake', { warehouse: 'w', account: 'a', place: 'a' }, '/repo')).toBe('snowflake:a') + expect(identityOf('databricks', { warehouse: 'w', account: null, place: null }, '/repo')).toBe('project:/repo') + expect(identityOf('snowflake', undefined, '/other')).toBe('project:/other') +}) + +test('a SQL call is recognized over MCP and in a shell, and nothing else is', () => { + const tool = 'mcp__plugin_altimate-code_altimate-code__sql_execute' + expect(sqlCallOf(tool, { warehouse: 'a' })).toEqual(['a']) + expect(sqlCallOf(tool, {})).toEqual([null]) + expect(sqlCallOf(tool, { queries: [{ warehouse: 'a' }, { warehouse: 'b' }, {}] })).toEqual(['a', 'b', null]) + expect(sqlCallOf(tool, { warehouse: 'top', queries: [{}, { warehouse: 'b' }] })).toEqual(['top', 'b']) + expect(sqlCallOf('mcp__altimate-code__sql_explain', { warehouse: 'a' })).toEqual(['a']) + expect(sqlCallOf('mcp__plugin_altimate-code_altimate-code__schema_inspect', { warehouse: 'a' })).toBeNull() + expect(sqlCallOf('mcp__other__sql_execute', { warehouse: 'a' })).toBeNull() + expect(sqlCallOf('Read', { file_path: 'x' })).toBeNull() + expect(sqlCallOf('Bash', { command: `altimate tool run sql_execute --args '{"warehouse":"a"}'` })).toEqual(['a']) + expect(sqlCallOf('Bash', { command: `cd x && altimate-code tool run sql_explain --args "{\\"warehouse\\":\\"b\\"}" --json` })).toEqual(['b']) + expect(sqlCallOf('Bash', { command: `altimate tool run sql_execute --args '{broken'` })).toBeNull() + expect(sqlCallOf('Bash', { command: `altimate tool run schema_inspect --args '{"warehouse":"a"}'` })).toBeNull() + expect(sqlCallOf('Bash', { command: 'echo altimate' })).toBeNull() + // With --allow-write and no connection, what it runs on is not the first connection for certain. + expect(sqlCallOf('Bash', { command: `altimate tool run sql_execute --args '{"query":"x"}' --allow-write` })).toBeNull() + expect(sqlCallOf('Bash', { command: `altimate tool run sql_execute --args '{"warehouse":"a"}' --allow-write` })).toEqual(['a']) +}) + +test('a connection runs on its configured compute, else the one its kept run went through', () => { + const list: SavingsConnection[] = [ + { name: 'pg', platform: null, warehouse: null, account: null }, + { name: 'dbx', platform: 'databricks', warehouse: 'w1', account: null }, + { name: 'env', platform: 'databricks', warehouse: null, account: null }, + { name: 'sf', platform: 'snowflake', warehouse: 'WH', account: 'acct' }, + { name: 'sf2', platform: 'snowflake', warehouse: 'WH', account: null }, + ] + expect(refOfConnection('dbx', list, {})).toEqual({ platform: 'databricks', warehouse: 'w1', scope: null }) + expect(refOfConnection('env', list, { x: kept('databricks', [], 'w9', null, 'env') })).toEqual({ platform: 'databricks', warehouse: 'w9', scope: null }) + expect(refOfConnection('env', list, {})).toBeNull() + expect(refOfConnection('nope', list, {})).toBeNull() + expect(refOfConnection('sf', list, {})).toEqual({ platform: 'snowflake', warehouse: 'WH', scope: 'acct' }) + // With no account known, the connection itself is the scope. + expect(refOfConnection('sf2', list, {})?.scope).toBe('sf2') + // The default is the first connection, even when that is not a warehouse this checks. + expect(refOfConnection(null, list, {})).toBeNull() + expect(refOfConnection(null, list.slice(1), {})?.warehouse).toBe('w1') + expect(scopeOf('databricks', list[1], 'dbx')).toBeNull() + expect(scopeOf('snowflake', undefined, 'named')).toBe('named') +}) + +test('a finding is matched to compute exactly, on its own platform and account, largest saving first', () => { + const small = finding({ monthlyMax: 20 }) + const large = finding({ monthlyMax: 90, title: 'Migrate' }) + const cluster = finding({ resourceType: 'cluster', resourceId: 'w2' }) + const sf = finding({ resourceId: '7', resourceName: 'COMPUTE_WH', matchName: 'COMPUTE_WH' }) + const all = { a: kept('databricks', [small, large, cluster]), s: kept('snowflake', [sf], 'COMPUTE_WH', 'acct-a') } + const dbx = (warehouse: string) => ({ platform: 'databricks' as const, warehouse, scope: null }) + expect(findingOn(dbx('wh-1'), all)).toBe(large) + expect(findingOn(dbx('w2'), all)).toBeNull() + expect(findingOn(dbx('WH-1'), all)).toBeNull() + // Snowflake folds unquoted names to upper case, so a profile's `compute_wh` is that warehouse. + expect(findingOn({ platform: 'snowflake', warehouse: 'compute_wh', scope: 'acct-a' }, all)).toBe(sf) + expect(findingOn({ platform: 'snowflake', warehouse: 'wh-1', scope: 'acct-a' }, all)).toBeNull() + // The same name in another account is another warehouse. + expect(findingOn({ platform: 'snowflake', warehouse: 'COMPUTE_WH', scope: 'acct-b' }, all)).toBeNull() + // A connection names its warehouse by id alone: an id flagged in two workspaces gets no note, not one of theirs. + const shared = { a: kept('databricks', [finding({ workspaceId: '111', monthlyMax: 20 }), finding({ workspaceId: '222', monthlyMax: 90 })]) } + expect(findingOn(dbx('wh-1'), shared)).toBeNull() + expect(findingOn(dbx('wh-1'), { a: kept('databricks', [finding({ workspaceId: '111', monthlyMax: 20 }), finding({ workspaceId: '111', monthlyMax: 90, title: 'Migrate' })]) })?.title).toBe('Migrate') + expect(rowNote(large)).toBe('Classic: 95% idle · $10.00–$90.00 a month → /savings') + expect(rowNote(finding({ monthlyMin: 0, monthlyMax: 0 }))).toBe('Classic: 95% idle · no dollar estimate → /savings') +}) + +test('only a dbt run or build written out in full counts', () => { + expect(dbtRunOf('cd x && dbt run -s orders')?.subcommand).toBe('run') + expect(dbtRunOf('uv run dbt build --target prod')?.target).toBe('prod') + expect(dbtRunOf('dbt test')).toBeNull() + expect(dbtRunOf('dbt run --target $T')).toBeNull() + expect(dbtRunOf('ls')).toBeNull() + const command = 'dbt run --profiles-dir ./conf --project-dir=app --profile "acme"' + const run = dbtRunOf(command)! + expect(dbtFlag(command, run, 'profiles-dir')).toBe('./conf') + expect(dbtFlag(command, run, 'project-dir')).toBe('app') + expect(dbtFlag(command, run, 'profile')).toBe('acme') + expect(dbtFlag(command, run, 'target')).toBeNull() + const inline = 'DBT_PROFILES_DIR=/conf dbt run' + expect(dbtInline(inline, dbtRunOf(inline)!, 'DBT_PROFILES_DIR')).toBe('/conf') + expect(dbtInline('dbt run', dbtRunOf('dbt run')!, 'DBT_PROFILES_DIR')).toBeNull() + const elsewhere = 'uv run --directory /other dbt run' + expect(dbtMovesFirst(elsewhere, dbtRunOf(elsewhere)!)).toBe(true) + const exported = 'export DBT_TARGET=prod; dbt run' + expect(dbtMovesFirst(exported, dbtRunOf(exported)!)).toBe(true) + const moved = 'cd sub && dbt run' + expect(dbtMovesFirst(moved, dbtRunOf(moved)!)).toBe(true) + expect(dbtMovesFirst('dbt run', dbtRunOf('dbt run')!)).toBe(false) +}) + +const PROFILES = `# profiles +config: + send_anonymous_usage_stats: false +acme: + target: dev # the default + outputs: + dev: + type: databricks + http_path: "/sql/1.0/warehouses/w1" + token: "{{ env_var('T') }}" + sf: + type: snowflake + account: AB123 + warehouse: TRANSFORM_WH + noaccount: + type: snowflake + warehouse: TRANSFORM_WH + templated: + type: snowflake + account: AB123 + warehouse: "{{ env_var('WH') }}" + pg: + type: postgres + host: localhost +plain: + outputs: + default: + type: snowflake + account: "{{ env_var('ACCOUNT') }}" + warehouse: 'BI_WH' +` + +test('a dbt target gives its warehouse; what it does not state plainly gives nothing', () => { + expect(readYaml('a: 1\nb:\n c: "x"\n').b).toEqual({ c: 'x' }) + expect(refOfProfile(PROFILES, 'acme', null)).toEqual({ platform: 'databricks', warehouse: 'w1', scope: null }) + expect(refOfProfile(PROFILES, 'acme', 'sf')).toEqual({ platform: 'snowflake', warehouse: 'TRANSFORM_WH', scope: 'ab123' }) + // A Snowflake target whose account is not stated could be any account's warehouse of that name. + expect(refOfProfile(PROFILES, 'acme', 'noaccount')).toBeNull() + expect(refOfProfile(PROFILES, 'plain', null)).toBeNull() + expect(refOfProfile(PROFILES, 'acme', 'templated')).toBeNull() + expect(refOfProfile(PROFILES, 'acme', 'pg')).toBeNull() + expect(refOfProfile(PROFILES, 'acme', 'missing')).toBeNull() + expect(refOfProfile(PROFILES, 'nope', null)).toBeNull() +}) diff --git a/plugins/altimate-code/hooks/savings-rows.ts b/plugins/altimate-code/hooks/savings-rows.ts new file mode 100644 index 0000000..cc6f945 --- /dev/null +++ b/plugins/altimate-code/hooks/savings-rows.ts @@ -0,0 +1,223 @@ +// Which warehouse a tool call runs on, for the one-line note under its row. Everything here reads what +// is already on this machine: altimate-code's connection list and config, dbt's profiles and the kept +// /savings answers. None of it queries a warehouse. +import type { SavingsConnection, SavingsFinding, SavingsKept, SavingsPlatform, SavingsWarehouseRef } from '../types' +import { parseDbtCommand, type DbtInvocation } from './dbt-command' +import { amount, oneLine } from './savings-format' + +const platformOfType = (type: unknown): SavingsPlatform | null => { + const name = String(type ?? '').trim().toLowerCase() + return name === 'databricks' || name === 'snowflake' ? name : null +} + +/** The connections in `warehouse_list`'s table (`Name | Type | Database`, a `Served by` column when one is shadowed), in its order. */ +export function parseWarehouseList(output: string): { name: string; platform: SavingsPlatform | null }[] { + const rows: { name: string; platform: SavingsPlatform | null }[] = [] + const lines = output.split('\n') + const header = lines.findIndex(line => /^Name \| Type \|/.test(line)) + if (header < 0) return rows + for (const line of lines.slice(header + 1)) { + if (!line.trim()) break + if (/^-+\s*\|/.test(line)) continue + const [name, type] = line.split(' | ') + if (name && type) rows.push({ name: name.trim(), platform: platformOfType(type) }) + } + return rows +} + +/** The SQL warehouse a Databricks `http_path` goes through; null for a cluster's path or anything else. */ +export function warehouseOfHttpPath(path: unknown): string | null { + return /^\/?sql\/1\.0\/(?:warehouses|endpoints)\/([^/?#\s]+)\/?$/.exec(String(path ?? '').trim())?.[1] ?? null +} + +const computeOf = (platform: SavingsPlatform | null, config: Record): string | null => { + // `httpPath` is the alias altimate-code's driver also takes. + if (platform === 'databricks') return warehouseOfHttpPath(config.http_path ?? config.httpPath) + if (platform === 'snowflake' && typeof config.warehouse === 'string') return config.warehouse.trim() || null + return null +} + +/** A Snowflake account as written in a connection or profile, in the one form they are compared in. */ +const accountOf = (value: unknown): string | null => + typeof value === 'string' && value.trim() && !value.includes('{{') ? value.trim().toLowerCase().replace(/\.snowflakecomputing\.com$/, '') : null + +/** What a run's answer or a tool call is scoped to: on Snowflake the account, else the connection, since a warehouse name repeats across accounts. */ +export const scopeOf = (platform: SavingsPlatform, connection: Pick | null | undefined, name: string | null): string | null => + platform === 'snowflake' ? (connection?.account ?? connection?.name ?? name) : null + +/** What a connection's config says about where it runs; nothing else is read from it. */ +export type ConnectionFacts = { + warehouse: string | null + account: string | null + /** The Databricks workspace host or Snowflake account it reaches. */ + place: string | null +} + +const hostOf = (config: Record): string | null => { + const host = [config.server_hostname, config.serverHostname, config.host].find(value => typeof value === 'string' && value.trim()) + return typeof host === 'string' && !host.includes('{{') ? host.trim().toLowerCase().replace(/^https?:\/\//, '').replace(/\/.*$/, '') || null : null +} + +/** + * What a kept answer belongs to. The plugin's store is one file for every project on the machine, and two + * projects can each have a connection called `prod`, so an answer is tied to the workspace or account its + * connection reaches, or to the project it ran in when the config does not say. + */ +export const identityOf = (platform: SavingsPlatform, facts: ConnectionFacts | undefined, root: string | null): string => + facts?.place ? `${platform}:${facts.place}` : `project:${root ?? ''}` + +/** + * The compute of each connection in a `connections.json`. The file holds credentials: only these fields + * are taken from it, and nothing else is kept or passed on. Every connection gets an entry, so one in the + * project's file replaces the global one of that name whole, as altimate-code reads them. + */ +export function factsOfConnections(text: string): Record { + let parsed: unknown + try { + parsed = JSON.parse(text) + } catch { + return {} + } + const out: Record = {} + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return out + for (const [name, config] of Object.entries(parsed as Record)) { + if (!config || typeof config !== 'object') continue + const fields = config as Record + const platform = platformOfType(fields.type) + const account = platform === 'snowflake' ? accountOf(fields.account) : null + out[name] = { warehouse: computeOf(platform, fields), account, place: platform === 'databricks' ? hostOf(fields) : account } + } + return out +} + +/** The list joined with what the config files say about each connection. */ +export function withFacts(list: { name: string; platform: SavingsPlatform | null }[], facts: Record): SavingsConnection[] { + return list.map(one => ({ ...one, warehouse: facts[one.name]?.warehouse ?? null, account: facts[one.name]?.account ?? null })) +} + +// The altimate-code tools that run SQL on a warehouse; without a `warehouse` they use the first connection. +const SQL_TOOLS = new Set(['sql_execute', 'sql_explain']) +const MCP_TOOL = /^mcp__.*altimate-code__([a-z_]+)$/ +const CLI_CALL = /(?:^|[\s;&|(])altimate(?:-code)?\s+tool\s+run\s+([a-z_]+)\s+--args\s+(?:'([^']*)'|"((?:[^"\\]|\\.)*)")/ + +/** The connection each statement of an altimate-code SQL call runs on; null for one left to the default. */ +function connectionsAsked(input: unknown): (string | null)[] { + const call = (input ?? {}) as { warehouse?: unknown; queries?: unknown } + const named = (value: unknown) => (typeof value === 'string' && value !== '' ? value : null) + const top = named(call.warehouse) + return Array.isArray(call.queries) && call.queries.length > 0 ? call.queries.map(one => named((one as { warehouse?: unknown } | null)?.warehouse) ?? top) : [top] +} + +/** The altimate-code SQL call in a tool row (over MCP, or `altimate tool run` in a shell), or null. */ +export function sqlCallOf(tool: string, input: unknown): (string | null)[] | null { + const mcp = MCP_TOOL.exec(tool) + if (mcp) return SQL_TOOLS.has(mcp[1]!) ? connectionsAsked(input) : null + if (tool !== 'Bash') return null + const command = String((input as { command?: unknown } | null)?.command ?? '') + const cli = CLI_CALL.exec(command) + if (!cli || !SQL_TOOLS.has(cli[1]!)) return null + try { + const asked = connectionsAsked(JSON.parse(cli[2] ?? cli[3]!.replace(/\\(.)/g, '$1'))) + // With --allow-write and no connection named, altimate-code may go through dbt instead of the first connection. + return asked.includes(null) && /\s--allow-write\b/.test(command) ? null : asked + } catch { + return null + } +} + +/** The compute a connection runs on: its config, else the warehouse its kept run went through. */ +export function refOfConnection(name: string | null, connections: readonly SavingsConnection[], kept: Record): SavingsWarehouseRef | null { + const connection = name === null ? connections[0] : connections.find(one => one.name === name) + if (!connection?.platform) return null + const warehouse = connection.warehouse ?? Object.values(kept).find(one => one.view.connection === connection.name)?.view.ranOn + return warehouse ? { platform: connection.platform, warehouse, scope: scopeOf(connection.platform, connection, connection.name) } : null +} + +/** The kept finding with the largest saving on that compute, or null. */ +export function findingOn(ref: SavingsWarehouseRef, kept: Record): SavingsFinding | null { + const same = (one: SavingsFinding) => + ref.platform === 'databricks' + ? one.resourceType === 'sql_warehouse' && one.resourceId === ref.warehouse + : (one.resourceType === 'warehouse' || one.resourceType === 'sql_warehouse') && [one.resourceId, one.matchName].some(name => name.toLowerCase() === ref.warehouse.toLowerCase()) + let best: SavingsFinding | null = null + const workspaces = new Set() + for (const { view } of Object.values(kept)) { + if (view.platform !== ref.platform || view.scope !== ref.scope) continue + for (const one of view.findings) { + if (!same(one)) continue + workspaces.add(one.workspaceId ?? '') + if (!best || one.monthlyMax > best.monthlyMax) best = one + } + } + // A connection names its warehouse by id, which repeats across workspaces: one flagged in several gets no note, + // rather than another workspace's saving. + return workspaces.size > 1 ? null : best +} + +/** The line under a tool row. */ +export const rowNote = (one: SavingsFinding) => `${oneLine(one.resourceName)}: ${one.fact} · ${amount(one.monthlyMin, one.monthlyMax)} → /savings` + +// --- dbt: a `dbt run` or `dbt build` runs on its target's warehouse. + +/** The first `dbt run` or `dbt build` a command line states fully, or null. */ +export function dbtRunOf(command: string): DbtInvocation | null { + return parseDbtCommand(command).find(one => !one.dynamic && (one.subcommand === 'run' || one.subcommand === 'build')) ?? null +} + +/** Whether the line moves or reconfigures dbt before it runs, so what the session's files say may not apply. */ +export const dbtMovesFirst = (command: string, invocation: DbtInvocation) => + /(?:^|[\s;&|(])(?:cd|pushd|export\s+DBT_\w+=)/.test(command.slice(0, invocation.start)) || /\s--(?:directory|project|cwd)\b/.test(invocation.binary) + +/** A variable as set in front of the invocation, or null. */ +export function dbtInline(command: string, invocation: DbtInvocation, name: 'DBT_PROFILES_DIR' | 'DBT_PROJECT_DIR'): string | null { + const value = new RegExp(`(?:^|\\s)${name}=("[^"]*"|'[^']*'|\\S+)`).exec(command.slice(invocation.start, invocation.end))?.[1] + return value ? value.replace(/^["']|["']$/g, '') : null +} + +/** The value of `--name value` or `--name=value` in the invocation's own text. */ +export function dbtFlag(command: string, invocation: DbtInvocation, name: string): string | null { + const text = command.slice(invocation.start, invocation.end) + const value = new RegExp(`(?:^|\\s)--${name}(?:=|\\s+)("[^"]*"|'[^']*'|\\S+)`).exec(text)?.[1] + return value ? value.replace(/^["']|["']$/g, '') : null +} + +type Yaml = { [key: string]: string | Yaml } + +/** The `key: value` and `key:` lines of a YAML file as nested maps; lists and anything fancier are skipped. */ +export function readYaml(text: string): Yaml { + const root: Yaml = {} + const stack: { indent: number; map: Yaml }[] = [{ indent: -1, map: root }] + for (const raw of text.split('\n')) { + const line = /^(\s*)([^\s#'"\-][^:#]*?|"[^"]+"|'[^']+')\s*:(?:\s+(.*?))?\s*$/.exec(raw) + if (!line) continue + const indent = line[1]!.length + while (stack.at(-1)!.indent >= indent) stack.pop() + const key = line[2]!.replace(/^["']|["']$/g, '') + const value = (line[3] ?? '').replace(/\s+#.*$/, '') + if (value === '') { + const map: Yaml = {} + stack.at(-1)!.map[key] = map + stack.push({ indent, map }) + } else { + stack.at(-1)!.map[key] = value.replace(/^["']|["']$/g, '') + } + } + return root +} + +/** The compute a dbt profile's target runs on; null when the profile does not state it plainly (a `{{ env_var() }}`, say). */ +export function refOfProfile(profiles: string, profile: string, target: string | null): SavingsWarehouseRef | null { + const entry = readYaml(profiles)[profile] + if (!entry || typeof entry !== 'object') return null + const name = target ?? (typeof entry.target === 'string' ? entry.target : 'default') + const outputs = entry.outputs + const output = outputs && typeof outputs === 'object' ? outputs[name] : null + if (!output || typeof output !== 'object') return null + const platform = platformOfType(output.type) + const compute = computeOf(platform, output) + if (!platform || !compute || compute.includes('{{')) return null + if (platform === 'databricks') return { platform, warehouse: compute, scope: null } + // Without its account a Snowflake target cannot be told from one of the same name elsewhere. + const scope = accountOf(output.account) + return scope ? { platform, warehouse: compute, scope } : null +} diff --git a/plugins/altimate-code/hooks/status-line.ts b/plugins/altimate-code/hooks/status-line.ts index 92eaced..c49c227 100644 --- a/plugins/altimate-code/hooks/status-line.ts +++ b/plugins/altimate-code/hooks/status-line.ts @@ -5,7 +5,7 @@ import { atom, read, update } from 'claude-code' import type { EngineInterface } from 'claude-code' /** The features, in the order the plugin calls them (features/index.ts calls each by name in this order). */ -export const FEATURE_IDS = ['runs', 'defer', 'toModel', 'comments', 'cost', 'health', 'sqlGraph', 'docs', 'cteProfile'] as const +export const FEATURE_IDS = ['runs', 'defer', 'toModel', 'comments', 'cost', 'health', 'sqlGraph', 'docs', 'cteProfile', 'savings'] as const export type FeatureId = (typeof FEATURE_IDS)[number] export type StatusPartId = 'integrations' | 'altimateCode' | FeatureId diff --git a/plugins/altimate-code/hooks/task-impact.tsx b/plugins/altimate-code/hooks/task-impact.tsx index d45dcc1..369b9c7 100644 --- a/plugins/altimate-code/hooks/task-impact.tsx +++ b/plugins/altimate-code/hooks/task-impact.tsx @@ -17,18 +17,18 @@ import { fingerprint, type ModelChange, modelLevelOf, - openersFor, - type Platform, planLines, reportData, reportHtml, summaryLines, summaryOf, unknownReach, - WINDOWS_EXPLORER, } from './impact-report' import { projectLayout } from './lineage-graph' import { modelsNamed, openPane, projectRoot } from './lineage' +import { openReport } from './open-report' + +export { openReport } export const REPORT_COMMAND = 'lineage-report' // Under the project's target/, which dbt already keeps out of git. @@ -481,33 +481,6 @@ async function planReady($: EngineInterface, e: { plan?: unknown; planFilePath?: $.ui.log(planLines(view).map(line => line.trim()).join(' · ')) } -/** Which opener family this machine has: macOS, Linux, WSL (Linux under Windows), or Windows itself. */ -async function platformOf($: EngineInterface): Promise { - // -r too: a WSL kernel's release names Microsoft, with no environment variable needed. - const uname = await $.process.run(['uname', '-sr'], { timeoutMs: 5_000 }).catch(() => null) - if (!uname || uname.exitCode !== 0) return 'windows' - if (/darwin/i.test(uname.stdout)) return 'mac' - if (/microsoft/i.test(uname.stdout)) return 'wsl' - if (await $.env.get('WSL_DISTRO_NAME').catch(() => undefined)) return 'wsl' - return /microsoft/i.test(await $.fs.read('/proc/version').catch(() => '')) ? 'wsl' : 'linux' -} - -/** Opens the report in the person's browser; false when no opener worked. */ -export async function openReport($: EngineInterface, path: string): Promise { - const platform = await platformOf($) - let wsl = {} - if (platform === 'wsl') { - const windows = await $.process.run(['wslpath', '-w', path], { timeoutMs: 5_000 }).catch(() => null) - wsl = { windowsPath: windows?.exitCode === 0 ? windows.stdout.trim() || null : null, explorerAtC: await $.fs.exists(WINDOWS_EXPLORER).catch(() => false) } - } - // The first that starts and exits as it does on success; one that cannot start, or fails, gives way to the next. - for (const opener of openersFor(platform, path, wsl)) { - const result = await $.process.run(opener.argv, { timeoutMs: 15_000 }).catch(() => null) - if (result && opener.okExits.includes(result.exitCode)) return true - } - return false -} - /** Builds the last task's report and opens it, for the button and the command; what to say about it. */ async function buildAndOpen($: EngineInterface): Promise { const done = await lastTask($) diff --git a/plugins/altimate-code/hooks/tool-chain.test.ts b/plugins/altimate-code/hooks/tool-chain.test.ts index d6286d1..3ece5c1 100644 --- a/plugins/altimate-code/hooks/tool-chain.test.ts +++ b/plugins/altimate-code/hooks/tool-chain.test.ts @@ -78,7 +78,7 @@ test('without context lines the result is passed on as it came', async () => { }) test('the features are listed in the stated order, and the status line joins its parts in it', () => { - expect(FEATURE_IDS).toEqual(['runs', 'defer', 'toModel', 'comments', 'cost', 'health', 'sqlGraph', 'docs', 'cteProfile']) + expect(FEATURE_IDS).toEqual(['runs', 'defer', 'toModel', 'comments', 'cost', 'health', 'sqlGraph', 'docs', 'cteProfile', 'savings']) expect(STATUS_ORDER).toEqual(['integrations', ...FEATURE_IDS, 'altimateCode']) // Parts join in that order whatever order they were set in; feature parts alone get the plugin's mark. expect(statusLineOf({ cost: '2 GB', integrations: '1 synced', runs: '3 runs' })).toBe('1 synced · 3 runs · 2 GB') diff --git a/plugins/altimate-code/hooks/usage.test.tsx b/plugins/altimate-code/hooks/usage.test.tsx index a410e41..26a7b86 100644 --- a/plugins/altimate-code/hooks/usage.test.tsx +++ b/plugins/altimate-code/hooks/usage.test.tsx @@ -449,7 +449,7 @@ const SAVINGS_ANSWER = { }, } -test('/savings sends no usage event: not for the command, its pane, its buttons or a second run', async ($, on) => { +test('/savings sends no usage event: not for the command, its pane, Show all, its buttons or a second run', async ($, on) => { const { clock, events, usage, savingsRuns } = await start($, on, { savings: SAVINGS_ANSWER }) // Usage is on and this fake CLI records it: the session start's event arrived. expect(usage().map(argv => argv[3])).toEqual(['plugin_session_start']) @@ -469,11 +469,15 @@ test('/savings sends no usage event: not for the command, its pane, its buttons expect(await pane.find({ type: 'Text', text: /^\$80\.64–\$101 a month$/ })).toBeDefined() await pane.press({ key: 'fix-0' }) await clock.settle() + await pane.press({ key: 'more' }) + await clock.settle() await pane.press({ key: 'whatif-0-0' }) await clock.settle() expect(await pane.find({ type: 'Text', text: /^As serverless: / })).toBeDefined() await pane.press({ key: 'again' }) await clock.settle() + await pane.press({ key: 'share' }) + await clock.settle() await pane.unmount() // Two runs of the check (the command and Run again), and not one usage event among them. expect(savingsRuns()).toBe(2) diff --git a/plugins/altimate-code/skills/altimate-code/SKILL.md b/plugins/altimate-code/skills/altimate-code/SKILL.md index 39d33b4..f8aaeb1 100644 --- a/plugins/altimate-code/skills/altimate-code/SKILL.md +++ b/plugins/altimate-code/skills/altimate-code/SKILL.md @@ -105,6 +105,7 @@ Arguments for the most used tools (`?` marks optional): | `sql_translate` | `{"sql", "source_dialect", "target_dialect"}` | | `finops_analyze_credits` | `{"warehouse"?, "days"?}` | | `finops_databricks_savings` | Do not call it yourself: ask the user to type `/savings [connection]`. That runs it read-only with telemetry and the tool daemon off, keeps the findings in the side pane, and only the user can start it (it may start their SQL warehouse, which bills) | +| `finops_snowflake_savings` | Do not call it yourself: ask the user to type `/savings [connection]`. That runs it read-only with telemetry and the tool daemon off, keeps the findings in the side pane, and only the user can start it (it may resume their warehouse, which bills) | | `workspace_context` | `{"include_tools"?, "refresh"?}` | | `workspace_skill` | `{"workspace_token", "name"}` | | `workspace_execute` | `{"workspace_token", "operation", "arguments"}` | diff --git a/plugins/altimate-code/types/index.d.ts b/plugins/altimate-code/types/index.d.ts index d6d64bb..d3b8e05 100644 --- a/plugins/altimate-code/types/index.d.ts +++ b/plugins/altimate-code/types/index.d.ts @@ -635,41 +635,99 @@ export interface CteProfileState { /** A warehouse's settings as the CLI listed them: each its value, or null where the CLI did not read it. */ export type WarehouseConfig = { size: string | null; type: string | null } +/** The warehouse platforms /savings can check. */ +export type SavingsPlatform = 'databricks' | 'snowflake' + +/** An altimate-code connection as /savings knows it: never its credentials. */ +export type SavingsConnection = { + name: string + /** Null for a connection of any other type. */ + platform: SavingsPlatform | null + /** The compute it runs on: a Databricks SQL warehouse id, or a Snowflake warehouse name; null when its config does not say. */ + warehouse: string | null + /** The Snowflake account it reaches; null when its config does not say, and for anything else. */ + account: string | null +} + +/** The compute a tool call runs on. */ +export type SavingsWarehouseRef = { + platform: SavingsPlatform + warehouse: string + /** Which Snowflake account that name is in: a name means nothing across accounts. Null on Databricks, whose ids are unique. */ + scope: string | null +} + +/** One finding of a /savings run, as the pane draws it. */ +export type SavingsFinding = { + /** The check that raised it, by its id in Altimate's catalog. */ + checkId: string + title: string + /** `sql_warehouse`, `warehouse`, `cluster` or `job`. */ + resourceType: string + resourceId: string + /** Cleaned for showing. */ + resourceName: string + /** As the workspace spells it, to recognise it in files, commands and connections. */ + matchName: string + /** The workspace it is in; null when the check read only one. */ + workspace: string | null + /** The workspace it is in, whether or not the check read several. */ + workspaceId: string | null + /** Both 0 when the finding has no dollar estimate. */ + monthlyMin: number + monthlyMax: number + evidence: string[] + /** The one fact a line under a tool call quotes. */ + fact: string + /** What the resource cost a day over the window, from billing; null when the answer does not say. */ + dailyCost: number | null + /** A warehouse's settings when it was measured, each as read or null; null for anything else. */ + config: WarehouseConfig | null + /** The request "Draft the fix" puts in the prompt box: the change, for Claude to draft and the person to review. */ + fixRequest: string +} + +/** What became of a drafted fix, as of one run. */ +export type SavingsFixLine = { + /** The fixed resource's type, as its finding gave it (`sql_warehouse`, `warehouse`, `cluster`, `job`). */ + resourceType: string + resourceId: string + /** The workspace the fixed resource is in; null when the answer does not say. */ + workspaceId: string | null + resourceName: string + /** `lower`: the change was seen and billed spend fell; amounts from different weeks, so not a measured saving. */ + state: 'measuring' | 'lower' | 'no_saving' | 'unchanged' | 'unmeasured' + text: string +} + /** One /savings run's answer, as the pane draws it. */ export type SavingsView = { + platform: SavingsPlatform /** The altimate-code connection that ran the check. */ connection: string | null + /** What the answer is about: the workspace host or Snowflake account, else the project it ran in. It is shown only there. */ + identity: string + /** The Snowflake account the answer is about (its connection's name when the account is not known); null on Databricks. */ + scope: string | null + /** How its dollars are priced: `list price`, or the account's own credit price. */ + pricing: string + /** The SQL warehouse its queries ran on. */ + ranOn: string | null /** The window the check read (YYYY-MM-DD, UTC) and its length in days; `days` is derived from the ends when the CLI did not send `lookback_days`, and is absent only on reports saved before it was kept. */ window: { start: string; end: string; days?: number } /** What was read; `workspaces` counts the Databricks workspaces the run read warehouses, clusters or jobs from. */ checked: { warehouses: number; clusters: number; jobs: number; workspaces: number } /** - * Checks that did not run in full, each as "Check name (the CLI's reason)": the connection could not read - * its system tables, the run hit its time limit (its query may still be running), or core refused its facts. + * What did not run in full, each with the CLI's reason in brackets: a check whose system tables the connection + * could not read, that hit the run's time limit (its query may still be running) or whose facts core refused; + * on Snowflake also warehouses the role cannot list. */ skipped: string[] /** What a query read only the first 10,000 of, e.g. `jobs`. */ limited: string[] - /** Dollars a month at list price, each resource counted once at its largest saving. */ + /** Dollars a month, each resource with a dollar estimate counted once at its largest saving. */ total: { min: number; max: number; resources: number } - findings: { - title: string - /** `sql_warehouse`, `cluster` or `job`. */ - resourceType: string - resourceId: string - resourceName: string - /** As the workspace spells it, to recognise it in files and commands. */ - matchName: string - /** The workspace it is in; null when the check read only one. */ - workspace: string | null - /** The workspace it is in, whether or not the check read several; null when the answer does not say. */ - workspaceId: string | null - monthlyMin: number - monthlyMax: number - evidence: string[] - /** The request "Draft the fix" puts in the prompt box: the change, for Claude to draft and the person to review. */ - fixRequest: string - }[] + findings: SavingsFinding[] /** What each flagged warehouse would cost at other sizes or as serverless. */ whatIf: { resourceId: string @@ -683,9 +741,21 @@ export type SavingsView = { }[] /** Warehouses whose size or type changed since a run first flagged them, with their observed spend a month before and * after: billed in different weeks, so not a saving measured with the workload held constant. */ - changes: { name: string; from: string; to: string; since: string; monthlyBefore: number; monthlyNow: number }[] + changes: { resourceId: string; workspaceId: string | null; name: string; from: string; to: string; since: string; monthlyBefore: number; monthlyNow: number }[] + /** Every warehouse the run read, with what it cost over the window. */ + /** `workspaceId` is null when the answer did not say; an answer kept before it was stored has none. */ + inventory: { id: string; workspaceId?: string | null; name: string; type: string; size: string | null; windowCost: number | null }[] + /** Queries the findings' evidence counted; null when none did. */ + queryCount: number | null + /** The warehouse type those queries ran on (`CLASSIC`), when they all ran on one. */ + queriesOn: string | null + /** The fixes drafted from earlier results, and what this run says became of them. */ + fixes: SavingsFixLine[] } +/** A run's answer as it is kept between sessions, for seven days. */ +export type SavingsKept = { savedAt: number; view: SavingsView } + declare module 'claude-code' { interface PluginState { 'altimate-code': { @@ -763,16 +833,25 @@ declare module 'claude-code' { health: HealthState | null /** hooks/features/: SqlGraphState. */ sqlGraph: Shaped - /** The last /savings answer; null before one, or after /clear. */ - savingsReport: Shaped + /** The kept /savings answers, by connection; each lasts seven days or until that connection is checked again. */ + savingsReports: Shaped> /** What /savings is doing now; null when it is idle. */ - savingsBusy: { label: string } | null - /** Why there is no answer to show: the check's refusal and the step that fixes it. */ - savingsMessage: { text: string; recovery: string } | null + savingsBusy: { label: string; detail: string } | null + /** Why a platform has no answer to show: the check's refusal and the step that fixes it. */ + // A refusal about no one platform (a connection name that is neither) carries none. + savingsMessages: { platform: SavingsPlatform | null; text: string; recovery: string }[] /** The line above the prompt when the session touches Databricks config; null when there is none. */ savingsBand: { text: string } | null /** The alternative pressed in the pane's what-if row; null when none is. */ - savingsWhatIf: { workspaceId: string | null; resourceId: string; label: string } | null + savingsWhatIf: { connection: string | null; workspaceId: string | null; resourceId: string; label: string } | null + /** altimate-code's connections, in its order; null until they are read. */ + savingsConnections: SavingsConnection[] | null + /** The compute each dbt run or build in the transcript runs on, by tool call. */ + savingsRows: Record + /** What the pane's last Share report or Altimate press did. */ + savingsShared: { text: string } | null + /** Whether the pane shows every finding and its detail (Show all) or only the largest few; each run starts slim. */ + savingsExpanded: boolean /** hooks/features/: DocsState. */ docs: DocsState | null /** hooks/features/: CteProfileState. */