diff --git a/CHANGELOG.md b/CHANGELOG.md index b930016bc8..b013c8e034 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,62 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.12.12] - 2026-11-20 + +**dbt Power User features now work from the command line, and an owner can send a workspace request back for changes.** Nine new tools estimate what a dbt model or query would scan before it runs (BigQuery dry run, Snowflake and Databricks from the planner's EXPLAIN), read the last dbt run, check a model's docs coverage, report DataPilot project health, time a model's CTEs, draw its SQL graph, map raw SQL tables to `ref()` and `source()`, read the defer setting, and reply to comments on shared dbt docs. Call them with `altimate-code tool run` or from another coding agent through `mcp serve`. The new `altimate-code integrations` command connects GitHub, Jira and Linear with your own credentials. On workspaces with review on, a request can be sent back with a comment, then changed and sent again. The TUI says what changed in the workspace's skills and knowledge since your last session. Also in this release: stricter SQL checks in the tool CLI and MCP server, the agent keeps your changes instead of reverting them, `altimate review` reviews only the PR's own changes, and Snowflake key-pair login reads every private-key format. + +**Heads-up for support:** +- **The dbt Power User tools are not offered to the agent in the TUI.** They are in `altimate-code tool run` and `mcp serve` only. `dbt_cost_estimate`, `dbt_health`, `dbt_cte_profile` (when timing a CTE) and `dbt_sql_graph` start the project's dbt adapter, which runs `dbt deps` and renders Jinja, so they need `--allow-write` and refuse in plan mode. `dbt_sql_graph` reads the parents' column metadata from the warehouse. `dbt_health` also needs the `altimate-datapilot-cli` package in the project's Python. +- **What `dbt_cost_estimate` runs.** It never runs the query itself. On Databricks, `EXPLAIN COST` can start a stopped SQL warehouse, which is billed while it runs. Snowflake's number is an upper bound, except when the plan reads an external table, a stage or a secure view, or reports 0, which the answer says. A query that may hold a second statement, or that reads files on Databricks (including through `IDENTIFIER()`), gets no estimate. An EXPLAIN that takes over 90 s answers "explain failed". `dbt_cte_profile` runs one `COUNT(*)` per CTE timed. +- **The tool CLI and MCP server refuse more SQL, even with `--allow-write`.** The new refusals are `DROP CATALOG`, `DROP NAMESPACE`, `DROP EXTERNAL SCHEMA`, `DROP PLUGGABLE DATABASE`, and MySQL and MariaDB executable comments (`/*! ... */`). Jinja in SQL sent to a dbt target counts as a write. `sql_explain` explains one statement only, without leading `EXPLAIN` or its options. +- **On Snowflake, MySQL and ClickHouse, a backslash inside a quoted string makes the SQL uncertain.** `sql_explain` refuses it and says so, and `sql_execute` treats it as a write. Regexes and Windows paths are the usual triggers. Tracked in #1782. +- **`altimate integrations` keeps secrets in the macOS keychain on macOS**, unless `ALTIMATE_INTEGRATIONS_DIR` is set. On Linux and Windows, and on macOS with that variable, they are kept in a file (in the data directory, or in `ALTIMATE_INTEGRATIONS_DIR`). Tracked in #1785. +- **The tools that start the dbt adapter no longer write to the project's `target/`.** In the `core` and `corecommand` modes dbt writes their artifacts to `/.altimate-code/`, so `target/manifest.json` stays as your own `dbt compile` left it. The first such call on a project parses it in full, so it is slower once. The `fusion` and `cloud` modes still write to `target/`. +- **`altimate review` in CI now fails when the PR's target branch isn't fetched**, instead of guessing `origin/main`. Use `fetch-depth: 0`. `--base` with no common history also fails. +- **New integration surfaces for plugins.** `skill publish --json` refusals carry a `code`. Requests can have the status `changes requested`. `serve` adds `POST /altimate/rules/{id}/withdraw|resubmit` `GET /altimate/workspace/activity` and `POST /altimate/workspace/activity/seen`. + +### Added + +- **`dbt_cost_estimate`** — the bytes a dbt model or query would scan, without running it: a BigQuery dry run, Snowflake `EXPLAIN USING JSON` and Databricks `EXPLAIN COST`. (#1732, #1768, #1776, #1779) +- **`dbt_run_results`** — the last dbt run's invocation id, command, timings, counts and per-node results, failures first. (#1729) +- **`dbt_docs_coverage`** — which output columns of a model have no description, and the percent documented. Column reach keeps how each reached column comes from the traced one. (#1733) +- **`dbt_health`** — DataPilot project health insights per model, such as hard-coded references and missing tests or docs. (#1738) +- **`dbt_cte_profile`** — a model's CTEs in source order, or the row count and warehouse time of one CTE, without dbt's start-up. (#1731, #1781) +- **`dbt_sql_graph`** — a model's CTEs, joins and filters as a graph, with joins, filters, groups and sorts named by their clause. (#1735, #1781) +- **`dbt_map_relations`** — the `ref()` or `source()` call for each table in raw SQL, matched against the manifest. (#1737) +- **`dbt_defer_state`** — the dbt Power User defer setting and the profile's targets. (#1734) +- **`docs_share_comments`** — list, reply to and resolve comment threads on shared dbt docs. (#1730) +- **`altimate-code integrations`** — connect GitHub, Jira and Linear with your own credentials: `status`, `detect`, `fields`, `set`, `set-secret`, `connect`, `sync`, `block` and `disconnect`. Secrets never go on the command line, and a credential stays local or is saved to the workspace. See "Integrations" in the CLI docs. (#1622) +- **Request changes on workspace review.** The owner or an admin can send a skill, knowledge or rule request back with a comment. You are told once, `workspace review status` and `/rules` show the comment, and the request can be sent again or withdrawn. Claude Code and Codex sessions are told too. (#1755) +- **"What changed" in a linked workspace.** A few seconds after the TUI starts, one line names the skills and knowledge added or removed since your last session. The VS Code extension gets the same line from `serve`. (#1752) +- **The Claude Code plugin's dbt helpers** are documented in "Using with Claude Code", including what `altimate-dbt` is. (#1728, #1779) +- **`tool report-event` takes the Claude Code plugin's session-start and feature-used events**: versions, the OS and a random install id, with no session, machine, project or account id, and skipped when telemetry is off. (#1775) + +### Changed + +- **Stricter SQL classification in the tool CLI and MCP server** (see Heads-up). (#1644) +- **`altimate review` reviews only the PR's own changes.** The base comes from `--base` or the CI target branch, the diff is taken from the merge-base, only files in the dbt project are reviewed, renamed models keep their old side, custom `model-paths` are honoured, and a Jinja model without compiled SQL is marked unverified instead of getting warnings. (#1719) +- **The agent keeps your changes.** When a test or build fails because of a change you made, it fixes the test or the callers, or asks, instead of reverting your change. It never weakens a test to make it pass. (#1766) + +### Fixed + +- **A link that hits a workspace you cannot see names the workspace id and the account you are signed in as.** Before, it said only "a workspace you can't see". (#1764) +- **Workspace review decisions are no longer hidden by "Sync now".** Decisions that arrive together show as one toast. (#1751) +- **The column answer reads a cast after a SELECT modifier or in parentheses**, and column names at the edges of the answer are right. (#1760, #1754) +- **`schema-verify` says when its verdict rests on a stale manifest.** (#1704) +- **Snowflake key-pair login reads every private-key format**: PEMs whose line breaks became spaces, encrypted PKCS#8 keys with their passphrase (and a clear error when `private_key_passphrase` is missing), and legacy encrypted PKCS#1 keys. (#1777) +- **`serve` never sends a stack trace in an error response.** A remote config that can't be fetched is a 502 that names the remote. (#1788) +- **A missing npm on Windows is reported as missing**, not as a failed driver install. (#1790) +- **dbt tool argument errors name the field**, and activating a different virtualenv (`VIRTUAL_ENV`, `CONDA_PREFIX`) gets a `tool run` daemon that uses it. (#1781) +- **Release review fixes.** + - The `ALTIMATE_INTEGRATIONS_*_API` overrides must be https or a local address, judged by the parsed host, with no credentials in the URL. + - The missing-fields hint gives full commands, with a secret source for `set-secret`, and its re-run keeps the failed call's `update`, `--local-only`, `--share` and `--variant`. + - The dbt adapter refusal names the fix that applies: `--allow-write`, or leaving plan mode. + - `dbt_run_results` accepts a UNC target path and skips a `run_results.json` over 256 MiB. + - The dbt Power User tools and `integrations` are documented. + - `altimate review` refuses a `--base` or `--head` that starts with `-`. + - Remote-config errors and the debug log name the remote by its URL template, never the URL with the token filled in. + ## [0.12.11] - 2026-11-16 **You can use a Claude Pro or Max plan through your own Claude Code login, and workspace review works from every client.** The new Claude subscription provider runs Claude models through the `claude` you already have installed; Altimate Code never reads or stores its token. The first-run picker and `/connect` suggest the subscription logins already on the machine. On workspaces with review on, a member's skill goes to the owner or an admin for approval, everyone sees their own requests and their status, and requests can be withdrawn or removed from the TUI, `serve` and the plugins. Team rules also reach Claude Code and Codex sessions through the plugins. `impact_analysis` answers where a column's value goes, or where it comes from, hop by hop. Also in this release: a capped agent ends with an answer, one overflow compacts once, and the dbt adapter starts under Bun. diff --git a/docs/docs/data-engineering/tools/dbt-tools.md b/docs/docs/data-engineering/tools/dbt-tools.md index c61b697b92..0b924da59e 100644 --- a/docs/docs/data-engineering/tools/dbt-tools.md +++ b/docs/docs/data-engineering/tools/dbt-tools.md @@ -1,6 +1,6 @@ --- title: "dbt Tools — Altimate Code" -description: "Run dbt commands from Altimate Code using the dbt_run tool with full output capture and error reporting." +description: "dbt tools in Altimate Code: dbt_run, dbt_manifest, dbt_unit_test_gen, and the dbt Power User tools for cost estimates, run results, docs coverage, project health, CTE timing, SQL graphs, relation mapping, defer state and shared-docs comments." --- # dbt Tools @@ -140,6 +140,43 @@ unit_tests: --- +## dbt Power User tools + +These tools bring dbt Power User features to the command line. Call them with `altimate-code tool run --args ''` (see [Tool CLI](../../usage/tool.md)) or from another coding agent through `altimate-code mcp serve`. The agent in the TUI does not offer them. + +Some of them start the project's dbt integration (the dbt adapter), which runs `dbt deps` and renders the project's Jinja. Jinja `run_query` calls can run billed queries. A read-only call (`altimate-code tool run` without `--allow-write`, or plan mode) does not start the adapter, so these tools refuse it and say which of the two to change. + +### Tools that start the dbt adapter and so need `--allow-write` + +| Tool | What it returns | Parameters | What it runs on the warehouse | +| --- | --- | --- | --- | +| `dbt_cost_estimate` | The bytes a model or a query would scan, without running it. | `model` or `sql` (may use Jinja), not both | BigQuery: a dry run. Snowflake: `EXPLAIN USING JSON`, bytes left after pruning: an upper bound when the plan can size every source it reads. When it can't (an external table, a stage, a secure view, or a scan sized at zero), the answer says the figure is not a cap. Databricks: `EXPLAIN COST`, the sizes of the tables it reads, which can start a stopped SQL warehouse (billed while it runs). A query that may hold a second statement, or that reads files on Databricks, is refused rather than planned. | +| `dbt_health` | DataPilot project health insights per model, such as hard-coded references, missing tests or documentation, and naming and structure issues. | `config_path` (optional DataPilot config) | Nothing. It needs the `altimate-datapilot-cli` Python package in the project's Python. | +| `dbt_cte_profile` | Without `cte` or `position`: the model's CTEs in source order. With one: that CTE's row count and its warehouse time in milliseconds (`queryMs`, without dbt's start-up; `timing` says how it was measured, and `wall` means neither measure was available, so the time includes dbt's start-up). | `model` (name, unique_id or `.sql` path), `cte`, `position` | Listing runs nothing and works read-only. Timing runs `SELECT COUNT(*)` over that CTE and the CTEs before it, so a model of N CTEs costs N queries. | +| `dbt_sql_graph` | A model's CTEs, joins and filters as a graph, each relation tied to the dbt node it stands for. | `model` | Reads the column metadata of the model's parent relations. Runs no query on their data. | + +### Read-only tools + +| Tool | What it returns | Parameters | +| --- | --- | --- | +| `dbt_run_results` | The last dbt run from `target/run_results.json`: invocation id, command, elapsed seconds, finish time, counts, and one row per node with failures first (at most 200). A compile or parse writes success rows without building anything. | `project_dir`, `target_path` | +| `dbt_docs_coverage` | For one model: the output columns without a description in the project's YAML, the percent documented, and whether the model has a description. Needs a compiled manifest (`dbt compile`). | `model`, `manifest_path` | +| `dbt_map_relations` | For each table in a raw SQL query, the `ref()` or `source()` call that replaces it, how it matched (`exact`, `case_insensitive`, `partial`, `none`) and the candidates. | `sql`, `dialect`, `manifest_path`, `project_dir` | +| `dbt_defer_state` | The dbt Power User defer setting (`dbt.deferConfigPerProject`) and the profile's default target and target names. It reads only the workspace's `.vscode/settings.json`, not user settings or a `.code-workspace` file. | `project_dir`, `workspace_dir` | + +### Shared-docs comments + +`docs_share_comments` works on comment threads on dbt docs shared through Altimate. It needs you to be signed in. + +- `action: "list"` returns the open threads for a dbt project: the shares you own and the threads you are tagged in. It can lag up to five minutes behind a new post. +- `action: "reply"` (with `share_id`, `group_id` and `text`) and `action: "resolve"` (with `share_id` and `group_id`) post under your name. They need write permission. + +```bash +altimate-code tool run dbt_run_results +altimate-code tool run dbt_cost_estimate --allow-write --args '{"model":"fct_revenue"}' +altimate-code tool run docs_share_comments --args '{"action":"list"}' +``` + ## altimate-dbt CLI `altimate-dbt` is a standalone CLI for dbt workflows. It auto-detects your dbt project directory, Python environment, and adapter type (Snowflake, BigQuery, Databricks, Redshift, etc.). diff --git a/docs/docs/usage/cli.md b/docs/docs/usage/cli.md index d7488aee90..422f0c02d3 100644 --- a/docs/docs/usage/cli.md +++ b/docs/docs/usage/cli.md @@ -29,6 +29,7 @@ altimate --agent analyst | `run` | Run a prompt non-interactively | | `check` | Run deterministic SQL checks (no LLM required) -- see [SQL Check](check.md) | | `tool` | Run the data tools without a model, optionally via a warm daemon -- see [Tool CLI](tool.md) | +| `integrations` | Connect GitHub, Jira and Linear with your own credentials -- see [Integrations](#integrations) | | `serve` | Start the HTTP API server | | `web` | Start the web UI | | `agent` | Agent management | @@ -75,6 +76,24 @@ With workspaces on: - When `altimate-code serve` is launched by the VS Code / Cursor extension, the workspace selected in the extension's panel governs that session's skills, memory and (unless `--integrations local` is set) warehouse tool routing, taking priority over whatever the project is linked to on the backend, and is scoped to the folder it was launched for. A pin is fixed for the life of the `serve` process, so the extension relaunches `serve` when the selection changes; nothing updates a running one. - `serve` also gives the IDE extension what the TUI shows: `GET /altimate/workspace/starter` (the starter message after a link) and `GET /altimate/trace` with `GET /altimate/trace//view` (the trace list and viewer behind `/traces`). Traces hold prompts and tool output, including SQL and query results. Like every `serve` route, these need no password unless `OPENCODE_SERVER_PASSWORD` is set, so set one on a shared machine. +### Integrations + +`altimate-code integrations` connects GitHub, Jira (Cloud or Server / Data Center) and Linear with your own credentials. A credential can stay on this machine or be saved to the linked workspace. Every subcommand accepts `--json`. + +```bash +altimate-code integrations status # each provider's state +altimate-code integrations detect # find credentials already on this machine (secrets are never printed) +altimate-code integrations fields jira # the fields a provider needs, pre-filled where possible +altimate-code integrations set jira jiraDomain mycompany +altimate-code integrations set-secret jira jiraApiToken --from-clipboard +altimate-code integrations connect jira # check the credential with the provider, then save it +``` + +- `set-secret` reads a secret only from `--from-clipboard`, `--from-env ` or `--stdin`, never from the command line. `open-token-page ` opens the page where the provider's token is created. +- `connect` checks the credential with the provider before saving it. With `--local-only` it stays on this machine. Otherwise it is saved to the linked workspace. Attaching it to a workspace that is not private, so its members can use it, needs `--share`. +- `update ` saves a new credential and keeps the sync mode. `sync [provider] | --all` pushes credentials to the workspace. `block` and `unblock` keep a provider on this machine only or allow it to sync again. `block` refuses a provider whose connection is saved only in the workspace; when the workspace can't be checked it blocks anyway, and a copy already saved there stays until you `disconnect` it. `discard` forgets fields typed in but not connected. `disconnect` removes the local credential and the workspace connection. +- On macOS, secrets are kept in the keychain, unless `ALTIMATE_INTEGRATIONS_DIR` is set, which keeps them in a file in that folder. On Linux and Windows they are kept in a file in your altimate-code data directory (or `ALTIMATE_INTEGRATIONS_DIR`), readable only by you on Linux (mode 0600). Windows does not apply that mode. + ## Global Flags | Flag | Description | diff --git a/packages/opencode/src/altimate/integrations/credentials.ts b/packages/opencode/src/altimate/integrations/credentials.ts index 60971838dc..de26bfc1b3 100644 --- a/packages/opencode/src/altimate/integrations/credentials.ts +++ b/packages/opencode/src/altimate/integrations/credentials.ts @@ -604,9 +604,27 @@ export interface Validation { message: string | null } -const githubApi = () => (process.env.ALTIMATE_INTEGRATIONS_GITHUB_API || "https://api.github.com").replace(/\/+$/, "") -const linearApi = () => process.env.ALTIMATE_INTEGRATIONS_LINEAR_API || "https://api.linear.app/graphql" -const jiraCloudBase = (site: string) => (process.env.ALTIMATE_INTEGRATIONS_JIRA_API || `https://${site}.atlassian.net`).replace(/\/+$/, "") +// An override receives the real token, so it must be https or a local http address, as a Jira server URL must; any other value is ignored. +// The parsed host decides, so `http://localhost@remote.example` (userinfo before a remote host) is not local, and an override +// carrying credentials of its own is refused. +const LOCAL_HOSTS = new Set(["127.0.0.1", "localhost", "[::1]"]) +const apiOverride = (name: string) => { + const v = process.env[name]?.trim() + if (!v) return undefined + let u: URL + try { + u = new URL(v) + } catch { + return undefined + } + if (u.username || u.password) return undefined + return u.protocol === "https:" || (u.protocol === "http:" && LOCAL_HOSTS.has(u.hostname)) ? v : undefined +} +/** For tests. */ +export const credentialsInternals = { apiOverride } +const githubApi = () => (apiOverride("ALTIMATE_INTEGRATIONS_GITHUB_API") || "https://api.github.com").replace(/\/+$/, "") +const linearApi = () => apiOverride("ALTIMATE_INTEGRATIONS_LINEAR_API") || "https://api.linear.app/graphql" +const jiraCloudBase = (site: string) => (apiOverride("ALTIMATE_INTEGRATIONS_JIRA_API") || `https://${site}.atlassian.net`).replace(/\/+$/, "") /** GitHub sends the expiry as `2026-11-01 00:00:00 UTC`. */ export function parseGithubExpiry(header: string | null): string | null { diff --git a/packages/opencode/src/altimate/review/git.ts b/packages/opencode/src/altimate/review/git.ts index 6a5f094a96..8f61634cec 100644 --- a/packages/opencode/src/altimate/review/git.ts +++ b/packages/opencode/src/altimate/review/git.ts @@ -230,6 +230,9 @@ async function ciTargetBranch(env: NodeJS.ProcessEnv): Promise<{ branch: string; * is what made PRs into a non-default branch review hundreds of unrelated files. */ export async function resolveReviewBase(opts: ResolveBaseOptions): Promise { + // `merge-base` takes these as bare argv entries, where a leading `-` would be read as a git option. + for (const [flag, ref] of [["--base", opts.base], ["--head", opts.head]] as const) + if (ref?.startsWith("-")) throw new Error(`${flag} ${ref}: a git ref cannot start with "-".`) const head = opts.head ?? "HEAD" const env = opts.env ?? process.env diff --git a/packages/opencode/src/altimate/tools/dbt-adapter-access.ts b/packages/opencode/src/altimate/tools/dbt-adapter-access.ts index 6beef71403..d1bdb6d1b9 100644 --- a/packages/opencode/src/altimate/tools/dbt-adapter-access.ts +++ b/packages/opencode/src/altimate/tools/dbt-adapter-access.ts @@ -31,7 +31,10 @@ export async function dbtAdapterFor(ctx: Pick start && sql[j] === "\\"; j--) run++ - if (run % 2 === 1) complete = false + if (run % 2 === 1) { + complete = false + backslash = true + } } if ((escaped || backslashEscapes) && sql[i] === "\\") { + sawEscape = true i += 2 continue } @@ -161,7 +171,11 @@ export function tokenizeSql(sql: string, dialect?: string): { tokens: SqlToken[] closed = true break } - if (!closed) complete = false + if (!closed) { + complete = false + // A string left open after a backslash escape most likely ends in an escaped quote. + if (sawEscape) backslash = true + } i = Math.min(i, sql.length) } else if (dollarQuotes && sql[i] === "$" && !(clickhouse ? /[\w$]/ : IDENTIFIER_CHAR).test(sql[i - 1] ?? "")) { DOLLAR_TAG.lastIndex = i @@ -199,7 +213,7 @@ export function tokenizeSql(sql: string, dialect?: string): { tokens: SqlToken[] code = i } if (code < sql.length) tokens.push({ kind: "code", text: sql.slice(code) }) - return { tokens, complete } + return { tokens, complete, backslash } } export function maskSql(tokens: SqlToken[], identifiers = false): string { diff --git a/packages/opencode/src/altimate/validators/validator-utils.ts b/packages/opencode/src/altimate/validators/validator-utils.ts index 1e87ef7a4b..caa99988f0 100644 --- a/packages/opencode/src/altimate/validators/validator-utils.ts +++ b/packages/opencode/src/altimate/validators/validator-utils.ts @@ -511,9 +511,9 @@ function resolveJinjaPathValue(value: string): string | null { return m[2] !== undefined && m[2].length > 0 ? m[2] : null } -/** Absolute-path test that also accepts Windows drive-letter roots. */ +/** Absolute-path test that also accepts Windows drive-letter roots and UNC paths (\\server\share). */ function isAbsolutePath(p: string): boolean { - return p.startsWith("/") || /^[A-Za-z]:[\\/]/.test(p) + return p.startsWith("/") || /^[A-Za-z]:[\\/]/.test(p) || /^\\\\[^\\]/.test(p) } // --------------------------------------------------------------------------- @@ -1355,16 +1355,19 @@ export function isFailedRunStatus(status: string): boolean { return !OK_RUN_STATUSES.has(status.toLowerCase()) } +/** A run_results.json larger than this is not read into memory; it is far above what a large project writes. */ +const MAX_RUN_RESULTS_BYTES = 256 * 1024 * 1024 + /** * Read and parse `/run_results.json`. Returns null when the artifact - * is absent or unparseable — callers decide what that means for their gate. + * is absent, unparseable or over {@link MAX_RUN_RESULTS_BYTES} — callers decide what that means for their gate. */ export async function readRunResults(dbtRoot: string, targetPathOverride?: string): Promise { const targetPath = await resolveDbtTargetPath(dbtRoot, targetPathOverride) const path = join(targetPath, "run_results.json") try { const stat = await fs.stat(path, { bigint: true }) - if (!stat.isFile()) return null + if (!stat.isFile() || stat.size > MAX_RUN_RESULTS_BYTES) return null const raw = await fs.readFile(path, "utf8") // The time keeps the plain stat's own rounding: every other caller compares it with mtimes read the same way, and a different rounding of equal timestamps would order them apart. It is taken between the two bigint stats, so the comparison below proves it describes the same file version as the rows. const plain = await fs.stat(path) diff --git a/packages/opencode/src/cli/cmd/integrations.ts b/packages/opencode/src/cli/cmd/integrations.ts index 085a1373ae..1afa85219f 100644 --- a/packages/opencode/src/cli/cmd/integrations.ts +++ b/packages/opencode/src/cli/cmd/integrations.ts @@ -237,7 +237,17 @@ async function runCredentials(args: any, update: boolean) { if (r.status === "connected") { out(`${S.TEXT_SUCCESS}✓${S.TEXT_NORMAL} ${name} ${update ? "updated" : "connected"}${r.account ? ` as ${S.TEXT_NORMAL_BOLD}${clean(r.account)}${S.TEXT_NORMAL}` : ""}`) out(` ${S.TEXT_DIM}${r.sync === "synced" ? `synced to your workspace from ${clean(os.hostname())}` : "kept local, not synced"}${r.expiresAt ? ` · expires ${clean(r.expiresAt)}` : ""}${r.message ? ` · ${clean(r.message)}` : ""}${S.TEXT_NORMAL}`) - } else out(`${S.TEXT_DANGER}✗${S.TEXT_NORMAL} ${name}: ${clean(r.message ?? r.status)}`) + } else { + out(`${S.TEXT_DANGER}✗${S.TEXT_NORMAL} ${name}: ${clean(r.message ?? r.status)}`) + if (r.status === "missing_fields") { + // The re-run keeps the flags of the call that failed: without --local-only it would sync the credential. + // A variant named by its label ("Jira Server / Data Center") is quoted so the copied command parses. + const shellWord = (v: string) => (/^[\w.:/-]+$/.test(v) ? v : `'${v.replace(/'/g, "'\\''")}'`) + const variant = typeof args.variant === "string" && args.variant ? ` --variant ${shellWord(clean(args.variant))}` : "" + const rerun = `${update ? "update" : "connect"} ${id}${variant}${args.share ? " --share" : ""}${!update && args["local-only"] ? " --local-only" : ""}` + out(` ${S.TEXT_DIM}See the fields with \`altimate integrations fields ${id}${variant}\`, fill them with \`altimate integrations set ${id} \` or \`altimate integrations set-secret ${id} --stdin\` (or \`--from-env VAR\`, \`--from-clipboard\`), then run \`altimate integrations ${rerun}\` again.${S.TEXT_NORMAL}`) + } + } } catch (e) { fail(e, args.json) } diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index 345a4c2e87..2ffa84be3a 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -373,7 +373,9 @@ export const layer = Layer.effect( // altimate_change end } return yield* Schema.decodeEffect(Schema.fromJsonString(schema))(body).pipe( - Effect.catch((error) => Effect.die(new Error(`failed to decode remote config from ${url}: ${String(error)}`))), + // altimate_change start — see `shown` above + Effect.catch((error) => Effect.die(new Error(`failed to decode remote config from ${shown}: ${String(error)}`))), + // altimate_change end ) }) @@ -575,17 +577,19 @@ export const layer = Layer.effect( ) const fetchedConfig = remote ? yield* Effect.gen(function* () { - yield* Effect.logDebug("fetching remote config", { url: remote.url }) - // altimate_change start — errors name the remote by its template (`{env:…}` and all), not the - // substituted URL, which can carry the auth token + // altimate_change start — errors and logs name the remote by its template (`{env:…}` and all), not + // the substituted URL, which can carry the auth token const template = isRecord(wellknown.remote_config) ? wellknown.remote_config.url : undefined const shown = typeof template === "string" ? template : url + yield* Effect.logDebug("fetching remote config", { url: shown }) const data = yield* fetchRemoteJson(remote.url, remote.headers, Schema.Json, url, shown) // altimate_change end if (isRecord(data) && isRecord(data.config)) return data.config if (isRecord(data)) return data return yield* Effect.die( - new Error(`failed to decode remote config from ${remote.url}: expected object`), + // altimate_change start — see `shown` above + new Error(`failed to decode remote config from ${shown}: expected object`), + // altimate_change end ) }) : {} diff --git a/packages/opencode/test/altimate/dbt-adapter-access.test.ts b/packages/opencode/test/altimate/dbt-adapter-access.test.ts index 74ff3438ad..6996eaa0b2 100644 --- a/packages/opencode/test/altimate/dbt-adapter-access.test.ts +++ b/packages/opencode/test/altimate/dbt-adapter-access.test.ts @@ -193,12 +193,22 @@ describe("dbtAdapterFor", () => { }) test("a refusal for an adapter that didn't load names the Python dbt ran with and how to fix it", async () => { - dbtAdapterInternals.create = async () => ({ isInitialized: () => false, dispose: async () => {} }) - const access = await dbtAdapterFor(ctx) - // The Python the config chose: dbt missing from it is the usual cause. - expect(access.reason).toContain("(python3)") - expect(access.reason).toContain("Activate the project's virtualenv") - expect(access.reason).toContain("altimate-code tool daemon stop") + // A HOME without ~/.altimate-code/dbt.json, so a developer's saved pythonPath can't change the hint. + const home = await mkdtemp(path.join(os.tmpdir(), "dbt-adapter-access-home-")) + const saved = process.env.HOME + try { + process.env.HOME = home + dbtAdapterInternals.create = async () => ({ isInitialized: () => false, dispose: async () => {} }) + const access = await dbtAdapterFor(ctx) + // The Python the config chose: dbt missing from it is the usual cause. + expect(access.reason).toContain("(python3)") + expect(access.reason).toContain("Activate the project's virtualenv") + expect(access.reason).toContain("altimate-code tool daemon stop") + } finally { + if (saved === undefined) delete process.env.HOME + else process.env.HOME = saved + await rm(home, { recursive: true, force: true }) + } }) test("with a saved dbt config, the refusal says to change its pythonPath, which wins over any virtualenv", async () => { diff --git a/packages/opencode/test/altimate/dbt-health.test.ts b/packages/opencode/test/altimate/dbt-health.test.ts index 8277e4dc2b..62e8f6dff7 100644 --- a/packages/opencode/test/altimate/dbt-health.test.ts +++ b/packages/opencode/test/altimate/dbt-health.test.ts @@ -732,7 +732,9 @@ describe("dbt_health", () => { test("plan mode is refused as a read-only call", async () => { const plan = await run({}, { agent: "plan" }) expect(plan.metadata).toMatchObject({ success: false, refusal: "read_only" }) - expect(plan.output).toContain("--allow-write") + // --allow-write does nothing in plan mode, so the refusal names leaving plan mode instead. + expect(plan.output).toContain("outside plan mode") + expect(plan.output).not.toContain("--allow-write") }) test("an answer whose model_insights is an array, or holds a non-list, is a failure, not an empty report", async () => { diff --git a/packages/opencode/test/altimate/tool-cli/runner.test.ts b/packages/opencode/test/altimate/tool-cli/runner.test.ts index 33e234592d..67cbae0f0e 100644 --- a/packages/opencode/test/altimate/tool-cli/runner.test.ts +++ b/packages/opencode/test/altimate/tool-cli/runner.test.ts @@ -65,6 +65,15 @@ describe("tool list", () => { "finops_query_history", "project_scan", "answer_commit", + "dbt_cost_estimate", + "dbt_cte_profile", + "dbt_defer_state", + "dbt_docs_coverage", + "dbt_health", + "dbt_map_relations", + "dbt_run_results", + "dbt_sql_graph", + "docs_share_comments", ]) expect(ids).toContain(id) for (const tool of tools) { @@ -409,7 +418,9 @@ describe("sql_explain", () => { Registry.setConfigs({ pg: { type: "postgres" } as any }) try { const result = await runner.run("sql_explain", { sql: "SELECT 'a\\'", warehouse: "pg" }) - expect(JSON.stringify(result)).toContain("could not be read with certainty") + const text = JSON.stringify(result) + expect(text).toContain("backslash in a quoted string") + expect(text).toContain("is not explained") } finally { Registry.reset() } diff --git a/packages/opencode/test/skill/release-v0.12.12-adversarial.test.ts b/packages/opencode/test/skill/release-v0.12.12-adversarial.test.ts new file mode 100644 index 0000000000..8374d6566d --- /dev/null +++ b/packages/opencode/test/skill/release-v0.12.12-adversarial.test.ts @@ -0,0 +1,419 @@ +/** + * Adversarial coverage for the v0.12.12 payload (v0.12.11..HEAD), on top of the suites each PR shipped + * with. The largest changes are the dbt Power User tools (#1729-#1738, #1761, #1768), the SQL + * classification hardening for the tool CLI and MCP server (#1644) and the `altimate integrations` + * command (#1622); each carries its own suite. + * + * This file adds the boundary classes those suites do not reach, and covers the release review fixes: + * + * - `dbt_cost_estimate`'s script check against statement smuggling on Snowflake and Databricks, its Jinja + * literal against breaking out of the string, and its plan parsers against hostile JSON. + * - The classifier's hard-deny list for the DROP forms #1644 added, and that Jinja keeps a read from + * being read as one. + * - `readRunResults` against non-files, non-JSON, prototype keys, an oversized file (the review's size + * cap) and a UNC target path (the review's `isAbsolutePath` fix). + * - `sql_explain`'s refusal naming a backslash on Snowflake rather than an unterminated quote. + * - The dbt adapter refusal naming plan mode, and source guards for the integrations API overrides. + */ +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test" +import fs from "fs/promises" +import { promises as fsp } from "fs" +import os from "os" +import path from "path" +import { Effect } from "effect" +import type { Tool } from "@/tool/tool" +import { SessionID, MessageID } from "@/session/schema" +import { + explainJinja, + formatBytes, + mayBeScript, + parseDatabricksExplainCost, + parseSnowflakeExplain, + readsFiles, +} from "@/altimate/tools/dbt-cost-estimate" +import { classifyAndCheck, mentionsHardDenyAnywhere } from "@/altimate/tools/sql-classify" +import { readRunResults, resolveDbtTargetPath } from "@/altimate/validators/validator-utils" +import { dbtAdapterFor } from "@/altimate/tools/dbt-adapter-access" +import { SqlExplainTool } from "@/altimate/tools/sql-explain" +import * as Registry from "@/altimate/native/connections/registry" +import { initTool } from "../altimate/tool-fixture" +import { resolveReviewBase } from "@/altimate/review/git" +import { credentialsInternals } from "@/altimate/integrations/credentials" +import { tokenizeSql } from "@/altimate/tools/sql-tokenize" +import { DbtBuildGreenValidator } from "@/altimate/validators/dbt-build-green" + +const src = path.join(import.meta.dir, "../../src") +const read = (file: string) => fs.readFile(path.join(src, file), "utf8") + +const ctx = (extra: Partial = {}): Tool.Context => ({ + sessionID: SessionID.make("ses_release_v01212"), + messageID: MessageID.make("msg_release_v01212"), + agent: "analyst", + abort: new AbortController().signal, + messages: [], + metadata: () => Effect.void, + ask: () => Effect.void, + ...extra, +}) + +describe("v0.12.12: dbt_cost_estimate never sends a second statement", () => { + const smuggled = [ + "select 1; drop table t", + "select 1;\ndrop table t", + "select 1 /* ; */; delete from t", + "select $$; drop table t$$", + "select 1 // ;\n; drop table t", + "!set variable_substitution=true\nselect 1", + "select 1 /* unclosed", + "select 'unclosed", + "execute immediate 'drop table t'", + "select 1;select 2", + ] + for (const sql of smuggled) + test(`Snowflake counts as a script: ${JSON.stringify(sql)}`, () => { + expect(mayBeScript(sql, "snowflake")).toBe(true) + }) + + for (const sql of ["select 1; drop table t", "select 1 /* unclosed", "select `a;b`; drop table t"]) + test(`Databricks counts as a script: ${JSON.stringify(sql)}`, () => { + expect(mayBeScript(sql, "databricks")).toBe(true) + }) + + test("a single statement with quoted semicolons and a trailing one is not a script", () => { + expect(mayBeScript("select ';' as a, \"b;c\" from t -- ; trailing\n;", "snowflake")).toBe(false) + expect(mayBeScript("select `a;b` from t;", "databricks")).toBe(false) + }) + + test("the empty string and whitespace are not scripts", () => { + expect(mayBeScript("", "snowflake")).toBe(false) + expect(mayBeScript(" \n\t ", "databricks")).toBe(false) + }) + + test("the Jinja literal cannot be closed by the SQL it carries", () => { + for (const sql of ["select '}}' as a", "select 'x' ~ '{{ 7*7 }}'", "select '\\' as b", "select 'it''s'", "{% do run_query('drop table t') %}"]) { + const jinja = explainJinja("EXPLAIN USING JSON", sql) + const literal = jinja.match(/run_query\('((?:\\.|[^'\\])*)'\)/) + expect(literal).not.toBeNull() + // Unescaping the literal gives back exactly the statement: nothing leaked outside the quotes. + expect(literal![1].replace(/\\(.)/g, "$1")).toBe(`EXPLAIN USING JSON\n${sql}`) + } + }) + + test("Databricks queries that read files are refused", () => { + for (const sql of ["select * from read_files('s3://b/x')", "SELECT * FROM cloud_files('/p', 'json')", "select * from json.`/tmp/a.json`"]) + expect(readsFiles(sql)).toBe(true) + expect(readsFiles("select read_files_count from t")).toBe(false) + }) +}) + +describe("v0.12.12: plan parsers against hostile JSON", () => { + const junk: unknown[] = [null, undefined, 0, -1, NaN, "", "{}", [], [null], {}, { __proto__: { bytesAssigned: 5 } }, JSON.parse('{"__proto__":{"GlobalStats":{"bytesAssigned":5}}}')] + test("Snowflake: junk gives no estimate and does not throw", () => { + for (const value of junk) expect(parseSnowflakeExplain(value)).toBeUndefined() + }) + test("Snowflake: negative or non-numeric bytes give no estimate", () => { + for (const bytesAssigned of [-1, "12", NaN, Infinity]) + expect(parseSnowflakeExplain(JSON.stringify({ GlobalStats: { bytesAssigned, partitionsAssigned: 1, partitionsTotal: 1 } }))).toBeUndefined() + // The same plan with a real count is read, so the cases above fail on the bytes, not the shape. + expect(parseSnowflakeExplain(JSON.stringify({ GlobalStats: { bytesAssigned: 5, partitionsAssigned: 1, partitionsTotal: 1 } }))).toBeDefined() + }) + test("Databricks: junk gives no estimate and does not throw", () => { + for (const value of junk) expect(() => parseDatabricksExplainCost(value)).not.toThrow() + for (const value of [null, undefined, 0, "", [], {}]) { + const r = parseDatabricksExplainCost(value) + expect(r === undefined || (typeof r === "object" && "noStats" in r)).toBe(true) + } + }) + test("formatBytes at the boundaries", () => { + expect(formatBytes(0)).toBe("0.0 Bytes") + expect(formatBytes(1023)).toBe("1023.0 Bytes") + expect(formatBytes(1024)).not.toContain("Bytes") + // The largest unit holds any size: no "undefined" unit. + expect(formatBytes(Number.MAX_SAFE_INTEGER)).not.toContain("undefined") + expect(formatBytes(1024 ** 8)).not.toContain("undefined") + }) +}) + +describe("v0.12.12: SQL classification hardening (#1644)", () => { + test("the new DROP forms are hard-denied wherever they appear", () => { + for (const sql of ["DROP CATALOG c", "drop namespace n", "DROP EXTERNAL SCHEMA s", "DROP PLUGGABLE DATABASE p", "select 1; DROP CATALOG c"]) { + expect(classifyAndCheck(sql, "snowflake").blocked).toBe(true) + expect(mentionsHardDenyAnywhere(sql)).toBe(true) + } + }) + test("a function or column named after a keyword stays a read", () => { + for (const sql of ["select truncate(x, 2) from t", "select a as truncate from t", "select 'DROP SCHEMA s' as note"]) { + const r = classifyAndCheck(sql, "snowflake") + expect([r.queryType, r.blocked]).toEqual(["read", false]) + } + }) + test("non-ASCII identifiers and strings are reads", () => { + for (const sql of ['select "Straße", name from kunden where stadt = \'München\'', "select 日本 from t"]) + expect(classifyAndCheck(sql, "snowflake").queryType).toBe("read") + }) +}) + +describe("v0.12.12: readRunResults against hostile files", () => { + let root: string + // An inherited DBT_TARGET_PATH would point readRunResults at another folder. + const savedTarget = process.env.DBT_TARGET_PATH + beforeEach(async () => { + delete process.env.DBT_TARGET_PATH + root = await fs.mkdtemp(path.join(os.tmpdir(), "release-v0.12.12-")) + await fs.mkdir(path.join(root, "target")) + }) + afterEach(async () => { + if (savedTarget === undefined) delete process.env.DBT_TARGET_PATH + else process.env.DBT_TARGET_PATH = savedTarget + await fs.rm(root, { recursive: true, force: true }) + }) + const write = (text: string) => fs.writeFile(path.join(root, "target", "run_results.json"), text) + + test("no file, a directory, non-JSON and an object without results are no evidence", async () => { + expect(await readRunResults(root)).toBeNull() + await fs.mkdir(path.join(root, "target", "run_results.json")) + expect(await readRunResults(root)).toBeNull() + await fs.rm(path.join(root, "target", "run_results.json"), { recursive: true }) + for (const text of ["", "not json", "[]", "null", '{"results":{}}', '{"__proto__":{"results":[]}}']) { + await write(text) + expect(await readRunResults(root)).toBeNull() + } + expect(Object.prototype).not.toHaveProperty("results") + }) + + test("a file over the size cap is not read", async () => { + const file = path.join(root, "target", "run_results.json") + await write('{"results":[]}') + // A sparse file on POSIX: the size is over the cap without writing the bytes. + await fs.truncate(file, 257 * 1024 * 1024) + // The cap, not a parse failure, must reject it: the file is never read. + const read = spyOn(fsp, "readFile") + try { + expect(await readRunResults(root)).toBeNull() + expect(read.mock.calls.some(([p]) => String(p) === file)).toBe(false) + } finally { + read.mockRestore() + } + }) + + test("a file of exactly the size cap is still read", async () => { + const file = path.join(root, "target", "run_results.json") + await write("{}") + await fs.truncate(file, 256 * 1024 * 1024) + // The bytes are not materialized: the read answers a small artifact for this file. + const read = spyOn(fsp, "readFile").mockResolvedValue('{"results":[]}' as any) + try { + expect(await readRunResults(root)).not.toBeNull() + expect(read.mock.calls.some(([p]) => String(p) === file)).toBe(true) + } finally { + read.mockRestore() + } + }) + + test("an artifact over the cap is no build evidence for the build-green gate", async () => { + await fs.writeFile(path.join(root, "dbt_project.yml"), "name: t\nversion: '1.0'\nconfig-version: 2\nprofile: t\n") + await fs.mkdir(path.join(root, "models")) + await fs.writeFile(path.join(root, "models", "stg_orders.sql"), "select 1 as id") + const file = path.join(root, "target", "run_results.json") + await write(JSON.stringify({ results: [{ unique_id: "model.t.stg_orders", status: "success" }] })) + await fs.truncate(file, 257 * 1024 * 1024) + const r = await DbtBuildGreenValidator.check({ sessionID: "s", workingDirectory: root, sessionStartMs: 0, step: 1, retryCount: 0 }) + expect(r.ok).toBe(false) + expect(r.details!["verdict"]).toBe("no-fresh-build") + }) + + test("a well-formed file is read", async () => { + await write(JSON.stringify({ results: [], args: { which: "build" }, elapsed_time: 1 })) + expect(await readRunResults(root)).not.toBeNull() + }) + + test("a UNC or drive-letter target path is used as given, not joined onto the project", async () => { + for (const target of ["\\\\server\\share\\target", "C:\\dbt\\target", "/abs/target"]) + expect(await resolveDbtTargetPath(root, target)).toBe(target) + expect(await resolveDbtTargetPath(root, "custom")).toBe(path.join(root, "custom")) + }) +}) + +describe("v0.12.12: refusal messages name the real cause", () => { + afterEach(() => Registry.reset()) + + test("sql_explain on Snowflake names the backslash, not an unterminated quote", async () => { + Registry.setConfigs({ sf: { type: "snowflake" } as any }) + const tool = await initTool(SqlExplainTool) + for (const sql of ["select regexp_replace(a, '\\\\d+', '') from t", "select * from f where p like 'C:\\\\Users\\\\%'"]) { + const result = await tool.execute({ sql, warehouse: "sf", analyze: false }, ctx()) + expect(result.metadata.success).toBe(false) + expect(result.output).toContain("backslash") + expect(result.output).not.toContain("unterminated") + } + }) + + test("sql_explain still names an unterminated quote when there is no backslash", async () => { + Registry.setConfigs({ sf: { type: "snowflake" } as any }) + const tool = await initTool(SqlExplainTool) + const result = await tool.execute({ sql: "select 'abc", warehouse: "sf", analyze: false }, ctx()) + expect(result.output).toContain("unterminated") + }) + + test("the backslash hint appears only when a backslash is why the quotes could not be read", async () => { + Registry.setConfigs({ pg: { type: "postgres" } as any, lite: { type: "sqlite" } as any, my: { type: "mysql" } as any }) + const tool = await initTool(SqlExplainTool) + const explain = (sql: string, warehouse: string) => tool.execute({ sql, warehouse, analyze: false }, ctx()) + // An unterminated quote in SQL that also holds a backslash elsewhere: the backslash is not the cause. + for (const [sql, warehouse] of [ + ["select regexp_replace(a, '\\d', '') || 'abc from t", "pg"], + ["select 'C:\\dir' || 'abc from t", "lite"], + ]) { + const out = (await explain(sql, warehouse)).output + expect(out).toContain("unterminated") + expect(out).not.toContain("backslash") + } + // A quote after a backslash: PostgreSQL with standard_conforming_strings off, and MySQL, read it as escaped. + for (const [sql, warehouse] of [ + ["select 'it\\'s' from t", "pg"], + ["select 'a\\b' from t", "my"], + ]) { + const out = (await explain(sql, warehouse)).output + expect(out).toContain("backslash") + expect(out).toContain("CHR(92) or CHAR(92)") + } + }) + + test("tokenizeSql reports a backslash cause only for a backslash", () => { + expect(tokenizeSql("select 'abc", "postgres")).toMatchObject({ complete: false, backslash: false }) + expect(tokenizeSql("select 'it\\'s'", "postgres")).toMatchObject({ complete: false, backslash: true }) + // BigQuery escapes with a backslash, so a string left open after one most likely ends in an escaped quote. + expect(tokenizeSql("select 'abc\\'", "bigquery")).toMatchObject({ complete: false, backslash: true }) + expect(tokenizeSql("select 'a\\b'", "sqlite")).toMatchObject({ complete: true, backslash: false }) + }) + + test("the dbt adapter refusal names only the fix that applies: plan mode, or --allow-write", async () => { + const plan = await dbtAdapterFor(ctx({ agent: "plan" })) + const readOnly = await dbtAdapterFor(ctx({ extra: { forceReadOnly: true } })) + for (const access of [plan, readOnly]) { + expect(access.adapter).toBeUndefined() + expect(access.refusal).toBe("read_only") + } + expect(plan.reason).toContain("outside plan mode") + expect(plan.reason).not.toContain("--allow-write") + expect(readOnly.reason).toContain("--allow-write") + expect(readOnly.reason).not.toContain("plan mode") + }) + + test("a cancelled call is not answered with a refusal", async () => { + const abort = new AbortController() + abort.abort() + await expect(dbtAdapterFor(ctx({ abort: abort.signal, agent: "plan" }))).rejects.toBeDefined() + }) +}) + +describe("v0.12.12: integration API overrides receive the token only on https or this machine", () => { + const NAME = "ALTIMATE_INTEGRATIONS_GITHUB_API" + const saved = process.env[NAME] + afterEach(() => { + if (saved === undefined) delete process.env[NAME] + else process.env[NAME] = saved + }) + const override = (value: string) => { + process.env[NAME] = value + return credentialsInternals.apiOverride(NAME) + } + test("https and a local http address are used", () => { + for (const v of ["https://ghe.example/api/v3", "http://127.0.0.1:8080", "http://localhost", "http://[::1]:9/x"]) expect(override(v)).toBe(v) + }) + test("userinfo before a remote host, credentials, a remote http host and junk are ignored", () => { + for (const v of [ + "http://localhost:1234@evil.example", + "http://127.0.0.1@evil.example/", + "https://user:pass@ghe.example", + "http://localhost.evil.example", + "http://127.0.0.1.evil.example", + "http://ghe.example", + "file:///etc/passwd", + "javascript:alert(1)", + "not a url", + " ", + ]) + expect(override(v)).toBeUndefined() + }) +}) + +describe("v0.12.12: the missing-fields hint re-runs the call that failed", () => { + // An empty environment with only bun on PATH: no gh login or token can be detected and used. + const run = async (...args: string[]) => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "release-v0.12.12-hint-")) + try { + await fs.mkdir(path.join(dir, "bin")) + await fs.symlink(process.execPath, path.join(dir, "bin", "bun")) + const cli = path.join(import.meta.dir, "../../src/index.ts") + const p = Bun.spawnSync([path.join(dir, "bin", "bun"), "run", cli, "integrations", ...args], { + // NODE_ENV and ALTIMATE_TELEMETRY_DISABLED keep the child from sending telemetry. + env: { + HOME: dir, + PATH: path.join(dir, "bin"), + ALTIMATE_INTEGRATIONS_DIR: dir, + ALTIMATE_INTEGRATIONS_MOCK: "1", + NODE_ENV: "test", + ALTIMATE_TELEMETRY_DISABLED: "1", + }, + stdout: "pipe", + stderr: "pipe", + }) + return p.stdout.toString() + p.stderr.toString() + } finally { + await fs.rm(dir, { recursive: true, force: true }) + } + } + + test("--local-only is kept, so following the hint does not sync the credential", async () => { + const out = await run("connect", "github", "--local-only") + expect(out).toContain("Missing:") + expect(out).toContain("`altimate integrations connect github --local-only` again") + }, 60_000) + + test("--variant goes on fields and the re-run, and --share is kept", async () => { + const out = await run("connect", "jira", "--variant", "server", "--share") + expect(out).toContain("`altimate integrations fields jira --variant server`") + expect(out).toContain("`altimate integrations connect jira --variant server --share` again") + }, 60_000) + + test("a variant named by its label is quoted, so the copied command parses", async () => { + const out = await run("connect", "jira", "--variant", "Jira Server / Data Center") + expect(out).toContain("`altimate integrations fields jira --variant 'Jira Server / Data Center'`") + }, 60_000) +}) + +describe("v0.12.12: source guards", () => { + test("integration API overrides are used only for https or a local http address", async () => { + const text = await read("altimate/integrations/credentials.ts") + for (const name of ["ALTIMATE_INTEGRATIONS_GITHUB_API", "ALTIMATE_INTEGRATIONS_LINEAR_API", "ALTIMATE_INTEGRATIONS_JIRA_API"]) { + expect(text).toContain(`apiOverride("${name}")`) + expect(text).not.toContain(`process.env.${name}`) + } + }) + + test("the nine dbt Power User tools stay out of the in-session agent registry", async () => { + const registry = await read("tool/registry.ts") + for (const name of ["DbtCostEstimateTool", "DbtCteProfileTool", "DbtDeferStateTool", "DbtDocsCoverageTool", "DbtHealthTool", "DbtMapRelationsTool", "DbtRunResultsTool", "DbtSqlGraphTool", "DocsShareCommentsTool"]) + expect(registry).not.toContain(name) + }) +}) + +describe("v0.12.12: altimate review refs and remote-config errors", () => { + for (const [field, opts] of [ + ["--base", { base: "--output=/tmp/x" }], + ["--head", { base: "main", head: "-c" }], + ] as const) { + test(`a ${field} that starts with "-" is refused before git sees it`, async () => { + await expect(resolveReviewBase({ ...opts, cwd: os.tmpdir(), env: {} })).rejects.toThrow(`${field} `) + await expect(resolveReviewBase({ ...opts, cwd: os.tmpdir(), env: {} })).rejects.toThrow('cannot start with "-"') + }) + } + + test("remote-config errors and the debug log never interpolate the substituted URL", async () => { + const text = await read("config/config.ts") + expect(text).not.toContain("failed to decode remote config from ${remote.url}") + expect(text).not.toContain("failed to decode remote config from ${url}") + expect(text).not.toContain('logDebug("fetching remote config", { url: remote.url })') + }) +})