diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d80bdaa77..c3384cc1b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,42 +5,50 @@ 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). -## [Unreleased] +## [0.12.13] - 2026-12-04 -**Breaking: `dbt_cost_estimate` is BigQuery only, so Snowflake and Databricks are no longer gated by `maxScanBytes`.** The tool used to give a scan figure on Snowflake and Databricks from the warehouse planner's EXPLAIN (bytes assigned there count partitions before runtime pruning and usually overstate what runs). It now answers `supported: false` on every warehouse but BigQuery and compiles nothing, so the Claude plugin's scan check (`maxScanBytes`, 10 GiB by default) no longer holds a `dbt run`, `build` or `show` on those two warehouses; the command runs with a line saying why. On BigQuery the scan figure is unchanged, and `history: true` now also reads what a model's earlier runs cost (billed `INFORMATION_SCHEMA.JOBS` queries; see the dbt tools page). +**`/logout` signs you out of the provider behind your current model, Amazon Bedrock works in the compiled binary, `altimate review` checks much more of a dbt PR, and a pull request can no longer relax the policy it is judged by.** `altimate review` comments now sit on the changed lines, are not reposted on every run and fit GitHub's size limit. dbt Fusion projects no longer need Python, and `debug bundle` now covers config, credentials, sessions and runtime health. Three changes can break existing setups, all first under the heads-up below: in `gate` mode `altimate review` blocks only on engine findings and the rules you name, its new checks block on removed columns still read downstream and on undocumented PII, and `dbt_cost_estimate` now estimates BigQuery only. -**Breaking: in `gate` mode, `altimate review` blocks only on engine findings, on pattern rules named in `rubric.blockingRules`, and on one proven-new PII pattern finding.** Before, any critical finding in a `blockOn` category could block, including pattern rules such as the regex PII check. Now pattern-rule findings comment but don't block unless their id is named in `rubric.blockingRules`; the AI lane never blocks. One pattern finding still blocks without being named: a highly sensitive PII column (SSN, passport or card number, date of birth) proven new when the base or the head can't be compiled (proven only when the review reads the base file's SQL fully). To keep another pattern rule blocking, add its id to `rubric.blockingRules`. (#1722) +**Heads-up for support:** +- **Breaking: in `gate` mode, `altimate review` blocks only on engine findings, on rules named in `rubric.blockingRules`, and on one proven-new PII finding.** Pattern rules from the rule catalog, such as the regex PII check, and findings from tools the engine does not own now comment without blocking. The AI lane never blocks. A new SSN, passport, card number or date-of-birth column still blocks when the base or the head cannot be compiled. **To keep a rule blocking, add its id to `rubric.blockingRules` in `.altimate/review.yml` on the base branch.** (#1722) +- **Breaking: `altimate review`'s new checks block more PRs, and a bad key in the policy fails the run.** In `gate` mode, a removed column that a downstream model still reads and a PII column on a mart with no documentation now block (they commented before). An unreadable macro, snapshot or changed `dbt_project.yml` holds back approval. An unknown key under `rules:` or `posting:` in the base `.altimate/review.yml` fails the run with exit `1`. A clean run now posts no comment by default (`silentWhenClean`). (#1894) +- **Breaking: `dbt_cost_estimate` estimates BigQuery only.** On Snowflake and Databricks it answers `supported: false` and compiles nothing, so the Claude Code plugin's scan check (`maxScanBytes`, 10 GiB by default) no longer holds a `dbt run`, `build` or `show` there; the command runs with a line saying why. Teams that relied on it should use the warehouse's own guards, such as a Snowflake resource monitor or a statement timeout. BigQuery estimates are unchanged. (#1840) +- **`altimate review` reads `.altimate/review.yml` from the PR's merge-base.** A PR cannot relax the policy it is reviewed under: settings it changes are listed in the comment and take effect after merge, and `--mode` and `--severity` can only tighten the base policy. A PR branched before the target branch had a policy is reviewed under the defaults, and the run says so. A base `review.yml` that does not parse fails every review, including the PR that fixes it, until that PR is merged past the check. (#1722) +- **`altimate review` can now fail a CI job in `comment` mode.** When a check or a file's review throws, the CLI exits `3` in either mode, and the verdict is never APPROVE. An engine fault, a model with no compiled SQL or a file that cannot be read makes an otherwise clean verdict COMMENT and still exits `0`. The comment names what failed without its error message, which goes to the job log with passwords, tokens and connection-string credentials masked; some formats, such as AWS key ids, Google and Stripe keys and cookie values, are not. In a shallow checkout the PR's target branch and head are fetched from `origin`; when that fails the review stops with an error. (#1723) +- **Under a GitHub App token in Actions, set `ALTIMATE_REVIEW_BOT_LOGIN` to the app's account (`[bot]`).** Such a token cannot read its own account, so without the setting each run posts a new summary comment instead of updating the earlier one. The official action uses `GITHUB_TOKEN` and is not affected. After the upgrade, each open PR gets its inline comments once more, since earlier ones carry no finding marker. (#1721, #1894) +- **A blank key, instance name or URL in `altimate.json` now means signed out.** Before, the gateway was listed as connected and its first request failed with 403. A gateway 401 or 403 now says to sign in again. (#1835) +- **Server errors carry a message instead of an empty 500.** An error no handler recognises answers `Unexpected server error. Check server logs for details.` with a ref that is recorded in `opencode.log`; a failed prompt shows the error's text. (#1848) + +### Added + +- **`altimate review` checks much more of a dbt PR** — Consumers outside dbt, a model contract against its SELECT, integer division by dialect, incremental, microbatch and snapshot semantics, data tests that cannot fail, and macro, join, docs and project-file rules. Each rule posts inline, in the summary or not at all, with at most 10 inline comments per PR, and the summary lists what was not reviewed. The advisory AI lane sees more of the change, follows the team conventions in the repository's instruction files, and has its findings checked by a verifier; it never changes the verdict. `--all-projects` reviews every dbt project in a repository. (#1894) +- **`/logout` signs out of the provider behind the current model** — Before, it signed out of the Altimate LLM Gateway only. The menu names the login it removes, such as "Log out of OpenAI (ChatGPT subscription)", and a provider set by an environment variable or the config says where to remove it. (#1845) +- **dbt Fusion without Python** — With `dbtIntegration: fusion`, `altimate-dbt` and the dbt tools look for a dbt 2.x binary (next to the configured Python, in `~/.local/bin` or on `PATH`, launcher scripts included) and need no Python or dbt-core. In Fusion mode their refusals say what Fusion needs and to run `altimate-dbt doctor`. (#1757, #1825) +- **`dbt_cost_estimate` with `history: true` reads what a model's earlier runs cost on BigQuery** — It runs billed `INFORMATION_SCHEMA.JOBS` queries, up to eight per call; see the dbt tools page. (#1840) +- **`--ai-model provider/model` picks the model for `altimate review`'s advisory AI lane.** (#1720) +- **`debug bundle` reports config, credentials, sessions and runtime health** — Config files in load order and the file that set `model` and `small_model`; where each provider's credential was found, never its value; the workspace link and sync status; native modules, disk and cache sizes; and 14 days of session statistics. Failed session-title and prompt-enhancement requests are now logged and become findings. The bundle holds names, counts and error classes, never prompts, file contents or credential values, and keys are redacted by their shape wherever they appear. It still sends no model requests. (#1860) +- **`debug probe` tests the chat model and the small model** — One tool-less request to each, printing the model, where it was set, the HTTP status, latency and error class. Each request counts toward provider usage. (#1860) +- **Docs: install the Claude Code plugin from Altimate's marketplace,** with its panes and commands. (#1809) + +### Fixed + +- **Amazon Bedrock credentials work in the compiled binary** — The binary bundled the AWS SDK's browser stubs, so sign-in through a profile or the credentials file failed. The build now refuses a binary that carries such a stub. (#1867) +- **`dbt_cte_profile` lists the earlier CTEs each CTE reads,** so a CTE that follows a slower one it does not read no longer shows 0 ms. (#1795) +- **The read-only SQL guard accepts EXPLAIN options on a read** — Snowflake `EXPLAIN USING`, Databricks `EXPLAIN EXTENDED`, `FORMATTED` and `COST`, and Postgres option lists. EXPLAIN of a write is still a write. (#1778) +- **Column answers and `dbt_lineage` name only what a SELECT list writes,** and a repeated column beside any `*`, qualified or through a CTE, leaves the model unsettled as it does beside a bare `*`. (#1851) +- **Windows: a relative `ALTIMATE_DRIVER_DIR` finds the drivers npm installed there.** (#1833) +- **dbt-integration 0.3.22** finds dbt Fusion behind a `dbt` on `PATH` that cannot run, names a broken `dbtRunner` import and a project's last load error, and skips the automatic `dbt deps` at project start where it can only fail. (#1857) +- **Release builds retry a failed platform build once, and time-box each attempt.** (#1823, #1824) ### Changed -- **`altimate review` reads `.altimate/review.yml` from the base branch.** A PR can no longer relax the policy it is reviewed under; settings it changes are listed in the comment and take effect after merge. The `--mode` and `--severity` flags (the action's `mode` and `severity_threshold`) can only tighten a base policy, and `allowForceTier: false` rejects `--force-tier`. (#1722) -- **`altimate review` flags PII only for columns the change newly exposes**, not for PII columns the base already surfaced. Without a compiled base, a PII column is a non-blocking warning that may predate the PR, unless the base SQL cannot have exposed it (see the next entry). (#1721) -- **`altimate review` reports three PII exposures it used to call pre-existing.** (#1875) - - Without a compiled base, a PII output column is reported as new, and can block, when the base file's own SQL cannot have exposed that output column name: it does not name it outside comments, it does not name a source column that output reads either, its final query names every column in its own select list (no `*`, `COLUMNS(…)`, whole-row reference, struct expansion or Unicode-escaped name such as `U&"…"`), the review reads that query fully (a CTE column list, a parenthesised UNION, an integer division `//` or a column named like an unaliased `ref` leave it undecided), and it holds no Jinja but `ref`, `source`, `config`, `this` and `if`/`for`/`set` tags. - - A PII column output under another name (`email as contact`) is then new when the base names neither the new name nor the column it reads; a rename of a column the base already names is a non-blocking warning. - - A table compiled under another schema is the same table only when the model's code reads it the same way on both sides (the same `ref`, `source` or table name; the quote style and spacing inside a `ref` or `source` call do not count, a quoted SQL name is compared as written), or, for a model compiled under a name its `ref` does not show (an alias, a version or a source `identifier:`), when no relation in the model's code was added or replaced (a table read through an ephemeral model counts the same way); a schema, `source`, `var` or package a relation is built from, swapped in the model's code, is reported, and so is a `{% set %}` variable it is built from whose plain string value was replaced (`'masked'` → `'raw'`; the quote style and `{# … #}` comments do not count). - - Where the code cannot decide (such a model only gained a relation, the SQL is a shape the review does not fully parse or lists no relation, as when a macro emits the query, two different relations share one table name or one was added or removed beside an unchanged one, a `ref` gained or lost a package argument, or such a `{% set %}` changed in another way), the column is a non-blocking warning that may predate the PR, and such a warning never hides another PII finding. - - Renaming a CTE or subquery alias, turning a CTE into a subquery, qualifying a column, adding a join, or reading a CTE through `select *` instead of naming its columns, is not a change for a computed PII column (`lower(email) as email`), nor is an environment whose schemas sort differently. - - A UNION branch that computes PII under a name the base already exposed (`lower(ssn) as email`) is reported, also after a first branch that selects `*` from a CTE or subquery whose columns are all known, and so is a swap of which table each branch's computation reads (`md5(email)` from `a` and `lower(email)` from `b` reversed) or of which column sits in which argument (`coalesce(m.email, r.email)` reversed, where `m` masks it). - - Now reported that was not before: qualifying a raw table name (`from customers` → `from analytics.customers`), and replacing any relation, even an unrelated join, in a model compiled under a name its `ref` does not show. - - Not reliably detected yet: any later-branch column, raw or computed, at or after a `*` over a table, a `ref()`, a CTE that itself selects `*` or a `using`/`natural` join (its columns are matched only by their position among the select items; a new column past the last of them is a non-blocking warning), and any column of a later branch that itself selects `*`. - - A source schema changed in YAML is a non-blocking warning, for every `source()` in the reviewed models, when the same PR edits a `schema:`, `database:` or `identifier:` key in a source YAML (or deletes one) and also changes a model that reads a source; a PR that edits only the YAML gets no finding, and a `+schema` for sources in `dbt_project.yml`, a schema from `var()` or `env_var()` or set through a YAML anchor or folded value, and changes made outside the PR are not detected. - - Comparing source YAML per source and table (so a moved source or an edit to an unrelated source no longer turns every `source()` read into a warning) moved to a follow-up. - - An alias or qualifier changed inside `over (…)`, `filter (…)` or `within group (…)` is not a change for a computed PII column; a column there switched to another table (`over (order by c.id)` → `o.id`) is reported. - - A swap of which of two same-named tables in different schemas is read masked (`md5(m.email) || r.email` → `md5(r.email) || m.email` over `crm.customers` and `erp.customers`) is reported. When the two are `source()` calls and the base was compiled into another environment, it is a non-blocking warning, and so is any edit to a computed PII column of such a model. - - Without a compiled base, a base holding a `\'` inside a string literal that reads fully both as an escaped quote and as the end of the literal is undecided. - - A column the engine reported as undecided no longer gets a blocking pattern finding beside it. - - `{% set %}` tags with `+` white space control are read like the others; a changed `set` in a form the review does not read (a tuple target) is a non-blocking warning; a variable named only as an attribute (`target.schema`) is not the changed variable; and, in a model with no `if`/`for`/`macro` tag, an assignment that a later one always overwrites changes nothing. - - A PII read moved from one CTE or subquery to another is reported, whatever the two are called and whether the old one is kept or deleted, and so is one that skips a CTE that filters, joins or groups (reading the CTE below it). A CTE renamed and edited at once counts as edited in place. It is not a change when the new one is the old one plus a filter (a trailing `where`, `qualify`, `having`, `limit` or `order by`, one more `and` condition on its `where`, or `select distinct`: fewer rows at most; never with `or`, a set operator, or a window or aggregate in the CTE), nor when nothing left the value's way (a new layer on top), nor when a CTE is inlined as the final query. Editing the CTE it reads is still not a change by itself, so a filter removed there is not detected. - - A column inside `over (…)`, `filter (…)` or `within group (…)` newly read through a CTE or subquery that has rows of its own (it filters, joins or groups, or it is a joined source the value itself is not read through) is reported. - - A UNION whose `*` is written out as columns, or the reverse, in a branch whose columns cannot be placed, is a non-blocking warning. - - An expression over more than 64 column reads no longer tells two same-named tables apart. - - Without a compiled base, a base that renames columns in its FROM (an alias column list after a Jinja relation, `pivot`, `unpivot`, `columns(…)`) is undecided. - - A pattern finding for a column the engine left undecided is dropped also when the column's alias is on the next line. - - A source YAML key whose line changed only in a trailing comment or its spacing is not a source move. - - A PII column read through a CTE whose columns the review cannot list (`* replace (…)`, a struct field) is reported when that CTE's body changes. - - When only the head is in a shape the review does not follow (DuckDB `from … select`), the column is a non-blocking warning. - - A relation whose table the code does not name is undecided, never a swap: a `ref` or `source` call with a variable argument that was renamed or inlined (its `{% set %}` literal replaced is a swap), a replaced relation beside a macro call that stands for a relation, and a rewritten `{% if %}` or `{% for %}` that chooses the relation after `from` or `join`. +- **`altimate review` PR comments sit on the changed lines and are not reposted** — Inline comments are anchored to the diff, a finding already posted is not posted again, findings from one rule are grouped, and the comment fits GitHub's size limit, with findings past it counted. PII is flagged only for columns the change newly exposes, and SQL portability notes are left out when the dialect is known. (#1721) +- **The `altimate review` comment says what it checked** — "Lint-only" now means no changed model resolved against a manifest, and an empty lint-only run no longer reads as an all-clear. Undecided findings, unverified models, out-of-scope files and the AI lane's status (`ok`, `skipped`, `timeout` or `error`, with the reason) each get a line. (#1720) +- **`altimate review` reports three PII exposures it used to treat as pre-existing** — a PII output column the base SQL cannot have exposed, when there is no compiled base; a PII column output under a new name (`email as contact`); and a computed PII column whose table changed (a schema, `source`, CTE or UNION branch swapped). Where the code cannot decide, the column is a non-blocking warning. The full rules, and what is not detected yet, are under **What the PR comment shows** on the dbt PR review page. (#1875) +- **A broken `altimate review` run never reads as clean** — An engine error, an unreadable file or a changed model without compiled head SQL is named in the comment and keeps the verdict from APPROVE, and a model the PII check could not analyse is listed as not fully verified. The envelope and telemetry record each failure's kind, check and file. (#1723) +- **`altimate review`: an equivalence check that cannot decide is listed as not fully verified instead of a warning, so the PR can approve.** Suggestions are never posted inline, and the "high downstream fan-out" warning is removed. (#1894) +- **`allowForceTier: false` in the base policy rejects `--force-tier`.** (#1722) +- **`altimate review` runs git in the C locale,** so the base-policy lookup works on a runner with a non-English locale. ## [0.12.12] - 2026-11-20 diff --git a/docs/docs/data-engineering/guides/using-with-claude-code.md b/docs/docs/data-engineering/guides/using-with-claude-code.md index 4189b72c5f..d63dc93406 100644 --- a/docs/docs/data-engineering/guides/using-with-claude-code.md +++ b/docs/docs/data-engineering/guides/using-with-claude-code.md @@ -145,7 +145,7 @@ The helpers read `manifest.json` and `run_results.json` from the `target-path` t The rest of the plugin's panes and commands call Altimate Code's tools through `altimate tool run`, and make no model-provider call of their own. The dbt Power User ones need altimate-code 0.12.12 or later, the release with the [dbt Power User tools](../tools/dbt-tools.md#dbt-power-user-tools); with an older one most say so where their answer would be, while `/runs` records nothing and `/defer` adds no flags. Cost, health, the SQL graph and CTE timing start the project's dbt adapter, so the plugin runs them with `altimate tool run --allow-write` itself, without asking. The commands are listed by the bare names the plugin registers. - **Lineage pane** (`/lineage [.column]`). The dbt model Claude reads or edits, with every model upstream and downstream, its exposures (dashboards and other consumers), each output column's sources and, for a picked column, the downstream models and dashboards that read it, from `dbt_lineage` and `impact_analysis` on `target/manifest.json`. When a task changed a model, a band above the prompt sums up each changed column's downstream reach, and **Open report** or `/lineage-report` builds an offline HTML report of it. Claude Code opens the pane on its own only in a terminal at least 144 columns wide; `/lineage` opens it at any width. -- **Scan cost check** (`/scan-cost `, `/allow-scan`). Before a `dbt run`, `build` or `show` that Claude runs names one model or an inline query, `dbt_cost_estimate` says what it would scan from a BigQuery dry run. The scan check uses the dry run only and sends no `INFORMATION_SCHEMA` query. A model's earlier run cost is read only when `dbt_cost_estimate` is asked with `history: true`, and each such call runs up to eight billed `INFORMATION_SCHEMA.JOBS` queries (three normally: capacity, history and boundary; one more for the earlier jobs of labelled invocations, which reads back to the 180 days JOBS keeps and can scan far more query text than the history; one more when a script matched, for its children; up to eight if your role cannot list every user's jobs, since the capacity, history and children reads each run again on `JOBS_BY_USER`, which scans only your own jobs, so service-account and other users' runs are left out and the answer says so first; the project-wide read needs `bigquery.jobs.create` and `bigquery.jobs.listAll`, the fallback `bigquery.jobs.create` and `bigquery.jobs.list`): a capacity check (7 days of jobs), the history (30 days, scanning the query text of every query job in the project, so the bytes grow with the project's activity, not the model, and its 500-row cap does not cap the bytes), the boundary (one more query, which also finds the model's jobs that are queued, running, or have no end time) and, when a script matched, the script's children. Each is billed on demand (at least 10 MiB) or uses reservation slots, and `INFORMATION_SCHEMA` is never cached. It works on BigQuery only. Over the plugin's `maxScanBytes` setting (10 GiB by default; 0 never holds) the command is refused with the estimate until you run `/allow-scan`, which lets that same command through once. A query with no estimate runs, with a line saying why, and other warehouses, Snowflake and Databricks included, are never held. +- **Scan cost check** (`/scan-cost `, `/allow-scan`). Before a `dbt run`, `build` or `show` that Claude runs names one model or an inline query, `dbt_cost_estimate` says what it would scan from a BigQuery dry run, which is free and sends no `INFORMATION_SCHEMA` query. Over the plugin's `maxScanBytes` setting (10 GiB by default; 0 never holds) the command is refused with the estimate until you run `/allow-scan`, which lets that same command through once. A query with no estimate runs, with a line saying why. The check works on BigQuery only: on Snowflake and Databricks no scan limit applies, so use the warehouse's own guards, such as a resource monitor or a statement timeout. What a model's earlier runs cost is read only when `dbt_cost_estimate` is called with `history: true`, which runs billed `INFORMATION_SCHEMA.JOBS` queries; see [dbt_cost_estimate](../tools/dbt-tools.md#dbt_cost_estimate). - **Project health** (`/health`). At session start `dbt_health` (DataPilot) records the project's existing insights; after a turn in which Claude changed model files, the check runs again and the new issues on those models show in a band. With `healthBlocksPush` on, `git push` is refused while the check of your latest changes is not in or finds new issues. `healthConfigPath` names a DataPilot config file by a path inside the dbt project. A check can take minutes, and it needs the `altimate-datapilot-cli` package in the project's Python. - **Team comments** (`/comments`). The open comment threads on dbt docs your team shared through Altimate, fetched at session start and, in an interactive session, every `commentsPollSeconds` (15 minutes by default). When Claude reads or edits a model that has open threads, they are added to its context as quoted data (`commentsInContext`), so it sees the review before it changes the model. Reply and resolve are buttons you press in the pane; Claude has no way to post. Needs an Altimate sign-in. - **dbt runs** (`/runs`). The dbt commands Claude ran that wrote `run_results.json`, with their per-node results from `dbt_run_results`, up to 50 runs per project, kept on this machine across sessions. From the pane a run can be opened, run again, or its failures run again through the prompt. diff --git a/docs/docs/data-engineering/tools/dbt-tools.md b/docs/docs/data-engineering/tools/dbt-tools.md index 12fc8e8c53..13e926b21e 100644 --- a/docs/docs/data-engineering/tools/dbt-tools.md +++ b/docs/docs/data-engineering/tools/dbt-tools.md @@ -296,6 +296,8 @@ altimate-dbt deps # Manage dependencies All commands provide friendly error diagnostics with actionable fix suggestions when something goes wrong. +**dbt Fusion.** With `dbtIntegration` set to `fusion` in the altimate-dbt config, no Python and no dbt-core are needed. altimate-dbt looks for a `dbt` whose `dbt --version` reports 2.x: next to the configured Python when that is a path, in `~/.local/bin`, or on `PATH`. Launcher scripts such as asdf or nix shims count. In this mode `altimate-dbt doctor` checks that binary and the project instead of Python and dbt-core. + > **Tip:** In builder mode, the agent prefers `altimate-dbt` over the raw `dbt_run` tool for better error handling and auto-detection. --- diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 2f66c8a005..0d427ab3c9 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -126,7 +126,7 @@ Options: |------|------| | `0` | The review completed without an internal exception, and in `gate` mode the verdict is not `REQUEST_CHANGES`. An engine fault, a model without compiled SQL, or a side of a changed file that could not be read makes the verdict COMMENT and still exits `0`, in both modes. | | `2` | `gate` mode, the verdict is `REQUEST_CHANGES`, and there was no internal exception. | -| `3` | The review hit an internal exception (a check or a file's review threw), in any mode. It takes precedence over `2`. The verdict and comment are still produced and name the failure; the envelope carries `internalFailure: true`, and the verdict is never APPROVE. | +| `3` | The review hit an internal exception (a check or a file's review threw), in any mode. It takes precedence over `2`. The verdict and comment are still produced and name the failure; the envelope carries `internalFailure: true`, and the verdict is never APPROVE. It means a bug in the review, not a finding: report it with the job log. | | `1` | The review could not run at all: bad arguments, no git repository, an unreadable base, or a base `.altimate/review.yml` that fails validation (a value of the wrong type, an unknown key under `ai:` or `posting:`, a `rules:` key that is not a rule id, a `tool:*` glob or `*`). Also when writing `--output` or posting the summary to GitHub fails after a completed review; this exit `1` replaces the `2` a `gate` block would have given, but not a `3`: precedence is `3`, then `1`, then `2`. | > **Full vs lint-only.** With a compiled `manifest.json` present, the reviewer diff --git a/packages/opencode/src/altimate/review/config.ts b/packages/opencode/src/altimate/review/config.ts index c3df5b8ea6..eda621ac09 100644 --- a/packages/opencode/src/altimate/review/config.ts +++ b/packages/opencode/src/altimate/review/config.ts @@ -210,7 +210,7 @@ export function resolveRubric(cfg: ReviewConfig): Rubric { }) } -const CANDIDATE_FILES = [".altimate/review.yml", ".altimate/review.yaml", ".altimate/review.json"] +export const CANDIDATE_FILES = [".altimate/review.yml", ".altimate/review.yaml", ".altimate/review.json"] /** Parse review config from raw text (YAML or JSON). Exposed for testing. */ export function parseReviewConfig(text: string): ReviewConfig { diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index 586648deb9..0dd0b2f3ab 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -218,7 +218,8 @@ function renderSummaryWith(env: VerdictEnvelope, opts: RenderOptions): string { if (!env.findings.length) { // With a broken run, no findings means not checked, not clean; with files - // left unverified it is clean only as far as the checks reached. + // left unverified it is clean only as far as the checks reached; a + // lint-only run checked less, so its empty result is not an all-clear. const unverified = unverifiedFiles(env) const hiddenBehind = (env.withheld ?? []).some((w) => w.verdict > 0 || (w.reason !== undefined && w.reason !== "rule_off")) lines.push( @@ -230,7 +231,9 @@ function renderSummaryWith(env: VerdictEnvelope, opts: RenderOptions): string { ? "No findings are listed: the findings behind this verdict are hidden (see above)." : unverified ? `No issues found; ${unverified} file(s) not fully verified (see above).` - : "No issues found in the changed dbt models. 🎉", + : env.summary.degraded + ? "No lint findings in the changed dbt models." + : "No issues found in the changed dbt models. 🎉", "", ) lines.push(...ledgerBlock(env, Math.max(120, maxChars - [...lines, ...tail].join("\n").length))) diff --git a/packages/opencode/src/altimate/review/run.ts b/packages/opencode/src/altimate/review/run.ts index 7b13b63a5b..2909655a75 100644 --- a/packages/opencode/src/altimate/review/run.ts +++ b/packages/opencode/src/altimate/review/run.ts @@ -2,7 +2,7 @@ import path from "node:path" import { readFile, realpath, stat, access, readdir } from "node:fs/promises" import YAML from "yaml" import { Installation } from "../../installation" -import { aiLaneEnabled, headPolicyChanges, loadReviewPolicy, policyHash, resolveRubric } from "./config" +import { aiLaneEnabled, CANDIDATE_FILES, headPolicyChanges, loadReviewPolicy, policyHash, resolveRubric } from "./config" import { SEVERITY_ORDER, type Severity } from "./finding" import { collectChangedFiles, @@ -375,9 +375,25 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise policy.changedInPr = [...new Set([...policy.changedInPr, ...addedHere])] } const config = policy.config + const cwdRel = await repoRelative(gitRoot, opts.cwd, true) + if (resolved && cwdRel !== undefined && policy.source === "default" && !policy.changedInPr.length) { + // A PR branched before the target branch gained its policy is reviewed under the defaults. + for (const rel of CANDIDATE_FILES) { + const atTip = await showAtRef(opts.cwd, resolved.ref, path.posix.join(cwdRel, rel)).catch(() => undefined) + if (atTip === undefined) continue + process.stderr.write( + `ℹ️ ${resolved.ref} has a ${rel} that the merge-base (${resolved.sha.slice(0, 10)}) lacks, ` + + `so the default policy was applied. Rebase onto ${resolved.ref} to be reviewed under its policy.\n`, + ) + break + } + } if (policy.changedInPr.length) { process.stderr.write( - `ℹ️ this PR changes .altimate/review (${policy.changedInPr.join(", ")}); the base branch's policy was applied.\n`, + `ℹ️ this PR changes .altimate/review (${policy.changedInPr.join(", ")}); ` + + (policy.source === "default" + ? `the merge-base has no policy, so the default policy was applied.\n` + : `the base branch's policy was applied.\n`), ) } if (opts.forceTier && config.allowForceTier === false) { diff --git a/packages/opencode/test/cli/run/json-output.test.ts b/packages/opencode/test/cli/run/json-output.test.ts index d75274645b..9a608f9ecf 100644 --- a/packages/opencode/test/cli/run/json-output.test.ts +++ b/packages/opencode/test/cli/run/json-output.test.ts @@ -103,15 +103,15 @@ describe("opencode run: JSON output artifacts", () => { const answer = "The notes contain the current supported answer." yield* Effect.promise(() => Bun.write(inputPath, "current supported answer\n")) // The sleep is the workload being budgeted, not a synchronization delay. - // Five seconds leaves headroom for prompt setup and the final read after - // crossing the four-second soft deadline. - yield* llm.tool("bash", { command: "sleep 4.05", description: "Simulate a slow exploration tool" }) + // The soft deadline is at 80% of the budget (eight seconds); the sleep crosses + // it, and the two seconds left are for the read and two model round trips. + yield* llm.tool("bash", { command: "sleep 8.05", description: "Simulate a slow exploration tool" }) yield* llm.tool("read", { filePath: inputPath }) yield* llm.text(answer) const result = yield* opencode.run("Read the notes and give the supported answer.", { format: "json", - extraArgs: ["--time-budget", "5", "--output", outputPath], + extraArgs: ["--time-budget", "10", "--output", outputPath], bunRun: true, env: { ALTIMATE_CLI_YOLO: "true", @@ -131,7 +131,7 @@ describe("opencode run: JSON output artifacts", () => { expect(requests.filter(isBudgetFinalization)).toHaveLength(0) const events = opencode.parseJsonEvents(result.stdout) - expect(events.filter((event) => event.type === "time_budget_warning")).toMatchObject([{ limit_seconds: 5 }]) + expect(events.filter((event) => event.type === "time_budget_warning")).toMatchObject([{ limit_seconds: 10 }]) expect(events.filter((event) => event.type === "budget_exhausted")).toHaveLength(0) // altimate_change start — the soft deadline preserves a tool result after it finishes const tools = events.filter((event) => event.type === "tool_use").map((event) => event.part) @@ -141,14 +141,14 @@ describe("opencode run: JSON output artifacts", () => { expect(JSON.stringify(requests[2])).toContain("current supported answer") // altimate_change end expect(events.filter((event) => event.type === "termination")).toMatchObject([ - { why_harness_stopped: "none", time_budget_s: 5, time_budget_deadline: "soft" }, + { why_harness_stopped: "none", time_budget_s: 10, time_budget_deadline: "soft" }, ]) const saved = events.filter((event) => event.type === "trace_saved") expect(saved).toHaveLength(1) const trace: TraceFile = yield* Effect.promise(() => Bun.file(saved[0]!.path as string).json()) - expect(trace.metadata).toMatchObject({ time_budget_s: 5, time_budget_deadline: "soft" }) - expect(trace.metadata.elapsed_s).toBeGreaterThanOrEqual(4) - expect(trace.metadata.elapsed_s).toBeLessThan(5) + expect(trace.metadata).toMatchObject({ time_budget_s: 10, time_budget_deadline: "soft" }) + expect(trace.metadata.elapsed_s).toBeGreaterThanOrEqual(8) + expect(trace.metadata.elapsed_s).toBeLessThan(10) expect(yield* llm.pending).toBe(0) }), 90_000, @@ -209,8 +209,10 @@ describe("opencode run: JSON output artifacts", () => { expect(output).toBe(finalAnswer) expect(events.filter((event) => event.type === "silent_turn")).toHaveLength(0) } else { + // The unfinished reply follows the note (run-output.ts `preserveLastText`). expect(output).toBe( - "No final answer was produced: the work budget was exhausted and the best-effort reply did not provide an answer.", + "No final answer was produced: the work budget was exhausted and the best-effort reply did not provide an answer." + + "\n\nPartial assistant response (not finalized):\n\nLet me explore a little further before answering.", ) expect(events.filter((event) => event.type === "silent_turn")).toHaveLength(1) } diff --git a/packages/opencode/test/skill/release-v0.12.13-adversarial.test.ts b/packages/opencode/test/skill/release-v0.12.13-adversarial.test.ts new file mode 100644 index 0000000000..c7465e5bf5 --- /dev/null +++ b/packages/opencode/test/skill/release-v0.12.13-adversarial.test.ts @@ -0,0 +1,346 @@ +import { describe, test, expect, afterAll, afterEach, spyOn } from "bun:test" +import { promises as fs } from "node:fs" +import path from "node:path" +import { tmpdir } from "node:os" +import { execFile } from "node:child_process" +import { promisify } from "node:util" +import { makeFinding } from "../../src/altimate/review/finding" +import { buildEnvelope } from "../../src/altimate/review/verdict" +import { renderSummary, REVIEW_MARKER } from "../../src/altimate/review/format" +import { postGitHubReview } from "../../src/altimate/review/post-github" +import { reviewPullRequest } from "../../src/altimate/review/run" +import { resolveHeadRef, showAtRef } from "../../src/altimate/review/git" +import { clientMessage } from "../../src/altimate/server/error-response" +import { classifyAndCheck } from "../../src/altimate/tools/sql-classify" + +/** + * v0.12.13 release: the fixes made during the release review (the review's git + * locale, the merge-base policy notice, the app-token summary account, the + * lint-only empty result) and adversarial inputs for the shipped changes. + */ + +const exec = promisify(execFile) + +/** A temporary folder, removed when the file's tests finish. */ +const made: string[] = [] +async function tmp(prefix: string) { + const dir = await fs.mkdtemp(path.join(tmpdir(), prefix)) + made.push(dir) + return dir +} +afterAll(() => Promise.all(made.map((d) => fs.rm(d, { recursive: true, force: true })))) +const g = (cwd: string, ...args: string[]) => exec("git", args, { cwd }).then((r) => r.stdout.trim()) + +/** Everything written to stderr while `fn` runs. */ +async function stderrOf(fn: () => Promise): Promise { + const out: string[] = [] + const spy = spyOn(process.stderr, "write").mockImplementation(((chunk: unknown) => { + out.push(String(chunk)) + return true + }) as typeof process.stderr.write) + try { + await fn() + } finally { + spy.mockRestore() + } + return out.join("") +} + +describe("review: git runs in the C locale", () => { + const saved = { LANG: process.env.LANG, LANGUAGE: process.env.LANGUAGE, LC_ALL: process.env.LC_ALL, PATH: process.env.PATH } + afterEach(() => { + for (const [k, v] of Object.entries(saved)) { + if (v === undefined) delete process.env[k] + else process.env[k] = v + } + }) + + async function oneCommit() { + const root = await fs.realpath(await tmp("rel-locale-")) + await g(root, "init", "-q", "-b", "main") + await g(root, "config", "user.email", "t@test") + await g(root, "config", "user.name", "t") + await g(root, "config", "commit.gpgsign", "false") + await fs.writeFile(path.join(root, "a.txt"), "a\n") + await g(root, "add", "-A") + await g(root, "commit", "-qm", "c") + return root + } + + test("an absent path is absent under a translated locale", async () => { + const root = await oneCommit() + for (const [lang, language] of [ + ["de_DE.UTF-8", "de"], + ["fr_FR.UTF-8", "fr"], + ["ja_JP.UTF-8", "ja"], + ]) { + process.env.LANG = lang + process.env.LANGUAGE = language + process.env.LC_ALL = lang + expect(await showAtRef(root, "HEAD", ".altimate/review.yml")).toBeUndefined() + expect(await showAtRef(root, "HEAD", "a.txt")).toBe("a\n") + } + }, 30_000) + + // The runner may not have a translated locale installed, in which case git prints English + // whatever the env says. A `git` on PATH that records `LC_ALL` checks what git is given. + test.skipIf(process.platform === "win32")("every git call, the fetch included, gets LC_ALL=C", async () => { + const realGit = Bun.which("git")! + const origin = await oneCommit() + await g(origin, "branch", "other") + const otherSha = await g(origin, "rev-parse", "other") + const clone = await fs.realpath(await tmp("rel-locale-clone-")) + await g(clone, "clone", "-q", "--single-branch", "-b", "main", origin, ".") + const bin = await tmp("rel-locale-bin-") + const log = path.join(bin, "calls.log") + await fs.writeFile( + path.join(bin, "git"), + `#!/bin/sh\nprintf '%s %s\\n' "\${LC_ALL-unset}" "$1" >> '${log}'\nexec '${realGit}' "$@"\n`, + { mode: 0o755 }, + ) + process.env.PATH = `${bin}${path.delimiter}${process.env.PATH}` + process.env.LC_ALL = "de_DE.UTF-8" + process.env.LANGUAGE = "de" + expect(await showAtRef(clone, "HEAD", ".altimate/review.yml")).toBeUndefined() + // `other` exists only on origin, so this fetches. + expect(await resolveHeadRef("other", clone)).toBe(otherSha) + const calls = (await fs.readFile(log, "utf8")).trim().split("\n") + expect(calls.some((c) => c.endsWith(" show"))).toBe(true) + expect(calls.some((c) => c.endsWith(" fetch"))).toBe(true) + expect(calls.filter((c) => !c.startsWith("C "))).toEqual([]) + }, 30_000) + + test("a bad ref still fails closed, whatever the locale", async () => { + const root = await oneCommit() + process.env.LANGUAGE = "de" + await expect(showAtRef(root, "no-such-ref", ".altimate/review.yml")).rejects.toThrow() + await expect(showAtRef(root, "HEAD~5", "a.txt")).rejects.toThrow() + }, 30_000) + + test("a path that tries to leave the repository is never read", async () => { + const root = await oneCommit() + for (const rel of ["../../etc/passwd", "/etc/passwd", "a.txt\0x"]) { + const got = await showAtRef(root, "HEAD", rel).catch(() => "threw") + expect(got === undefined || got === "threw").toBe(true) + } + }, 30_000) +}) + +describe("review: a PR branched before the target gained its policy", () => { + const saved = { ...process.env } + afterEach(() => { + for (const k of ["GITHUB_EVENT_PATH", "GITHUB_BASE_REF", "CI_MERGE_REQUEST_TARGET_BRANCH_NAME"]) { + if (saved[k] === undefined) delete process.env[k] + else process.env[k] = saved[k] + } + }) + + /** main → feature; then main gains `policyFile` (unless undefined) after feature branched. */ + async function repo(policyFile: string | undefined, prAdds?: string) { + const root = await fs.realpath(await tmp("rel-policy-")) + await g(root, "init", "-q", "-b", "main") + await g(root, "config", "user.email", "t@test") + await g(root, "config", "user.name", "t") + await g(root, "config", "commit.gpgsign", "false") + await fs.mkdir(path.join(root, "models"), { recursive: true }) + await fs.writeFile(path.join(root, "dbt_project.yml"), "name: p\n") + await fs.writeFile(path.join(root, "models", "a.sql"), "select 1 as id\n") + await g(root, "add", "-A") + await g(root, "commit", "-qm", "base") + await g(root, "checkout", "-q", "-b", "feature") + await fs.writeFile(path.join(root, "models", "a.sql"), "select 2 as id\n") + if (prAdds) { + await fs.mkdir(path.join(root, ".altimate"), { recursive: true }) + await fs.writeFile(path.join(root, prAdds), "mode: gate\n") + } + await g(root, "add", "-A") + await g(root, "commit", "-qm", "pr") + if (policyFile) { + await g(root, "checkout", "-q", "main") + await fs.mkdir(path.join(root, ".altimate"), { recursive: true }) + await fs.writeFile(path.join(root, policyFile), "mode: gate\n") + await g(root, "add", "-A") + await g(root, "commit", "-qm", "policy") + await g(root, "checkout", "-q", "feature") + } + delete process.env.GITHUB_EVENT_PATH + delete process.env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME + process.env.GITHUB_BASE_REF = "main" + return root + } + + for (const file of [".altimate/review.yml", ".altimate/review.yaml", ".altimate/review.json"]) { + test(`names the target's ${path.basename(file)} the merge-base lacks`, async () => { + const root = await repo(file) + let env: Awaited> | undefined + const err = await stderrOf(async () => { + env = await reviewPullRequest({ cwd: root, head: "HEAD", noAi: true }) + }) + // Still the merge-base policy: the PR is not judged by a policy it never branched from. + expect(env?.policy?.source).toBe("default") + expect(env?.mode).toBe("comment") + expect(err).toContain(`has a ${file} that the merge-base`) + expect(err).toContain("Rebase onto") + }, 60_000) + } + + test("a repo with no policy anywhere says nothing about it", async () => { + const root = await repo(undefined) + const err = await stderrOf(() => reviewPullRequest({ cwd: root, head: "HEAD", noAi: true })) + expect(err).not.toContain("the default policy was applied") + }, 60_000) + + test("a PR that adds the policy itself is not told to rebase", async () => { + const root = await repo(undefined, ".altimate/review.yml") + const err = await stderrOf(() => reviewPullRequest({ cwd: root, head: "HEAD", noAi: true })) + expect(err).not.toContain("Rebase onto") + expect(err).toContain("this PR changes .altimate/review") + expect(err).toContain("the merge-base has no policy, so the default policy was applied") + expect(err).not.toContain("the base branch's policy was applied") + }, 60_000) +}) + +describe("review: the summary comment under an app token", () => { + const target = { token: "t", owner: "o", repo: "r", prNumber: 7 } + const env = buildEnvelope({ findings: [], tier: "lite", mode: "comment" }) + + /** `/user` refuses (an app installation token); comments are posted as `poster`. */ + function octo(poster: string, comments: Array<{ id: number; body: string; user?: { login: string } }>) { + const calls: string[] = [] + const o = { + paginate: async (fn: (p: unknown) => Promise, p: Record) => fn(p), + rest: { + issues: { + listComments: async () => comments, + createComment: async () => { + calls.push("create") + return { data: { id: 99, user: { login: poster } } } + }, + updateComment: async (p: { comment_id: number }) => { + calls.push(`update ${p.comment_id}`) + return { data: { id: p.comment_id, user: { login: poster } } } + }, + }, + users: { + getAuthenticated: async () => { + throw Object.assign(new Error("Resource not accessible by integration"), { status: 403 }) + }, + }, + pulls: { + listReviewComments: async () => [], + listReviews: async () => [], + listFiles: async () => [], + get: async () => ({ data: { head: { sha: "abc" } } }), + createReview: async () => ({ data: { id: 9 } }), + }, + }, + } + return { octo: o as any, calls } + } + + test("with the override set, the earlier summary is updated in place and nothing is said", async () => { + const { octo: o, calls } = octo("myapp[bot]", [{ id: 5, body: `${REVIEW_MARKER}\nold`, user: { login: "myapp[bot]" } }]) + const err = await stderrOf(() => postGitHubReview(env, { ...target, actions: true, botLogin: "myapp[bot]" }, o)) + expect(calls).toEqual(["update 5"]) + expect(err).not.toContain("ALTIMATE_REVIEW_BOT_LOGIN") + }) + + test("a marker planted by another account is neither adopted nor named", async () => { + const { octo: o, calls } = octo("myapp[bot]", [{ id: 5, body: `${REVIEW_MARKER}\nplanted`, user: { login: "mallory" } }]) + const err = await stderrOf(() => postGitHubReview(env, { ...target, actions: true }, o)) + expect(calls).toEqual(["create"]) + expect(err).not.toContain("ALTIMATE_REVIEW_BOT_LOGIN") + }) + + test("a first run with no earlier summary says nothing", async () => { + const { octo: o } = octo("myapp[bot]", []) + const err = await stderrOf(() => postGitHubReview(env, { ...target, actions: true }, o)) + expect(err).not.toContain("ALTIMATE_REVIEW_BOT_LOGIN") + }) + +}) + +describe("review: an empty lint-only run is not an all-clear", () => { + const finding = () => + makeFinding({ + severity: "suggestion", + category: "test_coverage", + title: "m: t", + body: "b", + file: "models/m.sql", + model: "m", + confidence: "high", + evidence: { tool: "test-coverage", result: {} }, + }) + + test("lint-only with no findings", () => { + const env = buildEnvelope({ findings: [], tier: "lite", mode: "comment" }) + env.summary.degraded = true + const md = renderSummary(env) + expect(md).toContain("Lint-only run") + expect(md).toContain("No lint findings in the changed dbt models.") + expect(md).not.toContain("🎉") + }) + + test("a full run with no findings posts no summary", () => { + // #1894: a clean full run is silent, so it never reads as a lint-only all-clear either. + const env = buildEnvelope({ findings: [], tier: "lite", mode: "comment" }) + env.summary.degraded = false + expect(renderSummary(env)).toBe("") + }) + + test("lint-only with findings lists them and says neither line", () => { + const env = buildEnvelope({ findings: [finding()], tier: "lite", mode: "comment" }) + env.summary.degraded = true + const md = renderSummary(env) + expect(md).not.toContain("No lint findings") + expect(md).not.toContain("No issues found") + }) +}) + +describe("server errors: the client message (#1848)", () => { + test("a message made only of stack frames falls back to the fixed text", () => { + const err = new Error("x") + err.message = " at a (/srv/app.js:1:1)\n at b (/srv/app.js:2:2)" + expect(clientMessage(err)).not.toContain("/srv/app.js") + }) + + test("non-Error throws do not crash it", () => { + for (const v of [undefined, null, 0, "", {}, [], Symbol("s"), () => 1]) { + expect(typeof clientMessage(v)).toBe("string") + expect(clientMessage(v).length).toBeGreaterThan(0) + } + }) + + test("a huge message is returned without throwing", () => { + const big = new Error("e".repeat(1_000_000)) + expect(() => clientMessage(big)).not.toThrow() + }) +}) + +describe("read-only guard: EXPLAIN options (#1778)", () => { + const reads = (sql: string, dialect: string) => classifyAndCheck(sql, dialect).queryType === "read" + + test("an EXPLAIN option list never hides a write or a hard-denied statement", () => { + for (const [sql, dialect] of [ + ["EXPLAIN (ANALYZE) DELETE FROM t", "postgres"], + ["EXPLAIN (ANALYZE, BUFFERS) DROP TABLE t", "postgres"], + ["EXPLAIN (FORMAT JSON) SELECT 1; DROP SCHEMA s", "postgres"], + ["EXPLAIN USING JSON TRUNCATE TABLE t", "snowflake"], + ["EXPLAIN FORMATTED INSERT INTO t SELECT 1", "databricks"], + ["EXPLAIN (ANALYZE) /* SELECT */ UPDATE t SET a = 1", "postgres"], + ] as const) { + expect(reads(sql, dialect)).toBe(false) + } + }) + + test("a DROP DATABASE behind EXPLAIN options is still blocked", () => { + expect(classifyAndCheck("EXPLAIN (ANALYZE) DROP DATABASE prod", "postgres").blocked).toBe(true) + }) + + test("unbalanced or empty option lists are not reads", () => { + for (const sql of ["EXPLAIN ( SELECT 1", "EXPLAIN () ", "EXPLAIN (ANALYZE", "EXPLAIN ((((((((((SELECT 1"]) { + expect(reads(sql, "postgres")).toBe(false) + } + }) +})