From b7cfc0426d60963a83f22a8f5c6053c7b7fce8e4 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Fri, 13 Nov 2026 16:30:43 +0530 Subject: [PATCH 01/31] feat: foundation for the dbt Power User tools Nine tool stubs exposed through `altimate tool run` (dbt_run_results, dbt_defer_state, dbt_map_relations, docs_share_comments, dbt_cost_estimate, dbt_health, dbt_sql_graph, dbt_docs_coverage, dbt_cte_profile), an exported `AltimateApi.apiRequest` that calls the backend with the stored credentials, and `dbtAdapterFor`, the one gate every adapter-backed tool goes through: it refuses read-only calls, other projects, and an adapter that did not start. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/api/client.ts | 18 ++ .../src/altimate/tool-cli/allow-list.ts | 18 ++ .../src/altimate/tools/dbt-adapter-access.ts | 100 ++++++++ .../src/altimate/tools/dbt-cost-estimate.ts | 17 ++ .../src/altimate/tools/dbt-cte-profile.ts | 17 ++ .../src/altimate/tools/dbt-defer-state.ts | 16 ++ .../src/altimate/tools/dbt-docs-coverage.ts | 17 ++ .../opencode/src/altimate/tools/dbt-health.ts | 16 ++ .../src/altimate/tools/dbt-map-relations.ts | 18 ++ .../src/altimate/tools/dbt-run-results.ts | 16 ++ .../src/altimate/tools/dbt-sql-graph.ts | 16 ++ .../src/altimate/tools/docs-share-comments.ts | 20 ++ .../test/altimate/dbt-adapter-access.test.ts | 221 ++++++++++++++++++ 13 files changed, 510 insertions(+) create mode 100644 packages/opencode/src/altimate/tools/dbt-adapter-access.ts create mode 100644 packages/opencode/src/altimate/tools/dbt-cost-estimate.ts create mode 100644 packages/opencode/src/altimate/tools/dbt-cte-profile.ts create mode 100644 packages/opencode/src/altimate/tools/dbt-defer-state.ts create mode 100644 packages/opencode/src/altimate/tools/dbt-docs-coverage.ts create mode 100644 packages/opencode/src/altimate/tools/dbt-health.ts create mode 100644 packages/opencode/src/altimate/tools/dbt-map-relations.ts create mode 100644 packages/opencode/src/altimate/tools/dbt-run-results.ts create mode 100644 packages/opencode/src/altimate/tools/dbt-sql-graph.ts create mode 100644 packages/opencode/src/altimate/tools/docs-share-comments.ts create mode 100644 packages/opencode/test/altimate/dbt-adapter-access.test.ts diff --git a/packages/opencode/src/altimate/api/client.ts b/packages/opencode/src/altimate/api/client.ts index 7a03aeb906..069a182b7a 100644 --- a/packages/opencode/src/altimate/api/client.ts +++ b/packages/opencode/src/altimate/api/client.ts @@ -347,6 +347,24 @@ export namespace AltimateApi { // altimate_change end } + /** + * Calls an Altimate API endpoint with the stored credentials (Bearer key and x-tenant headers) and + * returns the parsed JSON body. Endpoint functions in other files go through this. Fails with a + * message naming the credentials file when none are stored or they can't be read. + */ + export async function apiRequest(method: string, endpoint: string, body?: unknown): Promise { + let creds: AltimateCredentials + try { + creds = await getCredentials() + } catch (e) { + const p = credentialsPath() + if (!(await Filesystem.exists(p))) + throw new Error(`No Altimate credentials are stored: sign in to Altimate in altimate-code first (they are saved to ${p}).`) + throw new Error(`The Altimate credentials in ${p} can't be used: ${e instanceof Error ? e.message : String(e)}`) + } + return request(creds, method, endpoint, body) + } + export async function listDatamates(creds?: AltimateCredentials) { creds ??= await getCredentials() const data = await request(creds, "GET", "/datamates/") diff --git a/packages/opencode/src/altimate/tool-cli/allow-list.ts b/packages/opencode/src/altimate/tool-cli/allow-list.ts index 33b452d75c..0bb4f18473 100644 --- a/packages/opencode/src/altimate/tool-cli/allow-list.ts +++ b/packages/opencode/src/altimate/tool-cli/allow-list.ts @@ -35,10 +35,19 @@ import { AltimateCoreTestgenTool } from "../tools/altimate-core-testgen" import { AltimateCoreTrackLineageTool } from "../tools/altimate-core-track-lineage" import { AltimateCoreValidateTool } from "../tools/altimate-core-validate" import { DataDiffTool } from "../tools/data-diff" +import { DbtCostEstimateTool } from "../tools/dbt-cost-estimate" +import { DbtCteProfileTool } from "../tools/dbt-cte-profile" +import { DbtDeferStateTool } from "../tools/dbt-defer-state" +import { DbtDocsCoverageTool } from "../tools/dbt-docs-coverage" +import { DbtHealthTool } from "../tools/dbt-health" import { DbtLineageTool } from "../tools/dbt-lineage" import { DbtManifestTool } from "../tools/dbt-manifest" +import { DbtMapRelationsTool } from "../tools/dbt-map-relations" import { DbtProfilesTool } from "../tools/dbt-profiles" +import { DbtRunResultsTool } from "../tools/dbt-run-results" +import { DbtSqlGraphTool } from "../tools/dbt-sql-graph" import { DbtUnitTestGenTool } from "../tools/dbt-unit-test-gen" +import { DocsShareCommentsTool } from "../tools/docs-share-comments" import { FinopsAnalyzeCreditsTool } from "../tools/finops-analyze-credits" import { FinopsExpensiveQueriesTool } from "../tools/finops-expensive-queries" import { FinopsQueryHistoryTool } from "../tools/finops-query-history" @@ -106,10 +115,19 @@ export const EXPOSED: Record = { altimate_core_track_lineage: AltimateCoreTrackLineageTool, altimate_core_validate: AltimateCoreValidateTool, data_diff: DataDiffTool, + dbt_cost_estimate: DbtCostEstimateTool, + dbt_cte_profile: DbtCteProfileTool, + dbt_defer_state: DbtDeferStateTool, + dbt_docs_coverage: DbtDocsCoverageTool, + dbt_health: DbtHealthTool, dbt_lineage: DbtLineageTool, dbt_manifest: DbtManifestTool, + dbt_map_relations: DbtMapRelationsTool, dbt_profiles: DbtProfilesTool, + dbt_run_results: DbtRunResultsTool, + dbt_sql_graph: DbtSqlGraphTool, dbt_unit_test_gen: DbtUnitTestGenTool, + docs_share_comments: DocsShareCommentsTool, finops_analyze_credits: FinopsAnalyzeCreditsTool, finops_expensive_queries: FinopsExpensiveQueriesTool, finops_query_history: FinopsQueryHistoryTool, diff --git a/packages/opencode/src/altimate/tools/dbt-adapter-access.ts b/packages/opencode/src/altimate/tools/dbt-adapter-access.ts new file mode 100644 index 0000000000..a2711e35d1 --- /dev/null +++ b/packages/opencode/src/altimate/tools/dbt-adapter-access.ts @@ -0,0 +1,100 @@ +import fs from "fs" +import path from "path" +import type { Tool } from "../../tool/tool" +import { projectRoot } from "../native/connections/registry" + +/** Why a tool may not use the dbt adapter. */ +export type DbtAdapterRefusal = "read_only" | "other_project" | "no_project" | "not_started" | "not_loaded" + +/** The project's dbt adapter, or why this call may not use it (`reason` is a sentence for the user). */ +export type DbtAdapterAccess = + | { adapter: any; refusal?: undefined; reason?: undefined } + | { adapter?: undefined; refusal: DbtAdapterRefusal; reason: string } + +/** Test seams. */ +export const dbtAdapterAccessInternals = { + /** How long a call waits for the dbt adapter to start before it gives up; the start goes on for the next call. */ + adapterStartTimeoutMs: 120_000, +} + +/** + * The dbt adapter for a tool call, which every adapter-backed tool goes through. Starting the adapter + * runs dbt deps and writes target/, and compiling renders Jinja, which can run SQL: a read-only call + * (no write permission, or plan mode) never starts or uses it. Nor does a session in a dbt project the + * adapter isn't set up for. The wait for the adapter to start is bounded and follows the call's abort. + */ +export async function dbtAdapterFor(ctx: Pick): Promise { + const signal = ctx.abort + if (ctx.extra?.forceReadOnly === true || ctx.agent === "plan") + return { + refusal: "read_only", + reason: "this needs the dbt adapter, which a read-only call doesn't start: re-run with --allow-write", + } + try { + const { getDbtAdapter, getDbtProjectRoot } = await import("../native/connections/register") + // The import yields: a call cancelled meanwhile starts nothing. + signal.throwIfAborted() + const project = await sessionProject() + signal.throwIfAborted() + if (project?.other) { + return { + refusal: "other_project", + reason: project.root + ? `the dbt adapter is set up for ${project.root}, not ${project.other}` + : `the dbt adapter isn't set up for ${project.other}`, + } + } + let stop = () => {} + let timer: ReturnType | undefined + const waited = new Promise((_, reject) => { + stop = () => reject(signal.reason) + signal.addEventListener("abort", stop, { once: true }) + const seconds = dbtAdapterAccessInternals.adapterStartTimeoutMs / 1000 + timer = setTimeout( + () => reject(new Error(`the dbt adapter didn't start within ${seconds} s`)), + dbtAdapterAccessInternals.adapterStartTimeoutMs, + ) + }) + const adapter = await Promise.race([getDbtAdapter(), waited]).finally(() => { + signal.removeEventListener("abort", stop) + clearTimeout(timer) + }) + if (!adapter) { + // No adapter also when the project exists but the adapter failed to start: say which. + const root = await getDbtProjectRoot() + const found = !!root && fs.existsSync(path.join(root, "dbt_project.yml")) + return found + ? { refusal: "not_started", reason: "the dbt adapter didn't start" } + : { refusal: "no_project", reason: "no dbt project here" } + } + if (adapter.isInitialized?.() === false) return { refusal: "not_loaded", reason: "the dbt adapter didn't load the project" } + return { adapter } + } catch (e) { + if (signal.aborted) throw e + return { refusal: "not_started", reason: e instanceof Error ? e.message : String(e) } + } +} + +/** + * The adapter's project root and, when the session's directory is in another dbt project, that one + * (`other`, both links resolved). Undefined when the session's directory is in no dbt project: the + * adapter's own discovery (a dbt.json, or a walk up from the working directory) decides then. + */ +async function sessionProject(): Promise<{ root?: string; other?: string } | undefined> { + const { findProjectRoot } = await import("../../../../dbt-tools/src/config") + const found = findProjectRoot(projectRoot()) + if (!found) return undefined + const { getDbtProjectRoot } = await import("../native/connections/register") + const root = await getDbtProjectRoot() + const real = (p: string) => { + try { + return fs.realpathSync(p) + } catch { + return path.resolve(p) + } + } + const here = real(found) + // path.relative ignores case on win32. + if (!root) return { other: here } + return path.relative(real(root), here) ? { root: real(root), other: here } : { root } +} diff --git a/packages/opencode/src/altimate/tools/dbt-cost-estimate.ts b/packages/opencode/src/altimate/tools/dbt-cost-estimate.ts new file mode 100644 index 0000000000..6529d828c6 --- /dev/null +++ b/packages/opencode/src/altimate/tools/dbt-cost-estimate.ts @@ -0,0 +1,17 @@ +import z from "zod" +import { Tool } from "../../tool/tool" + +export const DbtCostEstimateTool = Tool.define("dbt_cost_estimate", { + description: "Estimate the bytes a dbt model or a SQL query would scan, from a warehouse dry run (BigQuery).", + parameters: z.object({ + model: z.string().optional().describe("Model name to compile and estimate"), + sql: z.string().optional().describe("SQL (may use Jinja) to compile and estimate"), + }), + async execute() { + return { + title: "dbt_cost_estimate: not implemented", + metadata: { success: false }, + output: "dbt_cost_estimate is not implemented in this build of altimate-code yet.", + } + }, +}) diff --git a/packages/opencode/src/altimate/tools/dbt-cte-profile.ts b/packages/opencode/src/altimate/tools/dbt-cte-profile.ts new file mode 100644 index 0000000000..e7a5bde647 --- /dev/null +++ b/packages/opencode/src/altimate/tools/dbt-cte-profile.ts @@ -0,0 +1,17 @@ +import z from "zod" +import { Tool } from "../../tool/tool" + +export const DbtCteProfileTool = Tool.define("dbt_cte_profile", { + description: "List a dbt model's CTEs, or time one CTE with a row-count query.", + parameters: z.object({ + model: z.string().describe("Model name"), + cte: z.string().optional().describe("CTE to time; without it, the CTE list is returned"), + }), + async execute() { + return { + title: "dbt_cte_profile: not implemented", + metadata: { success: false }, + output: "dbt_cte_profile is not implemented in this build of altimate-code yet.", + } + }, +}) diff --git a/packages/opencode/src/altimate/tools/dbt-defer-state.ts b/packages/opencode/src/altimate/tools/dbt-defer-state.ts new file mode 100644 index 0000000000..75cbfe19cf --- /dev/null +++ b/packages/opencode/src/altimate/tools/dbt-defer-state.ts @@ -0,0 +1,16 @@ +import z from "zod" +import { Tool } from "../../tool/tool" + +export const DbtDeferStateTool = Tool.define("dbt_defer_state", { + description: "dbt Power User's defer-to-production setting for a dbt project, and the profile's default target.", + parameters: z.object({ + project_dir: z.string().describe("dbt project folder"), + }), + async execute() { + return { + title: "dbt_defer_state: not implemented", + metadata: { success: false }, + output: "dbt_defer_state is not implemented in this build of altimate-code yet.", + } + }, +}) diff --git a/packages/opencode/src/altimate/tools/dbt-docs-coverage.ts b/packages/opencode/src/altimate/tools/dbt-docs-coverage.ts new file mode 100644 index 0000000000..c4e0ec42d3 --- /dev/null +++ b/packages/opencode/src/altimate/tools/dbt-docs-coverage.ts @@ -0,0 +1,17 @@ +import z from "zod" +import { Tool } from "../../tool/tool" + +export const DbtDocsCoverageTool = Tool.define("dbt_docs_coverage", { + description: "Documentation coverage of a dbt model: which output columns have a description, and whether the model has one.", + parameters: z.object({ + model: z.string().describe("Model name"), + manifest_path: z.string().optional().describe("manifest.json to read (default: the dbt project's target/manifest.json)"), + }), + async execute() { + return { + title: "dbt_docs_coverage: not implemented", + metadata: { success: false }, + output: "dbt_docs_coverage is not implemented in this build of altimate-code yet.", + } + }, +}) diff --git a/packages/opencode/src/altimate/tools/dbt-health.ts b/packages/opencode/src/altimate/tools/dbt-health.ts new file mode 100644 index 0000000000..a3f26352c4 --- /dev/null +++ b/packages/opencode/src/altimate/tools/dbt-health.ts @@ -0,0 +1,16 @@ +import z from "zod" +import { Tool } from "../../tool/tool" + +export const DbtHealthTool = Tool.define("dbt_health", { + description: "DataPilot project health insights for the dbt project.", + parameters: z.object({ + config_path: z.string().optional().describe("DataPilot config file to use"), + }), + async execute() { + return { + title: "dbt_health: not implemented", + metadata: { success: false }, + output: "dbt_health is not implemented in this build of altimate-code yet.", + } + }, +}) diff --git a/packages/opencode/src/altimate/tools/dbt-map-relations.ts b/packages/opencode/src/altimate/tools/dbt-map-relations.ts new file mode 100644 index 0000000000..1216d6b2ee --- /dev/null +++ b/packages/opencode/src/altimate/tools/dbt-map-relations.ts @@ -0,0 +1,18 @@ +import z from "zod" +import { Tool } from "../../tool/tool" + +export const DbtMapRelationsTool = Tool.define("dbt_map_relations", { + description: "Map each table a raw SQL query reads to the dbt ref() or source() for it, from the manifest.", + parameters: z.object({ + sql: z.string().describe("Raw SQL to map"), + dialect: z.string().optional().describe("SQL dialect of the query"), + manifest_path: z.string().optional().describe("manifest.json to match against (default: the dbt project's target/manifest.json)"), + }), + async execute() { + return { + title: "dbt_map_relations: not implemented", + metadata: { success: false }, + output: "dbt_map_relations is not implemented in this build of altimate-code yet.", + } + }, +}) diff --git a/packages/opencode/src/altimate/tools/dbt-run-results.ts b/packages/opencode/src/altimate/tools/dbt-run-results.ts new file mode 100644 index 0000000000..86e68a1668 --- /dev/null +++ b/packages/opencode/src/altimate/tools/dbt-run-results.ts @@ -0,0 +1,16 @@ +import z from "zod" +import { Tool } from "../../tool/tool" + +export const DbtRunResultsTool = Tool.define("dbt_run_results", { + description: "The latest dbt run's results from target/run_results.json: command, duration and each node's status.", + parameters: z.object({ + project_dir: z.string().optional().describe("dbt project folder (default: the dbt project found from the working directory)"), + }), + async execute() { + return { + title: "dbt_run_results: not implemented", + metadata: { success: false }, + output: "dbt_run_results is not implemented in this build of altimate-code yet.", + } + }, +}) diff --git a/packages/opencode/src/altimate/tools/dbt-sql-graph.ts b/packages/opencode/src/altimate/tools/dbt-sql-graph.ts new file mode 100644 index 0000000000..b2af1b0f18 --- /dev/null +++ b/packages/opencode/src/altimate/tools/dbt-sql-graph.ts @@ -0,0 +1,16 @@ +import z from "zod" +import { Tool } from "../../tool/tool" + +export const DbtSqlGraphTool = Tool.define("dbt_sql_graph", { + description: "A dbt model's SQL as a graph: its CTEs, joins and filters, and the edges between them.", + parameters: z.object({ + model: z.string().describe("Model name"), + }), + async execute() { + return { + title: "dbt_sql_graph: not implemented", + metadata: { success: false }, + output: "dbt_sql_graph is not implemented in this build of altimate-code yet.", + } + }, +}) diff --git a/packages/opencode/src/altimate/tools/docs-share-comments.ts b/packages/opencode/src/altimate/tools/docs-share-comments.ts new file mode 100644 index 0000000000..2c8c0a2ab3 --- /dev/null +++ b/packages/opencode/src/altimate/tools/docs-share-comments.ts @@ -0,0 +1,20 @@ +import z from "zod" +import { Tool } from "../../tool/tool" + +export const DocsShareCommentsTool = Tool.define("docs_share_comments", { + description: "Comment threads on shared dbt docs: list open threads, reply to one, or resolve one.", + parameters: z.object({ + action: z.enum(["list", "reply", "resolve"]).describe("What to do"), + project: z.string().optional().describe("dbt project name the shared docs belong to"), + share_id: z.number().int().optional().describe("Shared docs id"), + group_id: z.number().int().optional().describe("Comment thread id"), + text: z.string().optional().describe("Reply text"), + }), + async execute() { + return { + title: "docs_share_comments: not implemented", + metadata: { success: false }, + output: "docs_share_comments is not implemented in this build of altimate-code yet.", + } + }, +}) diff --git a/packages/opencode/test/altimate/dbt-adapter-access.test.ts b/packages/opencode/test/altimate/dbt-adapter-access.test.ts new file mode 100644 index 0000000000..b565e5a58a --- /dev/null +++ b/packages/opencode/test/altimate/dbt-adapter-access.test.ts @@ -0,0 +1,221 @@ +// The tools the dbt Power User features call: their allow-list entries and placeholder answers, the +// one gate every dbt-adapter-backed tool goes through, and the API helper for new endpoint files. The +// dbt adapter is replaced through `dbtAdapterInternals`, so these tests need no Python or dbt. +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test" +import { mkdtemp, rm, writeFile } from "node:fs/promises" +import { realpathSync } from "node:fs" +import os from "node:os" +import path from "node:path" +import { Effect } from "effect" +import type { Tool } from "@/tool/tool" +import { SessionID, MessageID } from "@/session/schema" +import { dbtAdapterInternals, resetDbtAdapter } from "@/altimate/native/connections/register" +import { dbtAdapterAccessInternals, dbtAdapterFor } from "@/altimate/tools/dbt-adapter-access" +import { EXPOSED, MCP_OPEN_WRITE_TOOLS, WRITE_TOOLS } from "@/altimate/tool-cli/allow-list" +import { AltimateApi } from "@/altimate/api/client" +import { Instance } from "@/project/instance" +import { disposeInstance } from "@/effect/instance-registry" +import { initTool } from "./tool-fixture" + +/** Each tool with the smallest arguments its parameters accept. */ +const MINIMAL_ARGS: Record> = { + dbt_run_results: {}, + dbt_defer_state: { project_dir: "." }, + dbt_map_relations: { sql: "select 1" }, + docs_share_comments: { action: "list" }, + dbt_cost_estimate: {}, + dbt_health: {}, + dbt_sql_graph: { model: "customers" }, + dbt_docs_coverage: { model: "customers" }, + dbt_cte_profile: { model: "customers" }, +} +const FEATURE_TOOLS = Object.keys(MINIMAL_ARGS) + +const ctx: Tool.Context = { + sessionID: SessionID.make("ses_dbt_adapter_access"), + messageID: MessageID.make("msg_dbt_adapter_access"), + agent: "analyst", + abort: new AbortController().signal, + messages: [], + metadata: () => Effect.void, + ask: () => Effect.void, +} + +let project: string + +function useConfig() { + dbtAdapterInternals.readConfig = async () => ({ + projectRoot: project, + pythonPath: "python3", + dbtIntegration: "corecommand", + queryLimit: 500, + }) +} + +beforeAll(async () => { + project = await mkdtemp(path.join(os.tmpdir(), "dbt-adapter-access-")) + await writeFile(path.join(project, "dbt_project.yml"), "name: jaffle_shop\n") +}) + +afterAll(async () => { + await rm(project, { recursive: true, force: true }) +}) + +beforeEach(() => resetDbtAdapter()) + +afterEach(() => { + resetDbtAdapter() + delete dbtAdapterInternals.readConfig + delete dbtAdapterInternals.create +}) + +describe("feature tools in the allow-list", () => { + test("all nine are exposed, in the map's alphabetical order, and none is a write tool", () => { + const ids = Object.keys(EXPOSED) + for (const id of FEATURE_TOOLS) { + expect(ids).toContain(id) + expect(WRITE_TOOLS.has(id)).toBe(false) + expect(MCP_OPEN_WRITE_TOOLS.has(id)).toBe(false) + } + const listed = ids.filter((id) => id.startsWith("dbt_") || id.startsWith("docs_")) + expect(listed).toEqual([...listed].sort()) + }) + + test("each placeholder answers that it isn't implemented, as a failure", async () => { + for (const id of FEATURE_TOOLS) { + const tool = await initTool(EXPOSED[id] as any) + expect(tool.id).toBe(id) + const result = await tool.execute(MINIMAL_ARGS[id], ctx) + expect(result.title).toBe(`${id}: not implemented`) + expect(result.metadata.success).toBe(false) + expect(result.output).toContain(id) + } + }) +}) + +describe("dbtAdapterFor", () => { + let created: number + beforeEach(() => { + created = 0 + useConfig() + dbtAdapterInternals.create = async () => { + created += 1 + return { isInitialized: () => true, dispose: async () => {} } + } + }) + + test("refuses a read-only call and never creates the adapter", async () => { + const access = await dbtAdapterFor({ ...ctx, extra: { forceReadOnly: true } }) + expect(access.adapter).toBeUndefined() + expect(access.refusal).toBe("read_only") + expect(access.reason).toContain("--allow-write") + expect(created).toBe(0) + }) + + test("refuses a plan-mode call", async () => { + const access = await dbtAdapterFor({ ...ctx, agent: "plan" }) + expect(access.refusal).toBe("read_only") + expect(created).toBe(0) + }) + + test("returns the adapter where writes are allowed", async () => { + const access = await dbtAdapterFor(ctx) + expect(access.refusal).toBeUndefined() + expect(access.adapter?.isInitialized()).toBe(true) + expect(created).toBe(1) + }) + + test("says when the adapter didn't load the project", async () => { + dbtAdapterInternals.create = async () => ({ isInitialized: () => false, dispose: async () => {} }) + const access = await dbtAdapterFor(ctx) + expect(access).toEqual({ refusal: "not_loaded", reason: "the dbt adapter didn't load the project" }) + }) + + test("says there is no dbt project when the config finds none", async () => { + dbtAdapterInternals.readConfig = async () => null + const access = await dbtAdapterFor(ctx) + expect(access).toEqual({ refusal: "no_project", reason: "no dbt project here" }) + }) + + test("says when the adapter doesn't start in time", async () => { + dbtAdapterInternals.create = () => new Promise(() => {}) + const saved = dbtAdapterAccessInternals.adapterStartTimeoutMs + dbtAdapterAccessInternals.adapterStartTimeoutMs = 20 + try { + const access = await dbtAdapterFor(ctx) + expect(access).toEqual({ refusal: "not_started", reason: "the dbt adapter didn't start within 0.02 s" }) + } finally { + dbtAdapterAccessInternals.adapterStartTimeoutMs = saved + } + }) + + test("a cancelled call throws rather than answering", async () => { + const controller = new AbortController() + controller.abort() + await expect(dbtAdapterFor({ ...ctx, abort: controller.signal })).rejects.toThrow() + expect(created).toBe(0) + }) + + test("a session in a dbt project the adapter isn't set up for says so", async () => { + dbtAdapterInternals.readConfig = async () => null + try { + const access = await Instance.provide({ directory: project, fn: () => dbtAdapterFor(ctx) }) + expect(access).toEqual({ + refusal: "other_project", + reason: `the dbt adapter isn't set up for ${realpathSync(project)}`, + }) + expect(created).toBe(0) + } finally { + await disposeInstance(project) + } + }) +}) + +describe("AltimateApi.apiRequest", () => { + let home: string + let saved: string | undefined + beforeEach(async () => { + home = await mkdtemp(path.join(os.tmpdir(), "altimate-api-home-")) + saved = process.env.OPENCODE_TEST_HOME + process.env.OPENCODE_TEST_HOME = home + }) + afterEach(async () => { + if (saved === undefined) delete process.env.OPENCODE_TEST_HOME + else process.env.OPENCODE_TEST_HOME = saved + await rm(home, { recursive: true, force: true }) + }) + + test("fails with a clear message when no credentials are stored", async () => { + await expect(AltimateApi.apiRequest("GET", "/dbt/v1/x")).rejects.toThrow( + `No Altimate credentials are stored: sign in to Altimate in altimate-code first (they are saved to ${path.join(home, ".altimate", "altimate.json")}).`, + ) + }) + + test("sends the stored key and tenant and returns the JSON body", async () => { + await Bun.write( + path.join(home, ".altimate", "altimate.json"), + JSON.stringify({ altimateUrl: "https://api.example.test/", altimateInstanceName: "acme", altimateApiKey: "k1" }), + ) + const original = globalThis.fetch + const seen: { url: string; init: RequestInit }[] = [] + globalThis.fetch = (async (url: string, init: RequestInit) => { + seen.push({ url, init }) + return new Response(JSON.stringify({ ok: 1 }), { status: 200 }) + }) as unknown as typeof fetch + try { + expect(await AltimateApi.apiRequest("POST", "/dbt/v1/x", { a: 1 })).toEqual({ ok: 1 }) + expect(seen[0].url).toBe("https://api.example.test/dbt/v1/x") + const headers = seen[0].init.headers as Record + expect(headers.Authorization).toBe("Bearer k1") + expect(headers["x-tenant"]).toBe("acme") + expect(seen[0].init.body).toBe(JSON.stringify({ a: 1 })) + } finally { + globalThis.fetch = original + } + }) + + test("names the file when the stored credentials can't be read", async () => { + await Bun.write(path.join(home, ".altimate", "altimate.json"), "{not json") + await expect(AltimateApi.apiRequest("GET", "/dbt/v1/x")).rejects.toThrow("can't be used") + }) +}) From 21d0494cfbb1c87a2b1b3ba6e347f4f1be149856 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Fri, 13 Nov 2026 17:01:49 +0530 Subject: [PATCH 02/31] fix: harden the dbt Power User tool foundation Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/api/client.ts | 4 +- .../src/altimate/tools/dbt-adapter-access.ts | 3 +- .../src/altimate/tools/dbt-cost-estimate.ts | 2 +- .../src/altimate/tools/dbt-cte-profile.ts | 2 +- .../src/altimate/tools/dbt-defer-state.ts | 2 +- .../src/altimate/tools/dbt-docs-coverage.ts | 10 ++-- .../opencode/src/altimate/tools/dbt-health.ts | 2 +- .../src/altimate/tools/dbt-map-relations.ts | 7 ++- .../src/altimate/tools/dbt-run-results.ts | 7 ++- .../src/altimate/tools/dbt-sql-graph.ts | 2 +- .../src/altimate/tools/docs-share-comments.ts | 2 +- .../test/altimate/dbt-adapter-access.test.ts | 52 ++++++++++++++++++- 12 files changed, 78 insertions(+), 17 deletions(-) diff --git a/packages/opencode/src/altimate/api/client.ts b/packages/opencode/src/altimate/api/client.ts index 069a182b7a..cb53c0ec7b 100644 --- a/packages/opencode/src/altimate/api/client.ts +++ b/packages/opencode/src/altimate/api/client.ts @@ -359,7 +359,9 @@ export namespace AltimateApi { } catch (e) { const p = credentialsPath() if (!(await Filesystem.exists(p))) - throw new Error(`No Altimate credentials are stored: sign in to Altimate in altimate-code first (they are saved to ${p}).`) + throw new Error( + `No Altimate credentials are stored: sign in to Altimate in altimate-code first (they are saved to ${p}).`, + ) throw new Error(`The Altimate credentials in ${p} can't be used: ${e instanceof Error ? e.message : String(e)}`) } return request(creds, method, endpoint, body) diff --git a/packages/opencode/src/altimate/tools/dbt-adapter-access.ts b/packages/opencode/src/altimate/tools/dbt-adapter-access.ts index a2711e35d1..d73dd7e9c5 100644 --- a/packages/opencode/src/altimate/tools/dbt-adapter-access.ts +++ b/packages/opencode/src/altimate/tools/dbt-adapter-access.ts @@ -67,7 +67,8 @@ export async function dbtAdapterFor(ctx: Pick { expect(tool.id).toBe(id) const result = await tool.execute(MINIMAL_ARGS[id], ctx) expect(result.title).toBe(`${id}: not implemented`) - expect(result.metadata.success).toBe(false) + expect(result.metadata).toEqual({ success: false, error: "not implemented", truncated: false }) expect(result.output).toContain(id) } }) @@ -149,6 +149,30 @@ describe("dbtAdapterFor", () => { } }) + test("says the adapter didn't start when the project exists but creating it fails", async () => { + dbtAdapterInternals.create = async () => { + created += 1 + throw new Error("dbt-integration missing") + } + const access = await dbtAdapterFor(ctx) + expect(access).toEqual({ refusal: "not_started", reason: "the dbt adapter didn't start" }) + expect(created).toBe(1) + }) + + test("a call cancelled while the adapter starts throws and stops waiting", async () => { + let entered = () => {} + const starting = new Promise((resolve) => (entered = resolve)) + dbtAdapterInternals.create = () => { + entered() + return new Promise(() => {}) + } + const controller = new AbortController() + const pending = dbtAdapterFor({ ...ctx, abort: controller.signal }) + await starting + controller.abort(new Error("cancelled")) + await expect(pending).rejects.toThrow("cancelled") + }) + test("a cancelled call throws rather than answering", async () => { const controller = new AbortController() controller.abort() @@ -169,6 +193,28 @@ describe("dbtAdapterFor", () => { await disposeInstance(project) } }) + + test("a session in another dbt project than the adapter's says which", async () => { + const other = await mkdtemp(path.join(os.tmpdir(), "dbt-adapter-other-")) + await writeFile(path.join(other, "dbt_project.yml"), "name: other\n") + dbtAdapterInternals.readConfig = async () => ({ + projectRoot: other, + pythonPath: "python3", + dbtIntegration: "corecommand", + queryLimit: 500, + }) + try { + const access = await Instance.provide({ directory: project, fn: () => dbtAdapterFor(ctx) }) + expect(access).toEqual({ + refusal: "other_project", + reason: `the dbt adapter is set up for ${realpathSync(other)}, not ${realpathSync(project)}`, + }) + expect(created).toBe(0) + } finally { + await disposeInstance(project) + await rm(other, { recursive: true, force: true }) + } + }) }) describe("AltimateApi.apiRequest", () => { @@ -216,6 +262,8 @@ describe("AltimateApi.apiRequest", () => { test("names the file when the stored credentials can't be read", async () => { await Bun.write(path.join(home, ".altimate", "altimate.json"), "{not json") - await expect(AltimateApi.apiRequest("GET", "/dbt/v1/x")).rejects.toThrow("can't be used") + await expect(AltimateApi.apiRequest("GET", "/dbt/v1/x")).rejects.toThrow( + `The Altimate credentials in ${path.join(home, ".altimate", "altimate.json")} can't be used`, + ) }) }) From 911061dd304db80d9a57b956d81d956656564d6f Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Fri, 13 Nov 2026 17:03:11 +0530 Subject: [PATCH 03/31] feat: dbt_defer_state reads the Power User defer setting and the profile target Reads dbt.deferConfigPerProject from .vscode/settings.json (comments allowed), returns whether defer is on, favor state, the local state directory, and the profile's default target and output names. Remote mode reports that it is not supported yet instead of guessing a download request. Co-Authored-By: Claude Sonnet 5.5 --- .../src/altimate/tools/dbt-defer-state.ts | 203 +++++++++++++++++- .../test/altimate/dbt-defer-state.test.ts | 100 +++++++++ 2 files changed, 296 insertions(+), 7 deletions(-) create mode 100644 packages/opencode/test/altimate/dbt-defer-state.test.ts diff --git a/packages/opencode/src/altimate/tools/dbt-defer-state.ts b/packages/opencode/src/altimate/tools/dbt-defer-state.ts index 75cbfe19cf..65604e9a01 100644 --- a/packages/opencode/src/altimate/tools/dbt-defer-state.ts +++ b/packages/opencode/src/altimate/tools/dbt-defer-state.ts @@ -1,16 +1,205 @@ import z from "zod" +import fs from "fs" +import os from "os" +import path from "path" +import { parse as parseJsonc, type ParseError } from "jsonc-parser" import { Tool } from "../../tool/tool" +// The Power User setting this tool reads: `dbt.deferConfigPerProject`, keyed by the dbt project's path +// relative to its workspace folder. +const SETTING = "dbt.deferConfigPerProject" + +export interface DeferSetting { + deferToProduction?: boolean + favorState?: boolean + manifestPathForDeferral?: string + manifestPathType?: string + dbtCoreIntegrationId?: string | number +} + +export interface DeferStateResult { + enabled: boolean + favorState: boolean + /** "local" | "remote" | "none" (no entry for this project) */ + mode: "local" | "remote" | "none" + /** Directory holding the manifest to defer to; set only when it can be used. */ + stateDir?: string + /** Why defer is configured on but cannot be applied. */ + reason?: string + /** The settings key that matched, relative to the workspace folder. */ + settingsKey?: string + settingsFile?: string + profile?: string + defaultTarget?: string + targets: string[] +} + +/** Expand `${env:NAME}` and `${workspaceFolder}`; an unset variable is left as written. */ +function expandVariables(value: string, workspaceFolder: string): string { + return value + .replace(/\$\{env:(.*?)\}/g, (match, name: string) => process.env[name] ?? match) + .replace(/\$\{workspaceFolder\}/g, () => workspaceFolder) +} + +function readSettings(file: string): Record | undefined { + let text: string + try { + text = fs.readFileSync(file, "utf-8") + } catch { + return undefined + } + const errors: ParseError[] = [] + // .vscode/settings.json allows comments and trailing commas. + const parsed = parseJsonc(text, errors, { allowTrailingComma: true }) + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return undefined + return parsed as Record +} + +/** + * Find the entry for the project. The workspace folder is the nearest ancestor of the project (or the + * project itself) whose `.vscode/settings.json` has an entry under the project's relative path. + */ +export function findDeferSetting(projectDir: string, workspaceDir?: string) { + const start = path.resolve(projectDir) + const candidates: string[] = [] + if (workspaceDir) candidates.push(path.resolve(workspaceDir)) + else { + for (let dir = start; ; dir = path.dirname(dir)) { + candidates.push(dir) + if (path.dirname(dir) === dir) break + } + } + for (const folder of candidates) { + const file = path.join(folder, ".vscode", "settings.json") + const settings = readSettings(file) + const perProject = settings?.[SETTING] + if (!perProject || typeof perProject !== "object") continue + const key = path.relative(folder, start) + const entry = (perProject as Record)[key] + if (entry && typeof entry === "object") { + return { entry: entry as DeferSetting, key, file, folder } + } + } + return undefined +} + +function profilesFile(projectDir: string): string | undefined { + const dirs = [process.env.DBT_PROFILES_DIR, projectDir, path.join(os.homedir(), ".dbt")] + for (const dir of dirs) { + if (!dir) continue + const file = path.join(dir, "profiles.yml") + if (fs.existsSync(file)) return file + } + return undefined +} + +async function parseYaml(text: string): Promise { + const mod = await import("yaml") + return (mod.default ?? mod).parse(text) +} + +/** The project's profile name, that profile's default `target` and its output names. */ +export async function readProfileTargets(projectDir: string) { + const out: { profile?: string; defaultTarget?: string; targets: string[] } = { targets: [] } + try { + const project = await parseYaml(fs.readFileSync(path.join(projectDir, "dbt_project.yml"), "utf-8")) + if (typeof project?.profile === "string") out.profile = project.profile + } catch { + return out + } + if (!out.profile) return out + const file = profilesFile(projectDir) + if (!file) return out + try { + const profiles = await parseYaml(fs.readFileSync(file, "utf-8")) + const profile = profiles?.[out.profile] + if (profile && typeof profile === "object") { + if (typeof profile.target === "string") out.defaultTarget = profile.target + if (profile.outputs && typeof profile.outputs === "object") out.targets = Object.keys(profile.outputs) + } + } catch { + // An unreadable profiles.yml leaves the target unknown. + } + return out +} + +function isDirectory(dir: string): boolean { + try { + return fs.statSync(dir).isDirectory() + } catch { + return false + } +} + +export async function resolveDeferState(projectDir: string, workspaceDir?: string): Promise { + const root = path.resolve(projectDir) + const targets = await readProfileTargets(root) + const base: DeferStateResult = { enabled: false, favorState: false, mode: "none", ...targets } + const found = findDeferSetting(root, workspaceDir) + if (!found) return base + + const { entry } = found + const result: DeferStateResult = { + ...base, + settingsKey: found.key, + settingsFile: found.file, + favorState: entry.favorState === true, + } + if (entry.deferToProduction !== true) return result + + // Power User reads the type as "local" or "remote"; an entry without one is local. + const remote = entry.manifestPathType === "remote" + result.mode = remote ? "remote" : "local" + if (remote) { + // The request that downloads the manifest is not implemented, so remote mode cannot supply a state dir. + return { ...result, reason: "Remote defer mode is not supported yet: download the manifest and use a local path." } + } + + const raw = entry.manifestPathForDeferral + if (typeof raw !== "string" || raw.trim() === "") { + return { ...result, reason: "manifestPathForDeferral is not set." } + } + const expanded = expandVariables(raw, found.folder) + const stateDir = path.isAbsolute(expanded) ? expanded : path.resolve(root, expanded) + if (!isDirectory(stateDir)) { + return { ...result, reason: `manifestPathForDeferral is not a directory: ${stateDir}` } + } + return { ...result, enabled: true, stateDir } +} + export const DbtDeferStateTool = Tool.define("dbt_defer_state", { - description: "dbt Power User's defer-to-production setting for a dbt project, and the profile's default target.", + description: + "Read the dbt Power User defer setting for a dbt project (`dbt.deferConfigPerProject` in .vscode/settings.json) and the project's profile target. Returns whether defer is on, whether to favor state, the state directory to pass as `dbt --defer --state `, and the profile's default target and target names. Read-only.", parameters: z.object({ - project_dir: z.string().describe("dbt project folder"), + project_dir: z.string().describe("The dbt project directory (the folder holding dbt_project.yml)"), + workspace_dir: z + .string() + .optional() + .describe("The workspace folder that holds .vscode/settings.json (default: the nearest ancestor of project_dir whose settings have an entry for the project)"), }), - async execute() { - return { - title: "dbt_defer_state: not implemented", - metadata: { success: false }, - output: "dbt_defer_state is not implemented in this build of altimate-code yet.", + async execute(args) { + try { + const result = await resolveDeferState(args.project_dir, args.workspace_dir) + const lines = [ + `defer: ${result.enabled ? "on" : "off"}${result.favorState ? " (favor state)" : ""}`, + `mode: ${result.mode}`, + ] + if (result.stateDir) lines.push(`state dir: ${result.stateDir}`) + if (result.reason) lines.push(`note: ${result.reason}`) + if (result.defaultTarget) lines.push(`default target: ${result.defaultTarget}`) + if (result.targets.length) lines.push(`targets: ${result.targets.join(", ")}`) + return { + title: `dbt Defer: ${result.enabled ? "on" : "off"}`, + metadata: { success: true, error: undefined as string | undefined, ...result }, + output: lines.join("\n"), + } + } catch (e) { + const msg = e instanceof Error ? e.message : String(e) + return { + title: "dbt Defer: ERROR", + metadata: { success: false, error: msg as string | undefined, enabled: false }, + output: `Failed: ${msg}`, + } } }, }) diff --git a/packages/opencode/test/altimate/dbt-defer-state.test.ts b/packages/opencode/test/altimate/dbt-defer-state.test.ts new file mode 100644 index 0000000000..ce20432320 --- /dev/null +++ b/packages/opencode/test/altimate/dbt-defer-state.test.ts @@ -0,0 +1,100 @@ +import { describe, test, expect, beforeEach, afterEach } from "bun:test" +import fs from "fs" +import os from "os" +import path from "path" +import { resolveDeferState, findDeferSetting } from "../../src/altimate/tools/dbt-defer-state" + +describe("dbt_defer_state", () => { + let root: string + let savedProfilesDir: string | undefined + + const write = (rel: string, content: string) => { + const file = path.join(root, rel) + fs.mkdirSync(path.dirname(file), { recursive: true }) + fs.writeFileSync(file, content) + } + const settings = (perProject: Record) => + write(".vscode/settings.json", `// comment\n{\n "dbt.deferConfigPerProject": ${JSON.stringify(perProject)},\n}\n`) + + beforeEach(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), "defer-state-")) + savedProfilesDir = process.env.DBT_PROFILES_DIR + process.env.DBT_PROFILES_DIR = path.join(root, "profiles") + write("profiles/profiles.yml", "shop:\n target: dev\n outputs:\n dev:\n type: duckdb\n prod:\n type: duckdb\n") + write("analytics/dbt_project.yml", "name: shop\nprofile: shop\n") + fs.mkdirSync(path.join(root, "prod-state"), { recursive: true }) + }) + + afterEach(() => { + if (savedProfilesDir === undefined) delete process.env.DBT_PROFILES_DIR + else process.env.DBT_PROFILES_DIR = savedProfilesDir + fs.rmSync(root, { recursive: true, force: true }) + }) + + test("local mode returns the state dir, favor state and the profile's targets", async () => { + settings({ analytics: { deferToProduction: true, favorState: true, manifestPathForDeferral: "${workspaceFolder}/prod-state" } }) + const result = await resolveDeferState(path.join(root, "analytics")) + expect(result).toMatchObject({ + enabled: true, + favorState: true, + mode: "local", + stateDir: path.join(root, "prod-state"), + settingsKey: "analytics", + defaultTarget: "dev", + targets: ["dev", "prod"], + profile: "shop", + }) + }) + + test("defer off leaves the state dir unset", async () => { + settings({ analytics: { deferToProduction: false, manifestPathForDeferral: "${workspaceFolder}/prod-state" } }) + const result = await resolveDeferState(path.join(root, "analytics")) + expect(result.enabled).toBe(false) + expect(result.stateDir).toBeUndefined() + expect(result.defaultTarget).toBe("dev") + }) + + test("a project without an entry reports mode none", async () => { + settings({ other: { deferToProduction: true, manifestPathForDeferral: "x" } }) + const result = await resolveDeferState(path.join(root, "analytics")) + expect(result).toMatchObject({ enabled: false, mode: "none" }) + }) + + test("a project at the workspace root uses the empty key", async () => { + write("dbt_project.yml", "name: shop\nprofile: shop\n") + settings({ "": { deferToProduction: true, manifestPathForDeferral: "prod-state" } }) + const result = await resolveDeferState(root) + expect(result.enabled).toBe(true) + expect(result.stateDir).toBe(path.join(root, "prod-state")) + }) + + test("a state path that is not a directory is reported, not used", async () => { + write("prod-state-file", "x") + settings({ analytics: { deferToProduction: true, manifestPathForDeferral: "${workspaceFolder}/prod-state-file" } }) + const result = await resolveDeferState(path.join(root, "analytics")) + expect(result.enabled).toBe(false) + expect(result.stateDir).toBeUndefined() + expect(result.reason).toContain("not a directory") + }) + + test("remote mode is reported as unsupported with no state dir", async () => { + settings({ analytics: { deferToProduction: true, manifestPathType: "remote", dbtCoreIntegrationId: 7 } }) + const result = await resolveDeferState(path.join(root, "analytics")) + expect(result).toMatchObject({ enabled: false, mode: "remote" }) + expect(result.stateDir).toBeUndefined() + expect(result.reason).toContain("Remote defer mode") + }) + + test("missing settings file and unreadable profiles give defaults", async () => { + fs.rmSync(path.join(root, ".vscode"), { recursive: true, force: true }) + fs.rmSync(path.join(root, "profiles"), { recursive: true, force: true }) + const result = await resolveDeferState(path.join(root, "analytics")) + expect(result).toMatchObject({ enabled: false, mode: "none", targets: [] }) + expect(result.defaultTarget).toBeUndefined() + }) + + test("settings with comments and trailing commas parse", () => { + settings({ analytics: { deferToProduction: true } }) + expect(findDeferSetting(path.join(root, "analytics"))?.key).toBe("analytics") + }) +}) From 983309aca3c6a7469126b62d449f7764a6a7ca55 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Fri, 13 Nov 2026 17:25:12 +0530 Subject: [PATCH 04/31] fix(tool): dbt_defer_state returns the configured directory while defer is off and rejects unreadable settings The state directory is resolved whether or not defer is on, so a session can switch it on; settings that do not parse and unknown manifest types no longer enable defer; a state directory needs a manifest.json; profile and target written as env_var() are resolved with the shared profiles helpers. Co-Authored-By: Claude Sonnet 5.5 --- .../native/connections/dbt-profiles.ts | 4 +- .../src/altimate/tools/dbt-defer-state.ts | 50 ++++++----- .../test/altimate/dbt-adapter-access.test.ts | 4 +- .../test/altimate/dbt-defer-state.test.ts | 86 ++++++++++++++++++- 4 files changed, 115 insertions(+), 29 deletions(-) diff --git a/packages/opencode/src/altimate/native/connections/dbt-profiles.ts b/packages/opencode/src/altimate/native/connections/dbt-profiles.ts index e36b5bd0f6..3a92a6403f 100644 --- a/packages/opencode/src/altimate/native/connections/dbt-profiles.ts +++ b/packages/opencode/src/altimate/native/connections/dbt-profiles.ts @@ -53,7 +53,7 @@ const KEY_MAP: Record = { } /** Resolve Jinja {{ env_var('NAME') }} and {{ env_var('NAME', 'default') }} patterns. */ -function resolveEnvVars(value: unknown): unknown { +export function resolveEnvVars(value: unknown): unknown { if (typeof value !== "string") return value return value.replace( /\{\{\s*env_var\s*\(\s*'([^']+)'\s*(?:,\s*'([^']*)'\s*)?\)\s*\}\}/g, @@ -102,7 +102,7 @@ function mapConfig(dbtType: string, dbtConfig: Record): Connect * 3. Project-local profiles.yml (in dbt project root) * 4. ~/.dbt/profiles.yml (default) */ -function resolveProfilesPath(explicitPath?: string, projectDir?: string): string { +export function resolveProfilesPath(explicitPath?: string, projectDir?: string): string { if (explicitPath) return explicitPath const envDir = process.env.DBT_PROFILES_DIR diff --git a/packages/opencode/src/altimate/tools/dbt-defer-state.ts b/packages/opencode/src/altimate/tools/dbt-defer-state.ts index 65604e9a01..b6b0084a74 100644 --- a/packages/opencode/src/altimate/tools/dbt-defer-state.ts +++ b/packages/opencode/src/altimate/tools/dbt-defer-state.ts @@ -1,9 +1,9 @@ import z from "zod" import fs from "fs" -import os from "os" import path from "path" import { parse as parseJsonc, type ParseError } from "jsonc-parser" import { Tool } from "../../tool/tool" +import { resolveEnvVars, resolveProfilesPath } from "../native/connections/dbt-profiles" // The Power User setting this tool reads: `dbt.deferConfigPerProject`, keyed by the dbt project's path // relative to its workspace folder. @@ -20,11 +20,11 @@ export interface DeferSetting { export interface DeferStateResult { enabled: boolean favorState: boolean - /** "local" | "remote" | "none" (no entry for this project) */ + /** "local" | "remote" | "none" (no entry for this project, or a manifest type this tool does not know) */ mode: "local" | "remote" | "none" - /** Directory holding the manifest to defer to; set only when it can be used. */ + /** Directory holding the manifest to defer to; set whenever the configured local one can be used, also while defer is off. */ stateDir?: string - /** Why defer is configured on but cannot be applied. */ + /** Why the configured defer cannot be used: no usable state directory, remote mode, an unknown manifest type. */ reason?: string /** The settings key that matched, relative to the workspace folder. */ settingsKey?: string @@ -51,6 +51,8 @@ function readSettings(file: string): Record | undefined { const errors: ParseError[] = [] // .vscode/settings.json allows comments and trailing commas. const parsed = parseJsonc(text, errors, { allowTrailingComma: true }) + // A file that does not parse cannot be trusted to say defer is on. + if (errors.length > 0) return undefined if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return undefined return parsed as Record } @@ -84,13 +86,8 @@ export function findDeferSetting(projectDir: string, workspaceDir?: string) { } function profilesFile(projectDir: string): string | undefined { - const dirs = [process.env.DBT_PROFILES_DIR, projectDir, path.join(os.homedir(), ".dbt")] - for (const dir of dirs) { - if (!dir) continue - const file = path.join(dir, "profiles.yml") - if (fs.existsSync(file)) return file - } - return undefined + const file = resolveProfilesPath(undefined, projectDir) + return fs.existsSync(file) ? file : undefined } async function parseYaml(text: string): Promise { @@ -103,7 +100,8 @@ export async function readProfileTargets(projectDir: string) { const out: { profile?: string; defaultTarget?: string; targets: string[] } = { targets: [] } try { const project = await parseYaml(fs.readFileSync(path.join(projectDir, "dbt_project.yml"), "utf-8")) - if (typeof project?.profile === "string") out.profile = project.profile + const profile = resolveEnvVars(project?.profile) + if (typeof profile === "string" && profile !== "") out.profile = profile } catch { return out } @@ -114,7 +112,8 @@ export async function readProfileTargets(projectDir: string) { const profiles = await parseYaml(fs.readFileSync(file, "utf-8")) const profile = profiles?.[out.profile] if (profile && typeof profile === "object") { - if (typeof profile.target === "string") out.defaultTarget = profile.target + const target = resolveEnvVars(profile.target) + if (typeof target === "string" && target !== "") out.defaultTarget = target if (profile.outputs && typeof profile.outputs === "object") out.targets = Object.keys(profile.outputs) } } catch { @@ -145,16 +144,20 @@ export async function resolveDeferState(projectDir: string, workspaceDir?: strin settingsFile: found.file, favorState: entry.favorState === true, } - if (entry.deferToProduction !== true) return result + const wanted = entry.deferToProduction === true - // Power User reads the type as "local" or "remote"; an entry without one is local. - const remote = entry.manifestPathType === "remote" - result.mode = remote ? "remote" : "local" - if (remote) { + // Power User writes "local" or "remote"; an entry without a type is local. Anything else is not understood. + const type = entry.manifestPathType + if (type !== undefined && type !== "" && type !== "local" && type !== "remote") { + return { ...result, reason: `Unknown manifestPathType "${String(type)}": expected "local" or "remote".` } + } + if (type === "remote") { // The request that downloads the manifest is not implemented, so remote mode cannot supply a state dir. - return { ...result, reason: "Remote defer mode is not supported yet: download the manifest and use a local path." } + return { ...result, mode: "remote", reason: "Remote defer mode is not supported yet: download the manifest and use a local path." } } + result.mode = "local" + // The directory is resolved whether or not defer is on, so a session can still switch it on. const raw = entry.manifestPathForDeferral if (typeof raw !== "string" || raw.trim() === "") { return { ...result, reason: "manifestPathForDeferral is not set." } @@ -164,12 +167,15 @@ export async function resolveDeferState(projectDir: string, workspaceDir?: strin if (!isDirectory(stateDir)) { return { ...result, reason: `manifestPathForDeferral is not a directory: ${stateDir}` } } - return { ...result, enabled: true, stateDir } + if (!fs.existsSync(path.join(stateDir, "manifest.json"))) { + return { ...result, reason: `No manifest.json in manifestPathForDeferral: ${stateDir}` } + } + return { ...result, enabled: wanted, stateDir } } export const DbtDeferStateTool = Tool.define("dbt_defer_state", { description: - "Read the dbt Power User defer setting for a dbt project (`dbt.deferConfigPerProject` in .vscode/settings.json) and the project's profile target. Returns whether defer is on, whether to favor state, the state directory to pass as `dbt --defer --state `, and the profile's default target and target names. Read-only.", + "Read the dbt Power User defer setting for a dbt project (`dbt.deferConfigPerProject` in .vscode/settings.json) and the project's profile target. Returns whether defer is on, whether to favor state, the state directory to pass as `dbt --defer --state ` (use it only when `enabled` is true), and the profile's default target and target names. Read-only.", parameters: z.object({ project_dir: z.string().describe("The dbt project directory (the folder holding dbt_project.yml)"), workspace_dir: z @@ -184,7 +190,7 @@ export const DbtDeferStateTool = Tool.define("dbt_defer_state", { `defer: ${result.enabled ? "on" : "off"}${result.favorState ? " (favor state)" : ""}`, `mode: ${result.mode}`, ] - if (result.stateDir) lines.push(`state dir: ${result.stateDir}`) + if (result.stateDir) lines.push(`state dir${result.enabled ? "" : " (not used: defer is off)"}: ${result.stateDir}`) if (result.reason) lines.push(`note: ${result.reason}`) if (result.defaultTarget) lines.push(`default target: ${result.defaultTarget}`) if (result.targets.length) lines.push(`targets: ${result.targets.join(", ")}`) diff --git a/packages/opencode/test/altimate/dbt-adapter-access.test.ts b/packages/opencode/test/altimate/dbt-adapter-access.test.ts index b565e5a58a..5fa1c1ebdc 100644 --- a/packages/opencode/test/altimate/dbt-adapter-access.test.ts +++ b/packages/opencode/test/altimate/dbt-adapter-access.test.ts @@ -30,6 +30,8 @@ const MINIMAL_ARGS: Record> = { dbt_cte_profile: { model: "customers" }, } const FEATURE_TOOLS = Object.keys(MINIMAL_ARGS) +// Tools that have their own implementation and test: they no longer answer as placeholders. +const IMPLEMENTED = new Set(["dbt_defer_state"]) const ctx: Tool.Context = { sessionID: SessionID.make("ses_dbt_adapter_access"), @@ -82,7 +84,7 @@ describe("feature tools in the allow-list", () => { }) test("each placeholder answers that it isn't implemented, as a failure", async () => { - for (const id of FEATURE_TOOLS) { + for (const id of FEATURE_TOOLS.filter((id) => !IMPLEMENTED.has(id))) { const tool = await initTool(EXPOSED[id] as any) expect(tool.id).toBe(id) const result = await tool.execute(MINIMAL_ARGS[id], ctx) diff --git a/packages/opencode/test/altimate/dbt-defer-state.test.ts b/packages/opencode/test/altimate/dbt-defer-state.test.ts index ce20432320..50aeb632a0 100644 --- a/packages/opencode/test/altimate/dbt-defer-state.test.ts +++ b/packages/opencode/test/altimate/dbt-defer-state.test.ts @@ -2,7 +2,11 @@ import { describe, test, expect, beforeEach, afterEach } from "bun:test" import fs from "fs" import os from "os" import path from "path" -import { resolveDeferState, findDeferSetting } from "../../src/altimate/tools/dbt-defer-state" +import { Effect } from "effect" +import type { Tool } from "../../src/tool/tool" +import { SessionID, MessageID } from "../../src/session/schema" +import { DbtDeferStateTool, resolveDeferState, findDeferSetting } from "../../src/altimate/tools/dbt-defer-state" +import { initTool } from "./tool-fixture" describe("dbt_defer_state", () => { let root: string @@ -22,7 +26,7 @@ describe("dbt_defer_state", () => { process.env.DBT_PROFILES_DIR = path.join(root, "profiles") write("profiles/profiles.yml", "shop:\n target: dev\n outputs:\n dev:\n type: duckdb\n prod:\n type: duckdb\n") write("analytics/dbt_project.yml", "name: shop\nprofile: shop\n") - fs.mkdirSync(path.join(root, "prod-state"), { recursive: true }) + write("prod-state/manifest.json", "{}") }) afterEach(() => { @@ -46,11 +50,12 @@ describe("dbt_defer_state", () => { }) }) - test("defer off leaves the state dir unset", async () => { + test("defer off still returns the configured state dir, so a session can switch it on", async () => { settings({ analytics: { deferToProduction: false, manifestPathForDeferral: "${workspaceFolder}/prod-state" } }) const result = await resolveDeferState(path.join(root, "analytics")) expect(result.enabled).toBe(false) - expect(result.stateDir).toBeUndefined() + expect(result.mode).toBe("local") + expect(result.stateDir).toBe(path.join(root, "prod-state")) expect(result.defaultTarget).toBe("dev") }) @@ -77,6 +82,60 @@ describe("dbt_defer_state", () => { expect(result.reason).toContain("not a directory") }) + test("a state dir without manifest.json is reported, not used", async () => { + fs.mkdirSync(path.join(root, "empty-state")) + settings({ analytics: { deferToProduction: true, manifestPathForDeferral: "${workspaceFolder}/empty-state" } }) + const result = await resolveDeferState(path.join(root, "analytics")) + expect(result.enabled).toBe(false) + expect(result.stateDir).toBeUndefined() + expect(result.reason).toContain("manifest.json") + }) + + test("an unknown manifest type does not enable defer", async () => { + settings({ analytics: { deferToProduction: true, manifestPathType: "typo", manifestPathForDeferral: "${workspaceFolder}/prod-state" } }) + const result = await resolveDeferState(path.join(root, "analytics")) + expect(result).toMatchObject({ enabled: false, mode: "none" }) + expect(result.stateDir).toBeUndefined() + expect(result.reason).toContain("typo") + }) + + test("a settings file that does not parse is not trusted", async () => { + write(".vscode/settings.json", '{ "dbt.deferConfigPerProject": { "analytics": { "deferToProduction": true, "manifestPathForDeferral": "${workspaceFolder}/prod-state" } } } oops') + const result = await resolveDeferState(path.join(root, "analytics")) + expect(result).toMatchObject({ enabled: false, mode: "none" }) + }) + + test("${env:NAME} in the state path is expanded, and an unset one is left as written", async () => { + process.env.DEFER_TEST_STATE = path.join(root, "prod-state") + try { + settings({ analytics: { deferToProduction: true, manifestPathForDeferral: "${env:DEFER_TEST_STATE}" } }) + expect((await resolveDeferState(path.join(root, "analytics"))).stateDir).toBe(path.join(root, "prod-state")) + } finally { + delete process.env.DEFER_TEST_STATE + } + settings({ analytics: { deferToProduction: true, manifestPathForDeferral: "${env:DEFER_TEST_UNSET}" } }) + expect((await resolveDeferState(path.join(root, "analytics"))).reason).toContain("${env:DEFER_TEST_UNSET}") + }) + + test("an explicit workspace folder and an absolute state path are used", async () => { + write("elsewhere/.vscode/settings.json", JSON.stringify({ "dbt.deferConfigPerProject": { "../analytics": { deferToProduction: true, manifestPathForDeferral: path.join(root, "prod-state") } } })) + const result = await resolveDeferState(path.join(root, "analytics"), path.join(root, "elsewhere")) + expect(result).toMatchObject({ enabled: true, stateDir: path.join(root, "prod-state"), settingsKey: "../analytics" }) + }) + + test("a project or target written as env_var() is resolved, with its default", async () => { + write("analytics/dbt_project.yml", "name: shop\nprofile: \"{{ env_var('DEFER_TEST_PROFILE', 'shop') }}\"\n") + write("profiles/profiles.yml", "shop:\n target: \"{{ env_var('DEFER_TEST_TARGET', 'dev') }}\"\n outputs:\n dev:\n type: duckdb\n qa:\n type: duckdb\n") + process.env.DEFER_TEST_TARGET = "qa" + try { + const result = await resolveDeferState(path.join(root, "analytics")) + expect(result).toMatchObject({ profile: "shop", defaultTarget: "qa", targets: ["dev", "qa"] }) + } finally { + delete process.env.DEFER_TEST_TARGET + } + expect((await resolveDeferState(path.join(root, "analytics"))).defaultTarget).toBe("dev") + }) + test("remote mode is reported as unsupported with no state dir", async () => { settings({ analytics: { deferToProduction: true, manifestPathType: "remote", dbtCoreIntegrationId: 7 } }) const result = await resolveDeferState(path.join(root, "analytics")) @@ -97,4 +156,23 @@ describe("dbt_defer_state", () => { settings({ analytics: { deferToProduction: true } }) expect(findDeferSetting(path.join(root, "analytics"))?.key).toBe("analytics") }) + + test("the tool answers with the result as metadata and a readable report", async () => { + settings({ analytics: { deferToProduction: true, favorState: true, manifestPathForDeferral: "${workspaceFolder}/prod-state" } }) + const ctx: Tool.Context = { + sessionID: SessionID.make("ses_defer_state"), + messageID: MessageID.make("msg_defer_state"), + agent: "analyst", + abort: new AbortController().signal, + messages: [], + metadata: () => Effect.void, + ask: () => Effect.void, + } + const tool = await initTool(DbtDeferStateTool as any) + const ok = await tool.execute({ project_dir: path.join(root, "analytics") }, ctx) + expect(ok.title).toBe("dbt Defer: on") + expect(ok.metadata).toMatchObject({ success: true, enabled: true, favorState: true, stateDir: path.join(root, "prod-state"), defaultTarget: "dev", targets: ["dev", "prod"] }) + expect(ok.output).toContain(`state dir: ${path.join(root, "prod-state")}`) + expect(ok.output).toContain("defer: on (favor state)") + }) }) From f64f065df680df3671356359eb7ba1cff7cfcd42 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Fri, 13 Nov 2026 21:54:17 +0530 Subject: [PATCH 05/31] fix(tool): dbt_defer_state expands the workspace folder to the project like Power User, needs a manifest file, and stops at a settings file it cannot read Co-Authored-By: Claude Sonnet 5.5 --- .../src/altimate/tools/dbt-defer-state.ts | 31 ++++++++---- .../test/altimate/dbt-defer-state.test.ts | 47 ++++++++++++++----- 2 files changed, 59 insertions(+), 19 deletions(-) diff --git a/packages/opencode/src/altimate/tools/dbt-defer-state.ts b/packages/opencode/src/altimate/tools/dbt-defer-state.ts index b6b0084a74..a59da0f483 100644 --- a/packages/opencode/src/altimate/tools/dbt-defer-state.ts +++ b/packages/opencode/src/altimate/tools/dbt-defer-state.ts @@ -41,25 +41,29 @@ function expandVariables(value: string, workspaceFolder: string): string { .replace(/\$\{workspaceFolder\}/g, () => workspaceFolder) } -function readSettings(file: string): Record | undefined { +const UNREADABLE = Symbol("unreadable settings") + +/** The parsed settings; undefined when there is no file, UNREADABLE when there is one that cannot be trusted. */ +function readSettings(file: string): Record | typeof UNREADABLE | undefined { let text: string try { text = fs.readFileSync(file, "utf-8") - } catch { - return undefined + } catch (err) { + return (err as NodeJS.ErrnoException).code === "ENOENT" || (err as NodeJS.ErrnoException).code === "ENOTDIR" ? undefined : UNREADABLE } const errors: ParseError[] = [] // .vscode/settings.json allows comments and trailing commas. const parsed = parseJsonc(text, errors, { allowTrailingComma: true }) // A file that does not parse cannot be trusted to say defer is on. - if (errors.length > 0) return undefined - if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return undefined + if (errors.length > 0) return UNREADABLE + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return UNREADABLE return parsed as Record } /** * Find the entry for the project. The workspace folder is the nearest ancestor of the project (or the - * project itself) whose `.vscode/settings.json` has an entry under the project's relative path. + * project itself) whose `.vscode/settings.json` has an entry under the project's relative path. A settings + * file that cannot be read or parsed ends the search. */ export function findDeferSetting(projectDir: string, workspaceDir?: string) { const start = path.resolve(projectDir) @@ -74,6 +78,8 @@ export function findDeferSetting(projectDir: string, workspaceDir?: string) { for (const folder of candidates) { const file = path.join(folder, ".vscode", "settings.json") const settings = readSettings(file) + // The nearest settings file that cannot be read ends the search: an outer folder's entry must not stand in for it. + if (settings === UNREADABLE) return undefined const perProject = settings?.[SETTING] if (!perProject || typeof perProject !== "object") continue const key = path.relative(folder, start) @@ -122,6 +128,14 @@ export async function readProfileTargets(projectDir: string) { return out } +function isFile(file: string): boolean { + try { + return fs.statSync(file).isFile() + } catch { + return false + } +} + function isDirectory(dir: string): boolean { try { return fs.statSync(dir).isDirectory() @@ -162,12 +176,13 @@ export async function resolveDeferState(projectDir: string, workspaceDir?: strin if (typeof raw !== "string" || raw.trim() === "") { return { ...result, reason: "manifestPathForDeferral is not set." } } - const expanded = expandVariables(raw, found.folder) + // Power User expands ${workspaceFolder} to the dbt project's own folder. + const expanded = expandVariables(raw, root) const stateDir = path.isAbsolute(expanded) ? expanded : path.resolve(root, expanded) if (!isDirectory(stateDir)) { return { ...result, reason: `manifestPathForDeferral is not a directory: ${stateDir}` } } - if (!fs.existsSync(path.join(stateDir, "manifest.json"))) { + if (!isFile(path.join(stateDir, "manifest.json"))) { return { ...result, reason: `No manifest.json in manifestPathForDeferral: ${stateDir}` } } return { ...result, enabled: wanted, stateDir } diff --git a/packages/opencode/test/altimate/dbt-defer-state.test.ts b/packages/opencode/test/altimate/dbt-defer-state.test.ts index 50aeb632a0..9ef258ae13 100644 --- a/packages/opencode/test/altimate/dbt-defer-state.test.ts +++ b/packages/opencode/test/altimate/dbt-defer-state.test.ts @@ -26,7 +26,7 @@ describe("dbt_defer_state", () => { process.env.DBT_PROFILES_DIR = path.join(root, "profiles") write("profiles/profiles.yml", "shop:\n target: dev\n outputs:\n dev:\n type: duckdb\n prod:\n type: duckdb\n") write("analytics/dbt_project.yml", "name: shop\nprofile: shop\n") - write("prod-state/manifest.json", "{}") + write("analytics/prod-state/manifest.json", "{}") }) afterEach(() => { @@ -42,7 +42,7 @@ describe("dbt_defer_state", () => { enabled: true, favorState: true, mode: "local", - stateDir: path.join(root, "prod-state"), + stateDir: path.join(root, "analytics", "prod-state"), settingsKey: "analytics", defaultTarget: "dev", targets: ["dev", "prod"], @@ -55,7 +55,7 @@ describe("dbt_defer_state", () => { const result = await resolveDeferState(path.join(root, "analytics")) expect(result.enabled).toBe(false) expect(result.mode).toBe("local") - expect(result.stateDir).toBe(path.join(root, "prod-state")) + expect(result.stateDir).toBe(path.join(root, "analytics", "prod-state")) expect(result.defaultTarget).toBe("dev") }) @@ -67,6 +67,7 @@ describe("dbt_defer_state", () => { test("a project at the workspace root uses the empty key", async () => { write("dbt_project.yml", "name: shop\nprofile: shop\n") + write("prod-state/manifest.json", "{}") settings({ "": { deferToProduction: true, manifestPathForDeferral: "prod-state" } }) const result = await resolveDeferState(root) expect(result.enabled).toBe(true) @@ -74,7 +75,7 @@ describe("dbt_defer_state", () => { }) test("a state path that is not a directory is reported, not used", async () => { - write("prod-state-file", "x") + write("analytics/prod-state-file", "x") settings({ analytics: { deferToProduction: true, manifestPathForDeferral: "${workspaceFolder}/prod-state-file" } }) const result = await resolveDeferState(path.join(root, "analytics")) expect(result.enabled).toBe(false) @@ -83,7 +84,7 @@ describe("dbt_defer_state", () => { }) test("a state dir without manifest.json is reported, not used", async () => { - fs.mkdirSync(path.join(root, "empty-state")) + fs.mkdirSync(path.join(root, "analytics", "empty-state")) settings({ analytics: { deferToProduction: true, manifestPathForDeferral: "${workspaceFolder}/empty-state" } }) const result = await resolveDeferState(path.join(root, "analytics")) expect(result.enabled).toBe(false) @@ -91,6 +92,30 @@ describe("dbt_defer_state", () => { expect(result.reason).toContain("manifest.json") }) + test("a manifest.json that is a directory is not a usable state", async () => { + fs.mkdirSync(path.join(root, "analytics", "dir-state", "manifest.json"), { recursive: true }) + settings({ analytics: { deferToProduction: true, manifestPathForDeferral: "${workspaceFolder}/dir-state" } }) + const result = await resolveDeferState(path.join(root, "analytics")) + expect(result.enabled).toBe(false) + expect(result.stateDir).toBeUndefined() + expect(result.reason).toContain("manifest.json") + }) + + test("${workspaceFolder} is the dbt project's own folder, as in Power User", async () => { + fs.mkdirSync(path.join(root, "prod-state"), { recursive: true }) + fs.writeFileSync(path.join(root, "prod-state", "manifest.json"), "{}") + settings({ analytics: { deferToProduction: true, manifestPathForDeferral: "${workspaceFolder}/prod-state" } }) + const result = await resolveDeferState(path.join(root, "analytics")) + expect(result.stateDir).toBe(path.join(root, "analytics", "prod-state")) + }) + + test("a settings file that does not parse ends the search; an outer folder's entry does not stand in", async () => { + write("analytics/.vscode/settings.json", '{ "dbt.deferConfigPerProject": oops') + settings({ analytics: { deferToProduction: true, manifestPathForDeferral: "${workspaceFolder}/prod-state" } }) + const result = await resolveDeferState(path.join(root, "analytics")) + expect(result).toMatchObject({ enabled: false, mode: "none" }) + }) + test("an unknown manifest type does not enable defer", async () => { settings({ analytics: { deferToProduction: true, manifestPathType: "typo", manifestPathForDeferral: "${workspaceFolder}/prod-state" } }) const result = await resolveDeferState(path.join(root, "analytics")) @@ -106,10 +131,10 @@ describe("dbt_defer_state", () => { }) test("${env:NAME} in the state path is expanded, and an unset one is left as written", async () => { - process.env.DEFER_TEST_STATE = path.join(root, "prod-state") + process.env.DEFER_TEST_STATE = path.join(root, "analytics", "prod-state") try { settings({ analytics: { deferToProduction: true, manifestPathForDeferral: "${env:DEFER_TEST_STATE}" } }) - expect((await resolveDeferState(path.join(root, "analytics"))).stateDir).toBe(path.join(root, "prod-state")) + expect((await resolveDeferState(path.join(root, "analytics"))).stateDir).toBe(path.join(root, "analytics", "prod-state")) } finally { delete process.env.DEFER_TEST_STATE } @@ -118,9 +143,9 @@ describe("dbt_defer_state", () => { }) test("an explicit workspace folder and an absolute state path are used", async () => { - write("elsewhere/.vscode/settings.json", JSON.stringify({ "dbt.deferConfigPerProject": { "../analytics": { deferToProduction: true, manifestPathForDeferral: path.join(root, "prod-state") } } })) + write("elsewhere/.vscode/settings.json", JSON.stringify({ "dbt.deferConfigPerProject": { "../analytics": { deferToProduction: true, manifestPathForDeferral: path.join(root, "analytics", "prod-state") } } })) const result = await resolveDeferState(path.join(root, "analytics"), path.join(root, "elsewhere")) - expect(result).toMatchObject({ enabled: true, stateDir: path.join(root, "prod-state"), settingsKey: "../analytics" }) + expect(result).toMatchObject({ enabled: true, stateDir: path.join(root, "analytics", "prod-state"), settingsKey: "../analytics" }) }) test("a project or target written as env_var() is resolved, with its default", async () => { @@ -171,8 +196,8 @@ describe("dbt_defer_state", () => { const tool = await initTool(DbtDeferStateTool as any) const ok = await tool.execute({ project_dir: path.join(root, "analytics") }, ctx) expect(ok.title).toBe("dbt Defer: on") - expect(ok.metadata).toMatchObject({ success: true, enabled: true, favorState: true, stateDir: path.join(root, "prod-state"), defaultTarget: "dev", targets: ["dev", "prod"] }) - expect(ok.output).toContain(`state dir: ${path.join(root, "prod-state")}`) + expect(ok.metadata).toMatchObject({ success: true, enabled: true, favorState: true, stateDir: path.join(root, "analytics", "prod-state"), defaultTarget: "dev", targets: ["dev", "prod"] }) + expect(ok.output).toContain(`state dir: ${path.join(root, "analytics", "prod-state")}`) expect(ok.output).toContain("defer: on (favor state)") }) }) From 83c671174b70b9f0323adcd4b48f276356261990 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Sat, 14 Nov 2026 07:57:24 +0530 Subject: [PATCH 06/31] fix(tool): dbt_defer_state treats an empty settings file as empty and matches the project key through symlinks Co-Authored-By: Claude Sonnet 5.5 --- .../src/altimate/tools/dbt-defer-state.ts | 13 +++++++++++-- .../test/altimate/dbt-defer-state.test.ts | 18 ++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/tools/dbt-defer-state.ts b/packages/opencode/src/altimate/tools/dbt-defer-state.ts index a59da0f483..15433ba6ca 100644 --- a/packages/opencode/src/altimate/tools/dbt-defer-state.ts +++ b/packages/opencode/src/altimate/tools/dbt-defer-state.ts @@ -51,6 +51,8 @@ function readSettings(file: string): Record | typeof UNREADABLE } catch (err) { return (err as NodeJS.ErrnoException).code === "ENOENT" || (err as NodeJS.ErrnoException).code === "ENOTDIR" ? undefined : UNREADABLE } + // An empty or whitespace-only file is a settings file with nothing in it. + if (text.trim() === "") return {} const errors: ParseError[] = [] // .vscode/settings.json allows comments and trailing commas. const parsed = parseJsonc(text, errors, { allowTrailingComma: true }) @@ -66,9 +68,16 @@ function readSettings(file: string): Record | typeof UNREADABLE * file that cannot be read or parsed ends the search. */ export function findDeferSetting(projectDir: string, workspaceDir?: string) { - const start = path.resolve(projectDir) + const real = (p: string) => { + try { + return fs.realpathSync(path.resolve(p)) + } catch { + return path.resolve(p) + } + } + const start = real(projectDir) const candidates: string[] = [] - if (workspaceDir) candidates.push(path.resolve(workspaceDir)) + if (workspaceDir) candidates.push(real(workspaceDir)) else { for (let dir = start; ; dir = path.dirname(dir)) { candidates.push(dir) diff --git a/packages/opencode/test/altimate/dbt-defer-state.test.ts b/packages/opencode/test/altimate/dbt-defer-state.test.ts index 9ef258ae13..9d46c909b1 100644 --- a/packages/opencode/test/altimate/dbt-defer-state.test.ts +++ b/packages/opencode/test/altimate/dbt-defer-state.test.ts @@ -177,6 +177,24 @@ describe("dbt_defer_state", () => { expect(result.defaultTarget).toBeUndefined() }) + test("an empty settings file in the project does not hide the workspace entry", () => { + settings({ analytics: { deferToProduction: true } }) + fs.mkdirSync(path.join(root, "analytics", ".vscode"), { recursive: true }) + fs.writeFileSync(path.join(root, "analytics", ".vscode", "settings.json"), "") + expect(findDeferSetting(path.join(root, "analytics"))?.key).toBe("analytics") + }) + + test("a symlinked workspace path still finds the project's entry", () => { + settings({ analytics: { deferToProduction: true } }) + const link = path.join(root, "..", path.basename(root) + "-link") + fs.symlinkSync(root, link) + try { + expect(findDeferSetting(path.join(root, "analytics"), link)?.key).toBe("analytics") + } finally { + fs.rmSync(link) + } + }) + test("settings with comments and trailing commas parse", () => { settings({ analytics: { deferToProduction: true } }) expect(findDeferSetting(path.join(root, "analytics"))?.key).toBe("analytics") From 510e7be768d42b002703c2033f235a759478564f Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Sat, 14 Nov 2026 09:11:04 +0530 Subject: [PATCH 07/31] fix(tool): dbt_defer_state tries the project and workspace paths as given before following symlinks Co-Authored-By: Claude Sonnet 5.5 --- .../src/altimate/tools/dbt-defer-state.ts | 48 +++++++++++-------- .../test/altimate/dbt-defer-state.test.ts | 14 ++++++ 2 files changed, 43 insertions(+), 19 deletions(-) diff --git a/packages/opencode/src/altimate/tools/dbt-defer-state.ts b/packages/opencode/src/altimate/tools/dbt-defer-state.ts index 15433ba6ca..b1b494ff22 100644 --- a/packages/opencode/src/altimate/tools/dbt-defer-state.ts +++ b/packages/opencode/src/altimate/tools/dbt-defer-state.ts @@ -75,27 +75,37 @@ export function findDeferSetting(projectDir: string, workspaceDir?: string) { return path.resolve(p) } } - const start = real(projectDir) - const candidates: string[] = [] - if (workspaceDir) candidates.push(real(workspaceDir)) - else { - for (let dir = start; ; dir = path.dirname(dir)) { - candidates.push(dir) - if (path.dirname(dir) === dir) break + const search = (start: string, workspace?: string) => { + const candidates: string[] = [] + if (workspace) candidates.push(workspace) + else { + for (let dir = start; ; dir = path.dirname(dir)) { + candidates.push(dir) + if (path.dirname(dir) === dir) break + } } - } - for (const folder of candidates) { - const file = path.join(folder, ".vscode", "settings.json") - const settings = readSettings(file) - // The nearest settings file that cannot be read ends the search: an outer folder's entry must not stand in for it. - if (settings === UNREADABLE) return undefined - const perProject = settings?.[SETTING] - if (!perProject || typeof perProject !== "object") continue - const key = path.relative(folder, start) - const entry = (perProject as Record)[key] - if (entry && typeof entry === "object") { - return { entry: entry as DeferSetting, key, file, folder } + for (const folder of candidates) { + const file = path.join(folder, ".vscode", "settings.json") + const settings = readSettings(file) + // The nearest settings file that cannot be read ends the search: an outer folder's entry must not stand in for it. + if (settings === UNREADABLE) return UNREADABLE + const perProject = settings?.[SETTING] + if (!perProject || typeof perProject !== "object") continue + const key = path.relative(folder, start) + const entry = (perProject as Record)[key] + if (entry && typeof entry === "object") { + return { entry: entry as DeferSetting, key, file, folder } + } } + return undefined + } + // The paths as given first, as VS Code builds the key; then with symlinks followed, for a workspace reached through a link. + const lexical = [path.resolve(projectDir), workspaceDir ? path.resolve(workspaceDir) : undefined] as const + const resolved = [real(projectDir), workspaceDir ? real(workspaceDir) : undefined] as const + for (const [start, workspace] of lexical[0] === resolved[0] && lexical[1] === resolved[1] ? [lexical] : [lexical, resolved]) { + const found = search(start, workspace) + if (found === UNREADABLE) return undefined + if (found) return found } return undefined } diff --git a/packages/opencode/test/altimate/dbt-defer-state.test.ts b/packages/opencode/test/altimate/dbt-defer-state.test.ts index 9d46c909b1..c27ab7ecea 100644 --- a/packages/opencode/test/altimate/dbt-defer-state.test.ts +++ b/packages/opencode/test/altimate/dbt-defer-state.test.ts @@ -195,6 +195,20 @@ describe("dbt_defer_state", () => { } }) + test("a symlinked project folder still finds the entry under its path in the workspace", () => { + settings({ analytics: { deferToProduction: true } }) + const outside = fs.mkdtempSync(path.join(path.dirname(root), "ext-")) + fs.rmSync(path.join(root, "analytics"), { recursive: true, force: true }) + fs.symlinkSync(outside, path.join(root, "analytics")) + try { + expect(findDeferSetting(path.join(root, "analytics"), root)?.key).toBe("analytics") + expect(findDeferSetting(path.join(root, "analytics"))?.key).toBe("analytics") + } finally { + fs.rmSync(path.join(root, "analytics")) + fs.rmSync(outside, { recursive: true, force: true }) + } + }) + test("settings with comments and trailing commas parse", () => { settings({ analytics: { deferToProduction: true } }) expect(findDeferSetting(path.join(root, "analytics"))?.key).toBe("analytics") From 77c574875ea0d2b55c35cacad1e83edf1b20b312 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Sat, 14 Nov 2026 11:11:15 +0530 Subject: [PATCH 08/31] fix(tool): dbt_defer_state reaches the real-path settings when a file above the symlink cannot be parsed Co-Authored-By: Claude Sonnet 5.5 --- .../src/altimate/tools/dbt-defer-state.ts | 9 +++++++-- .../test/altimate/dbt-defer-state.test.ts | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/tools/dbt-defer-state.ts b/packages/opencode/src/altimate/tools/dbt-defer-state.ts index b1b494ff22..8b503f64dd 100644 --- a/packages/opencode/src/altimate/tools/dbt-defer-state.ts +++ b/packages/opencode/src/altimate/tools/dbt-defer-state.ts @@ -102,9 +102,14 @@ export function findDeferSetting(projectDir: string, workspaceDir?: string) { // The paths as given first, as VS Code builds the key; then with symlinks followed, for a workspace reached through a link. const lexical = [path.resolve(projectDir), workspaceDir ? path.resolve(workspaceDir) : undefined] as const const resolved = [real(projectDir), workspaceDir ? real(workspaceDir) : undefined] as const - for (const [start, workspace] of lexical[0] === resolved[0] && lexical[1] === resolved[1] ? [lexical] : [lexical, resolved]) { + const passes = lexical[0] === resolved[0] && lexical[1] === resolved[1] ? [lexical] : [lexical, resolved] + for (const [i, [start, workspace]] of passes.entries()) { const found = search(start, workspace) - if (found === UNREADABLE) return undefined + // An unreadable file ends the search of its own pass; the pass over the real paths may still reach a readable one. + if (found === UNREADABLE) { + if (i === passes.length - 1) return undefined + continue + } if (found) return found } return undefined diff --git a/packages/opencode/test/altimate/dbt-defer-state.test.ts b/packages/opencode/test/altimate/dbt-defer-state.test.ts index c27ab7ecea..ae16a18308 100644 --- a/packages/opencode/test/altimate/dbt-defer-state.test.ts +++ b/packages/opencode/test/altimate/dbt-defer-state.test.ts @@ -209,6 +209,24 @@ describe("dbt_defer_state", () => { } }) + test("an unparseable settings file above a symlinked project does not hide the entry on the real path", () => { + const real = fs.mkdtempSync(path.join(path.dirname(root), "real-")) + fs.mkdirSync(path.join(real, "analytics")) + fs.mkdirSync(path.join(real, ".vscode")) + fs.writeFileSync(path.join(real, ".vscode", "settings.json"), JSON.stringify({ "dbt.deferConfigPerProject": { analytics: { deferToProduction: true } } })) + const holder = fs.mkdtempSync(path.join(path.dirname(root), "hold-")) + fs.mkdirSync(path.join(holder, ".vscode")) + fs.writeFileSync(path.join(holder, ".vscode", "settings.json"), "{ not json") + const link = path.join(holder, "analytics") + fs.symlinkSync(path.join(real, "analytics"), link) + try { + expect(findDeferSetting(link)?.entry.deferToProduction).toBe(true) + } finally { + fs.rmSync(real, { recursive: true, force: true }) + fs.rmSync(holder, { recursive: true, force: true }) + } + }) + test("settings with comments and trailing commas parse", () => { settings({ analytics: { deferToProduction: true } }) expect(findDeferSetting(path.join(root, "analytics"))?.key).toBe("analytics") From 046acac48e4bf4be6b289ba655f9c73c1c6d01a8 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Sun, 15 Nov 2026 22:12:51 +0530 Subject: [PATCH 09/31] fix(tool): dbt_defer_state handles comment-only settings and symlinked project keys, env_var accepts double quotes, cancelled read-only calls cancel Co-Authored-By: Claude Sonnet 5.5 --- .../native/connections/dbt-profiles.ts | 4 +- .../src/altimate/tools/dbt-adapter-access.ts | 4 +- .../src/altimate/tools/dbt-defer-state.ts | 10 ++++- .../src/altimate/tools/dbt-lineage.ts | 27 +----------- .../test/altimate/dbt-adapter-access.test.ts | 8 ++++ .../test/altimate/dbt-defer-state.test.ts | 41 +++++++++++++++++-- 6 files changed, 60 insertions(+), 34 deletions(-) diff --git a/packages/opencode/src/altimate/native/connections/dbt-profiles.ts b/packages/opencode/src/altimate/native/connections/dbt-profiles.ts index 3a92a6403f..8f2d883c97 100644 --- a/packages/opencode/src/altimate/native/connections/dbt-profiles.ts +++ b/packages/opencode/src/altimate/native/connections/dbt-profiles.ts @@ -56,8 +56,8 @@ const KEY_MAP: Record = { export function resolveEnvVars(value: unknown): unknown { if (typeof value !== "string") return value return value.replace( - /\{\{\s*env_var\s*\(\s*'([^']+)'\s*(?:,\s*'([^']*)'\s*)?\)\s*\}\}/g, - (_match, envName: string, defaultValue?: string) => { + /\{\{\s*env_var\s*\(\s*(['"])([^'"]+)\1\s*(?:,\s*(['"])([^'"]*)\3\s*)?\)\s*\}\}/g, + (_match, _q1: string, envName: string, _q2?: string, defaultValue?: string) => { return process.env[envName] ?? defaultValue ?? "" }, ) diff --git a/packages/opencode/src/altimate/tools/dbt-adapter-access.ts b/packages/opencode/src/altimate/tools/dbt-adapter-access.ts index d73dd7e9c5..6de998c0d8 100644 --- a/packages/opencode/src/altimate/tools/dbt-adapter-access.ts +++ b/packages/opencode/src/altimate/tools/dbt-adapter-access.ts @@ -25,6 +25,8 @@ export const dbtAdapterAccessInternals = { */ export async function dbtAdapterFor(ctx: Pick): Promise { const signal = ctx.abort + // A call cancelled before it starts is a cancellation, not a refusal. + signal.throwIfAborted() if (ctx.extra?.forceReadOnly === true || ctx.agent === "plan") return { refusal: "read_only", @@ -81,7 +83,7 @@ export async function dbtAdapterFor(ctx: Pick { +export async function sessionProject(): Promise<{ root?: string; other?: string } | undefined> { const { findProjectRoot } = await import("../../../../dbt-tools/src/config") const found = findProjectRoot(projectRoot()) if (!found) return undefined diff --git a/packages/opencode/src/altimate/tools/dbt-defer-state.ts b/packages/opencode/src/altimate/tools/dbt-defer-state.ts index 8b503f64dd..b50ec64eb4 100644 --- a/packages/opencode/src/altimate/tools/dbt-defer-state.ts +++ b/packages/opencode/src/altimate/tools/dbt-defer-state.ts @@ -1,7 +1,7 @@ import z from "zod" import fs from "fs" import path from "path" -import { parse as parseJsonc, type ParseError } from "jsonc-parser" +import { parse as parseJsonc, printParseErrorCode, type ParseError } from "jsonc-parser" import { Tool } from "../../tool/tool" import { resolveEnvVars, resolveProfilesPath } from "../native/connections/dbt-profiles" @@ -57,6 +57,8 @@ function readSettings(file: string): Record | typeof UNREADABLE // .vscode/settings.json allows comments and trailing commas. const parsed = parseJsonc(text, errors, { allowTrailingComma: true }) // A file that does not parse cannot be trusted to say defer is on. + // A file holding only comments has no value to parse, which VS Code reads as empty settings. + if (parsed === undefined && errors.every((e) => printParseErrorCode(e.error) === "ValueExpected")) return {} if (errors.length > 0) return UNREADABLE if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return UNREADABLE return parsed as Record @@ -96,6 +98,12 @@ export function findDeferSetting(projectDir: string, workspaceDir?: string) { if (entry && typeof entry === "object") { return { entry: entry as DeferSetting, key, file, folder } } + // A key naming the project through a symlink: compare the real paths. + const target = real(start) + for (const [k, v] of Object.entries(perProject as Record)) { + if (!v || typeof v !== "object") continue + if (real(path.resolve(folder, k)) === target) return { entry: v as DeferSetting, key: k, file, folder } + } } return undefined } diff --git a/packages/opencode/src/altimate/tools/dbt-lineage.ts b/packages/opencode/src/altimate/tools/dbt-lineage.ts index a83efb84ae..2403dfab89 100644 --- a/packages/opencode/src/altimate/tools/dbt-lineage.ts +++ b/packages/opencode/src/altimate/tools/dbt-lineage.ts @@ -7,6 +7,7 @@ import type { DbtLineageResult } from "../native/types" import { loadRawManifest } from "../native/dbt/helpers" import { lineageGraph } from "../native/dbt/graph" import { projectRoot } from "../native/connections/registry" +import { sessionProject } from "./dbt-adapter-access" /** The structured result of dbt-integration's `getModelLineage` (version 1), relayed as is. */ export type ModelLineage = { @@ -359,32 +360,6 @@ async function defaultManifestPath(session: () => ReturnType { - const { findProjectRoot } = await import("../../../../dbt-tools/src/config") - const found = findProjectRoot(projectRoot()) - if (!found) return undefined - const { getDbtProjectRoot } = await import("../native/connections/register") - const root = await getDbtProjectRoot() - const real = (p: string) => { - try { - return fs.realpathSync(p) - } catch { - return path.resolve(p) - } - } - const here = real(found) - // path.relative ignores case on win32. - if (!root) return { other: here } - return path.relative(real(root), here) ? { root: real(root), other: here } : { root } -} - const MAX_TEXT_EDGES = 200 /** A compact reading of the structured result, for clients that show the text. */ diff --git a/packages/opencode/test/altimate/dbt-adapter-access.test.ts b/packages/opencode/test/altimate/dbt-adapter-access.test.ts index b10c13dd7d..48b744352b 100644 --- a/packages/opencode/test/altimate/dbt-adapter-access.test.ts +++ b/packages/opencode/test/altimate/dbt-adapter-access.test.ts @@ -95,6 +95,14 @@ describe("feature tools in the allow-list", () => { }) }) +describe("dbtAdapterFor abort", () => { + test("a read-only call that is already cancelled is cancelled, not refused", async () => { + const ac = new AbortController() + ac.abort() + await expect(dbtAdapterFor({ abort: ac.signal, agent: "plan", extra: { forceReadOnly: true } } as any)).rejects.toBeDefined() + }) +}) + describe("dbtAdapterFor", () => { let created: number beforeEach(() => { diff --git a/packages/opencode/test/altimate/dbt-defer-state.test.ts b/packages/opencode/test/altimate/dbt-defer-state.test.ts index ae16a18308..0218628997 100644 --- a/packages/opencode/test/altimate/dbt-defer-state.test.ts +++ b/packages/opencode/test/altimate/dbt-defer-state.test.ts @@ -131,15 +131,20 @@ describe("dbt_defer_state", () => { }) test("${env:NAME} in the state path is expanded, and an unset one is left as written", async () => { + const saved = { set: process.env.DEFER_TEST_STATE, unset: process.env.DEFER_TEST_UNSET } process.env.DEFER_TEST_STATE = path.join(root, "analytics", "prod-state") + delete process.env.DEFER_TEST_UNSET try { settings({ analytics: { deferToProduction: true, manifestPathForDeferral: "${env:DEFER_TEST_STATE}" } }) expect((await resolveDeferState(path.join(root, "analytics"))).stateDir).toBe(path.join(root, "analytics", "prod-state")) + settings({ analytics: { deferToProduction: true, manifestPathForDeferral: "${env:DEFER_TEST_UNSET}" } }) + expect((await resolveDeferState(path.join(root, "analytics"))).reason).toContain("${env:DEFER_TEST_UNSET}") } finally { - delete process.env.DEFER_TEST_STATE + if (saved.set === undefined) delete process.env.DEFER_TEST_STATE + else process.env.DEFER_TEST_STATE = saved.set + if (saved.unset === undefined) delete process.env.DEFER_TEST_UNSET + else process.env.DEFER_TEST_UNSET = saved.unset } - settings({ analytics: { deferToProduction: true, manifestPathForDeferral: "${env:DEFER_TEST_UNSET}" } }) - expect((await resolveDeferState(path.join(root, "analytics"))).reason).toContain("${env:DEFER_TEST_UNSET}") }) test("an explicit workspace folder and an absolute state path are used", async () => { @@ -161,6 +166,33 @@ describe("dbt_defer_state", () => { expect((await resolveDeferState(path.join(root, "analytics"))).defaultTarget).toBe("dev") }) + test("double-quoted env_var() names and defaults are resolved too", async () => { + write("analytics/dbt_project.yml", "name: shop\nprofile: '{{ env_var(\"DEFER_TEST_PROFILE\", \"shop\") }}'\n") + write("profiles/profiles.yml", "shop:\n target: '{{ env_var(\"DEFER_TEST_TARGET2\", \"dev\") }}'\n outputs:\n dev:\n type: duckdb\n") + delete process.env.DEFER_TEST_PROFILE + delete process.env.DEFER_TEST_TARGET2 + expect(await resolveDeferState(path.join(root, "analytics"))).toMatchObject({ profile: "shop", defaultTarget: "dev" }) + }) + + test("a settings file holding only a comment does not hide the workspace entry", () => { + settings({ analytics: { deferToProduction: true } }) + fs.mkdirSync(path.join(root, "analytics", ".vscode"), { recursive: true }) + fs.writeFileSync(path.join(root, "analytics", ".vscode", "settings.json"), "// nothing yet\n") + expect(findDeferSetting(path.join(root, "analytics"))?.key).toBe("analytics") + }) + + test("a settings key naming the project through a symlink matches the real project path", () => { + const outside = fs.mkdtempSync(path.join(path.dirname(root), "ext2-")) + fs.symlinkSync(outside, path.join(root, "linked")) + try { + settings({ linked: { deferToProduction: true } }) + expect(findDeferSetting(outside, root)?.key).toBe("linked") + } finally { + fs.rmSync(path.join(root, "linked")) + fs.rmSync(outside, { recursive: true, force: true }) + } + }) + test("remote mode is reported as unsupported with no state dir", async () => { settings({ analytics: { deferToProduction: true, manifestPathType: "remote", dbtCoreIntegrationId: 7 } }) const result = await resolveDeferState(path.join(root, "analytics")) @@ -171,7 +203,8 @@ describe("dbt_defer_state", () => { test("missing settings file and unreadable profiles give defaults", async () => { fs.rmSync(path.join(root, ".vscode"), { recursive: true, force: true }) - fs.rmSync(path.join(root, "profiles"), { recursive: true, force: true }) + // An invalid file in place (not a removed directory) keeps the lookup off the developer's ~/.dbt/profiles.yml. + write("profiles/profiles.yml", "shop: [unclosed\n") const result = await resolveDeferState(path.join(root, "analytics")) expect(result).toMatchObject({ enabled: false, mode: "none", targets: [] }) expect(result.defaultTarget).toBeUndefined() From 2f881ca85eab5514ec26d4231f843b620b56edd7 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Sun, 15 Nov 2026 22:23:04 +0530 Subject: [PATCH 10/31] fix(tool): env_var defaults may hold the other quote character, a stray token in a settings file stays unreadable Co-Authored-By: Claude Sonnet 5.5 --- .../altimate/native/connections/dbt-profiles.ts | 2 +- .../src/altimate/tools/dbt-defer-state.ts | 6 +++--- .../test/altimate/dbt-defer-state.test.ts | 16 ++++++++++++++++ 3 files changed, 20 insertions(+), 4 deletions(-) diff --git a/packages/opencode/src/altimate/native/connections/dbt-profiles.ts b/packages/opencode/src/altimate/native/connections/dbt-profiles.ts index 8f2d883c97..f397e4e554 100644 --- a/packages/opencode/src/altimate/native/connections/dbt-profiles.ts +++ b/packages/opencode/src/altimate/native/connections/dbt-profiles.ts @@ -56,7 +56,7 @@ const KEY_MAP: Record = { export function resolveEnvVars(value: unknown): unknown { if (typeof value !== "string") return value return value.replace( - /\{\{\s*env_var\s*\(\s*(['"])([^'"]+)\1\s*(?:,\s*(['"])([^'"]*)\3\s*)?\)\s*\}\}/g, + /\{\{\s*env_var\s*\(\s*(['"])((?:(?!\1).)+)\1\s*(?:,\s*(['"])((?:(?!\3).)*)\3\s*)?\)\s*\}\}/g, (_match, _q1: string, envName: string, _q2?: string, defaultValue?: string) => { return process.env[envName] ?? defaultValue ?? "" }, diff --git a/packages/opencode/src/altimate/tools/dbt-defer-state.ts b/packages/opencode/src/altimate/tools/dbt-defer-state.ts index b50ec64eb4..af9c4d2a84 100644 --- a/packages/opencode/src/altimate/tools/dbt-defer-state.ts +++ b/packages/opencode/src/altimate/tools/dbt-defer-state.ts @@ -1,7 +1,7 @@ import z from "zod" import fs from "fs" import path from "path" -import { parse as parseJsonc, printParseErrorCode, type ParseError } from "jsonc-parser" +import { parse as parseJsonc, stripComments, type ParseError } from "jsonc-parser" import { Tool } from "../../tool/tool" import { resolveEnvVars, resolveProfilesPath } from "../native/connections/dbt-profiles" @@ -57,8 +57,8 @@ function readSettings(file: string): Record | typeof UNREADABLE // .vscode/settings.json allows comments and trailing commas. const parsed = parseJsonc(text, errors, { allowTrailingComma: true }) // A file that does not parse cannot be trusted to say defer is on. - // A file holding only comments has no value to parse, which VS Code reads as empty settings. - if (parsed === undefined && errors.every((e) => printParseErrorCode(e.error) === "ValueExpected")) return {} + // A file holding only comments has no value to parse, which VS Code reads as empty settings; a stray token is not that. + if (parsed === undefined && stripComments(text).trim() === "") return {} if (errors.length > 0) return UNREADABLE if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return UNREADABLE return parsed as Record diff --git a/packages/opencode/test/altimate/dbt-defer-state.test.ts b/packages/opencode/test/altimate/dbt-defer-state.test.ts index 0218628997..4e37569f93 100644 --- a/packages/opencode/test/altimate/dbt-defer-state.test.ts +++ b/packages/opencode/test/altimate/dbt-defer-state.test.ts @@ -181,6 +181,22 @@ describe("dbt_defer_state", () => { expect(findDeferSetting(path.join(root, "analytics"))?.key).toBe("analytics") }) + test("a settings file holding a stray token is still unreadable", async () => { + write(".vscode/settings.json", "}") + expect(findDeferSetting(path.join(root, "analytics"))).toBeUndefined() + write(".vscode/settings.json", JSON.stringify({ "dbt.deferConfigPerProject": { analytics: { deferToProduction: true } } })) + fs.mkdirSync(path.join(root, "analytics", ".vscode"), { recursive: true }) + fs.writeFileSync(path.join(root, "analytics", ".vscode", "settings.json"), "}") + expect(findDeferSetting(path.join(root, "analytics"))).toBeUndefined() + }) + + test("an env_var() default may hold the other quote character", async () => { + write("analytics/dbt_project.yml", "name: shop\nprofile: shop\n") + write("profiles/profiles.yml", "shop:\n target: \"{{ env_var('DEFER_TEST_Q', 'say \\\"hi\\\"') }}\"\n outputs:\n dev:\n type: duckdb\n") + delete process.env.DEFER_TEST_Q + expect((await resolveDeferState(path.join(root, "analytics"))).defaultTarget).toBe('say "hi"') + }) + test("a settings key naming the project through a symlink matches the real project path", () => { const outside = fs.mkdtempSync(path.join(path.dirname(root), "ext2-")) fs.symlinkSync(outside, path.join(root, "linked")) From 0570fdb666d10b5d1c233e1470e7bc510b9bf6c8 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Sun, 15 Nov 2026 22:24:49 +0530 Subject: [PATCH 11/31] fix(tool): env_var defaults may span lines Co-Authored-By: Claude Sonnet 5.5 --- .../src/altimate/native/connections/dbt-profiles.ts | 2 +- packages/opencode/test/altimate/dbt-defer-state.test.ts | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/opencode/src/altimate/native/connections/dbt-profiles.ts b/packages/opencode/src/altimate/native/connections/dbt-profiles.ts index f397e4e554..e90c8edf9a 100644 --- a/packages/opencode/src/altimate/native/connections/dbt-profiles.ts +++ b/packages/opencode/src/altimate/native/connections/dbt-profiles.ts @@ -56,7 +56,7 @@ const KEY_MAP: Record = { export function resolveEnvVars(value: unknown): unknown { if (typeof value !== "string") return value return value.replace( - /\{\{\s*env_var\s*\(\s*(['"])((?:(?!\1).)+)\1\s*(?:,\s*(['"])((?:(?!\3).)*)\3\s*)?\)\s*\}\}/g, + /\{\{\s*env_var\s*\(\s*(['"])((?:(?!\1)[\s\S])+)\1\s*(?:,\s*(['"])((?:(?!\3)[\s\S])*)\3\s*)?\)\s*\}\}/g, (_match, _q1: string, envName: string, _q2?: string, defaultValue?: string) => { return process.env[envName] ?? defaultValue ?? "" }, diff --git a/packages/opencode/test/altimate/dbt-defer-state.test.ts b/packages/opencode/test/altimate/dbt-defer-state.test.ts index 4e37569f93..6075277a39 100644 --- a/packages/opencode/test/altimate/dbt-defer-state.test.ts +++ b/packages/opencode/test/altimate/dbt-defer-state.test.ts @@ -5,6 +5,7 @@ import path from "path" import { Effect } from "effect" import type { Tool } from "../../src/tool/tool" import { SessionID, MessageID } from "../../src/session/schema" +import { resolveEnvVars } from "../../src/altimate/native/connections/dbt-profiles" import { DbtDeferStateTool, resolveDeferState, findDeferSetting } from "../../src/altimate/tools/dbt-defer-state" import { initTool } from "./tool-fixture" @@ -197,6 +198,11 @@ describe("dbt_defer_state", () => { expect((await resolveDeferState(path.join(root, "analytics"))).defaultTarget).toBe('say "hi"') }) + test("an env_var() default may span lines", () => { + delete process.env.DEFER_TEST_KEY + expect(resolveEnvVars("{{ env_var('DEFER_TEST_KEY', 'line1\nline2') }}")).toBe("line1\nline2") + }) + test("a settings key naming the project through a symlink matches the real project path", () => { const outside = fs.mkdtempSync(path.join(path.dirname(root), "ext2-")) fs.symlinkSync(outside, path.join(root, "linked")) From d8c34693b09dd856b0efd2c4a1924c7320346720 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Sun, 15 Nov 2026 22:27:01 +0530 Subject: [PATCH 12/31] fix: send falsy API bodies, follow cancellation in apiRequest, check abort before a read-only refusal - apiRequest sends any body but undefined (null, false, 0 and "" were dropped) and takes an optional signal that cancels the request along with its 15 s timeout. - dbtAdapterFor throws for a cancelled call before it would refuse a read-only or plan-mode one. - Tests cover these and a session inside the adapter's own project. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/api/client.ts | 25 ++++++-- .../src/altimate/tools/dbt-adapter-access.ts | 2 + .../test/altimate/dbt-adapter-access.test.ts | 63 +++++++++++++++++++ 3 files changed, 84 insertions(+), 6 deletions(-) diff --git a/packages/opencode/src/altimate/api/client.ts b/packages/opencode/src/altimate/api/client.ts index cb53c0ec7b..6ea7d96354 100644 --- a/packages/opencode/src/altimate/api/client.ts +++ b/packages/opencode/src/altimate/api/client.ts @@ -318,7 +318,13 @@ export namespace AltimateApi { return data.auth_token } - async function request(creds: AltimateCredentials, method: string, endpoint: string, body?: unknown) { + async function request( + creds: AltimateCredentials, + method: string, + endpoint: string, + body?: unknown, + signal?: AbortSignal, + ) { const url = `${creds.altimateUrl}${endpoint}` // altimate_change start — upstream_fix: bound every API request. Without a // signal a stalled server holds the caller indefinitely. The abort stays @@ -327,7 +333,7 @@ export namespace AltimateApi { const timeout = setTimeout(() => controller.abort(), 15_000) try { const res = await fetch(url, { - signal: controller.signal, + signal: signal ? AbortSignal.any([controller.signal, signal]) : controller.signal, method, headers: { "Content-Type": "application/json", @@ -335,7 +341,8 @@ export namespace AltimateApi { "x-tenant": creds.altimateInstanceName, ...clientHeaders(), }, - ...(body ? { body: JSON.stringify(body) } : {}), + // Any body but undefined is sent: null, false, 0 and "" are JSON values too. + ...(body !== undefined ? { body: JSON.stringify(body) } : {}), }) if (!res.ok) { throw new Error(`API ${method} ${endpoint} failed with status ${res.status}`) @@ -350,9 +357,15 @@ export namespace AltimateApi { /** * Calls an Altimate API endpoint with the stored credentials (Bearer key and x-tenant headers) and * returns the parsed JSON body. Endpoint functions in other files go through this. Fails with a - * message naming the credentials file when none are stored or they can't be read. + * message naming the credentials file when none are stored or they can't be read. `signal` (a tool + * call's `ctx.abort`) cancels the request as well as the 15 s timeout. */ - export async function apiRequest(method: string, endpoint: string, body?: unknown): Promise { + export async function apiRequest( + method: string, + endpoint: string, + body?: unknown, + signal?: AbortSignal, + ): Promise { let creds: AltimateCredentials try { creds = await getCredentials() @@ -364,7 +377,7 @@ export namespace AltimateApi { ) throw new Error(`The Altimate credentials in ${p} can't be used: ${e instanceof Error ? e.message : String(e)}`) } - return request(creds, method, endpoint, body) + return request(creds, method, endpoint, body, signal) } export async function listDatamates(creds?: AltimateCredentials) { diff --git a/packages/opencode/src/altimate/tools/dbt-adapter-access.ts b/packages/opencode/src/altimate/tools/dbt-adapter-access.ts index d73dd7e9c5..1ff9047e9a 100644 --- a/packages/opencode/src/altimate/tools/dbt-adapter-access.ts +++ b/packages/opencode/src/altimate/tools/dbt-adapter-access.ts @@ -25,6 +25,8 @@ export const dbtAdapterAccessInternals = { */ export async function dbtAdapterFor(ctx: Pick): Promise { const signal = ctx.abort + // A cancelled call answers nothing, refused or not. + signal.throwIfAborted() if (ctx.extra?.forceReadOnly === true || ctx.agent === "plan") return { refusal: "read_only", diff --git a/packages/opencode/test/altimate/dbt-adapter-access.test.ts b/packages/opencode/test/altimate/dbt-adapter-access.test.ts index b2a012ed58..75a2fed64d 100644 --- a/packages/opencode/test/altimate/dbt-adapter-access.test.ts +++ b/packages/opencode/test/altimate/dbt-adapter-access.test.ts @@ -125,6 +125,18 @@ describe("dbtAdapterFor", () => { expect(created).toBe(1) }) + test("returns the adapter to a session inside the adapter's own project", async () => { + try { + const access = await Instance.provide({ directory: project, fn: () => dbtAdapterFor(ctx) }) + expect(access.refusal).toBeUndefined() + expect(access.reason).toBeUndefined() + expect(access.adapter?.isInitialized()).toBe(true) + expect(created).toBe(1) + } finally { + await disposeInstance(project) + } + }) + test("says when the adapter didn't load the project", async () => { dbtAdapterInternals.create = async () => ({ isInitialized: () => false, dispose: async () => {} }) const access = await dbtAdapterFor(ctx) @@ -180,6 +192,15 @@ describe("dbtAdapterFor", () => { expect(created).toBe(0) }) + test("a cancelled read-only or plan-mode call throws rather than being refused", async () => { + const controller = new AbortController() + controller.abort() + const abort = controller.signal + await expect(dbtAdapterFor({ ...ctx, abort, extra: { forceReadOnly: true } })).rejects.toThrow() + await expect(dbtAdapterFor({ ...ctx, abort, agent: "plan" })).rejects.toThrow() + expect(created).toBe(0) + }) + test("a session in a dbt project the adapter isn't set up for says so", async () => { dbtAdapterInternals.readConfig = async () => null try { @@ -260,6 +281,48 @@ describe("AltimateApi.apiRequest", () => { } }) + test("sends a falsy JSON body rather than dropping it", async () => { + await Bun.write( + path.join(home, ".altimate", "altimate.json"), + JSON.stringify({ altimateUrl: "https://api.example.test", altimateInstanceName: "acme", altimateApiKey: "k1" }), + ) + const original = globalThis.fetch + const bodies: unknown[] = [] + globalThis.fetch = (async (_url: string, init: RequestInit) => { + bodies.push(init.body) + return new Response("{}", { status: 200 }) + }) as unknown as typeof fetch + try { + for (const body of [null, false, 0, ""]) await AltimateApi.apiRequest("POST", "/dbt/v1/x", body) + await AltimateApi.apiRequest("GET", "/dbt/v1/x") + expect(bodies).toEqual(["null", "false", "0", '""', undefined]) + } finally { + globalThis.fetch = original + } + }) + + test("a cancelled call stops the request", async () => { + await Bun.write( + path.join(home, ".altimate", "altimate.json"), + JSON.stringify({ altimateUrl: "https://api.example.test", altimateInstanceName: "acme", altimateApiKey: "k1" }), + ) + const original = globalThis.fetch + globalThis.fetch = ((_url: string, init: RequestInit) => + new Promise((_, reject) => { + // Like fetch: a signal already aborted rejects at once, else the abort does. + if (init.signal?.aborted) return reject(init.signal.reason) + init.signal?.addEventListener("abort", () => reject(init.signal?.reason), { once: true }) + })) as unknown as typeof fetch + const controller = new AbortController() + try { + const pending = AltimateApi.apiRequest("GET", "/dbt/v1/x", undefined, controller.signal) + controller.abort(new Error("cancelled by the user")) + await expect(pending).rejects.toThrow("cancelled by the user") + } finally { + globalThis.fetch = original + } + }) + test("names the file when the stored credentials can't be read", async () => { await Bun.write(path.join(home, ".altimate", "altimate.json"), "{not json") await expect(AltimateApi.apiRequest("GET", "/dbt/v1/x")).rejects.toThrow( From 86f4705d005c721bdfeaf9ad4f50c5b18e2fd31c Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 06:14:28 +0530 Subject: [PATCH 13/31] fix(tool): drop unused import in dbt_lineage, restore env in the double-quote env_var test Co-Authored-By: Claude Sonnet 5.5 --- .../opencode/test/altimate/dbt-defer-state.test.ts | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/packages/opencode/test/altimate/dbt-defer-state.test.ts b/packages/opencode/test/altimate/dbt-defer-state.test.ts index 6075277a39..d590a840fa 100644 --- a/packages/opencode/test/altimate/dbt-defer-state.test.ts +++ b/packages/opencode/test/altimate/dbt-defer-state.test.ts @@ -170,9 +170,17 @@ describe("dbt_defer_state", () => { test("double-quoted env_var() names and defaults are resolved too", async () => { write("analytics/dbt_project.yml", "name: shop\nprofile: '{{ env_var(\"DEFER_TEST_PROFILE\", \"shop\") }}'\n") write("profiles/profiles.yml", "shop:\n target: '{{ env_var(\"DEFER_TEST_TARGET2\", \"dev\") }}'\n outputs:\n dev:\n type: duckdb\n") - delete process.env.DEFER_TEST_PROFILE - delete process.env.DEFER_TEST_TARGET2 - expect(await resolveDeferState(path.join(root, "analytics"))).toMatchObject({ profile: "shop", defaultTarget: "dev" }) + const saved = { profile: process.env.DEFER_TEST_PROFILE, target: process.env.DEFER_TEST_TARGET2 } + try { + delete process.env.DEFER_TEST_PROFILE + delete process.env.DEFER_TEST_TARGET2 + expect(await resolveDeferState(path.join(root, "analytics"))).toMatchObject({ profile: "shop", defaultTarget: "dev" }) + } finally { + if (saved.profile === undefined) delete process.env.DEFER_TEST_PROFILE + else process.env.DEFER_TEST_PROFILE = saved.profile + if (saved.target === undefined) delete process.env.DEFER_TEST_TARGET2 + else process.env.DEFER_TEST_TARGET2 = saved.target + } }) test("a settings file holding only a comment does not hide the workspace entry", () => { From e2fba066adb4030ec79776455c716e816a26e76f Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 06:14:40 +0530 Subject: [PATCH 14/31] fix(tool): drop unused projectRoot import in dbt_lineage Co-Authored-By: Claude Sonnet 5.5 --- packages/opencode/src/altimate/tools/dbt-lineage.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/opencode/src/altimate/tools/dbt-lineage.ts b/packages/opencode/src/altimate/tools/dbt-lineage.ts index 2403dfab89..bda961d1a9 100644 --- a/packages/opencode/src/altimate/tools/dbt-lineage.ts +++ b/packages/opencode/src/altimate/tools/dbt-lineage.ts @@ -6,7 +6,6 @@ import { Dispatcher } from "../native" import type { DbtLineageResult } from "../native/types" import { loadRawManifest } from "../native/dbt/helpers" import { lineageGraph } from "../native/dbt/graph" -import { projectRoot } from "../native/connections/registry" import { sessionProject } from "./dbt-adapter-access" /** The structured result of dbt-integration's `getModelLineage` (version 1), relayed as is. */ From 18a3fc4e0bd124e8f5fb3120fdc4d152be88cbe3 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 06:39:46 +0530 Subject: [PATCH 15/31] fix: keep the stored API key out of API errors, bound the dbt config read - apiRequest names what is wrong with the credentials file (not valid JSON, which field is missing) instead of quoting the parser's message, which can quote the key. - request() redacts the key from a failed send: Bun's header check quotes `Bearer ` for a key with CR/LF, and throws before fetch returns a promise, so both a throw and a rejection are caught. - A request that times out says so; a cancelled apiRequest reads nothing. - dbtAdapterFor bounds the project lookup with the same deadline and abort as the adapter's start, and checks the abort after each wait. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/api/client.ts | 75 ++++++-- .../src/altimate/tools/dbt-adapter-access.ts | 52 ++--- .../test/altimate/dbt-adapter-access.test.ts | 179 +++++++++++++++++- 3 files changed, 265 insertions(+), 41 deletions(-) diff --git a/packages/opencode/src/altimate/api/client.ts b/packages/opencode/src/altimate/api/client.ts index 6ea7d96354..d3cfd1a887 100644 --- a/packages/opencode/src/altimate/api/client.ts +++ b/packages/opencode/src/altimate/api/client.ts @@ -318,6 +318,17 @@ export namespace AltimateApi { return data.auth_token } + /** Test seams. */ + export const requestInternals = { + /** How long an API request may take, body included, before it is aborted. */ + timeoutMs: 15_000, + } + + /** `text` with every occurrence of `secret` replaced, so an error can be shown without the key. */ + function redact(text: string, secret: string): string { + return secret ? text.split(secret).join("[redacted]") : text + } + async function request( creds: AltimateCredentials, method: string, @@ -326,24 +337,43 @@ export namespace AltimateApi { signal?: AbortSignal, ) { const url = `${creds.altimateUrl}${endpoint}` + // Bun's fetch throws at once, not as a rejection, when it refuses a header: both are caught. + const send = async (start: () => Promise) => { + try { + return await start() + } catch (e) { + // A timeout or the caller's abort rejects with its own reason, which holds no header. + if (controller.signal.aborted || signal?.aborted) throw e + // Others can quote a header: Bun's check of a header value with CR/LF quotes `Bearer `. + const message = redact(e instanceof Error ? e.message : String(e), creds.altimateApiKey) + throw new Error(`API ${method} ${endpoint} could not be sent: ${message}`) + } + } // altimate_change start — upstream_fix: bound every API request. Without a // signal a stalled server holds the caller indefinitely. The abort stays // armed until the BODY is read: `fetch` resolves on headers. const controller = new AbortController() - const timeout = setTimeout(() => controller.abort(), 15_000) + const seconds = requestInternals.timeoutMs / 1000 + const timeout = setTimeout( + () => + controller.abort(new DOMException(`API ${method} ${endpoint} timed out after ${seconds} s`, "TimeoutError")), + requestInternals.timeoutMs, + ) try { - const res = await fetch(url, { - signal: signal ? AbortSignal.any([controller.signal, signal]) : controller.signal, - method, - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${creds.altimateApiKey}`, - "x-tenant": creds.altimateInstanceName, - ...clientHeaders(), - }, - // Any body but undefined is sent: null, false, 0 and "" are JSON values too. - ...(body !== undefined ? { body: JSON.stringify(body) } : {}), - }) + const res = await send(() => + fetch(url, { + signal: signal ? AbortSignal.any([controller.signal, signal]) : controller.signal, + method, + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${creds.altimateApiKey}`, + "x-tenant": creds.altimateInstanceName, + ...clientHeaders(), + }, + // Any body but undefined is sent: null, false, 0 and "" are JSON values too. + ...(body !== undefined ? { body: JSON.stringify(body) } : {}), + }), + ) if (!res.ok) { throw new Error(`API ${method} ${endpoint} failed with status ${res.status}`) } @@ -354,11 +384,25 @@ export namespace AltimateApi { // altimate_change end } + /** What is wrong with the stored credentials, naming fields but never quoting the file's text. */ + function credentialsProblem(e: unknown): string { + // The parser's message quotes the text it stopped at, which can be the key. + if (e instanceof SyntaxError) return "the file is not valid JSON." + if (e instanceof z.ZodError) { + const fields = [...new Set(e.issues.map((issue) => issue.path.join(".")))] + if (fields.length === 0 || fields.includes("")) return "the file does not hold the credentials object." + return `${fields.join(", ")} ${fields.length === 1 ? "is" : "are"} missing or not valid.` + } + // A file system error or a missing ${env:NAME} variable: names a path or a variable, no value. + return e instanceof Error ? e.message : String(e) + } + /** * Calls an Altimate API endpoint with the stored credentials (Bearer key and x-tenant headers) and * returns the parsed JSON body. Endpoint functions in other files go through this. Fails with a * message naming the credentials file when none are stored or they can't be read. `signal` (a tool - * call's `ctx.abort`) cancels the request as well as the 15 s timeout. + * call's `ctx.abort`) cancels the request as well as the 15 s timeout. No error it raises quotes the + * stored key. */ export async function apiRequest( method: string, @@ -366,6 +410,7 @@ export namespace AltimateApi { body?: unknown, signal?: AbortSignal, ): Promise { + signal?.throwIfAborted() let creds: AltimateCredentials try { creds = await getCredentials() @@ -375,7 +420,7 @@ export namespace AltimateApi { throw new Error( `No Altimate credentials are stored: sign in to Altimate in altimate-code first (they are saved to ${p}).`, ) - throw new Error(`The Altimate credentials in ${p} can't be used: ${e instanceof Error ? e.message : String(e)}`) + throw new Error(`The Altimate credentials in ${p} can't be used: ${credentialsProblem(e)}`) } return request(creds, method, endpoint, body, signal) } diff --git a/packages/opencode/src/altimate/tools/dbt-adapter-access.ts b/packages/opencode/src/altimate/tools/dbt-adapter-access.ts index 1ff9047e9a..df8fb597dc 100644 --- a/packages/opencode/src/altimate/tools/dbt-adapter-access.ts +++ b/packages/opencode/src/altimate/tools/dbt-adapter-access.ts @@ -21,7 +21,8 @@ export const dbtAdapterAccessInternals = { * The dbt adapter for a tool call, which every adapter-backed tool goes through. Starting the adapter * runs dbt deps and writes target/, and compiling renders Jinja, which can run SQL: a read-only call * (no write permission, or plan mode) never starts or uses it. Nor does a session in a dbt project the - * adapter isn't set up for. The wait for the adapter to start is bounded and follows the call's abort. + * adapter isn't set up for. Every wait, the project lookup and the adapter's start, is bounded by one + * deadline and follows the call's abort. */ export async function dbtAdapterFor(ctx: Pick): Promise { const signal = ctx.abort @@ -32,12 +33,30 @@ export async function dbtAdapterFor(ctx: Pick {} + let timer: ReturnType | undefined + const waited = new Promise((_, reject) => { + stop = () => reject(signal.reason) + signal.addEventListener("abort", stop, { once: true }) + const seconds = dbtAdapterAccessInternals.adapterStartTimeoutMs / 1000 + timer = setTimeout( + () => reject(new Error(`the dbt adapter didn't start within ${seconds} s`)), + dbtAdapterAccessInternals.adapterStartTimeoutMs, + ) + }) + // It can reject between two races, when nothing awaits it: the next race still sees the rejection. + waited.catch(() => {}) + const bounded = async (work: Promise): Promise => { + const value = await Promise.race([work, waited]) + // An abort queued while the work settled still wins. signal.throwIfAborted() + return value + } + try { + const { getDbtAdapter, getDbtProjectRoot } = await bounded(import("../native/connections/register")) + const project = await bounded(sessionProject()) if (project?.other) { return { refusal: "other_project", @@ -46,24 +65,10 @@ export async function dbtAdapterFor(ctx: Pick {} - let timer: ReturnType | undefined - const waited = new Promise((_, reject) => { - stop = () => reject(signal.reason) - signal.addEventListener("abort", stop, { once: true }) - const seconds = dbtAdapterAccessInternals.adapterStartTimeoutMs / 1000 - timer = setTimeout( - () => reject(new Error(`the dbt adapter didn't start within ${seconds} s`)), - dbtAdapterAccessInternals.adapterStartTimeoutMs, - ) - }) - const adapter = await Promise.race([getDbtAdapter(), waited]).finally(() => { - signal.removeEventListener("abort", stop) - clearTimeout(timer) - }) + const adapter = await bounded(getDbtAdapter()) if (!adapter) { // No adapter also when the project exists but the adapter failed to start: say which. - const root = await getDbtProjectRoot() + const root = await bounded(getDbtProjectRoot()) const found = !!root && fs.existsSync(path.join(root, "dbt_project.yml")) return found ? { refusal: "not_started", reason: "the dbt adapter didn't start" } @@ -75,6 +80,9 @@ export async function dbtAdapterFor(ctx: Pick { } }) + test("a stalled dbt config read gives up at the start timeout", async () => { + let release = () => {} + dbtAdapterInternals.readConfig = () => new Promise((resolve) => (release = () => resolve(null))) + const saved = dbtAdapterAccessInternals.adapterStartTimeoutMs + dbtAdapterAccessInternals.adapterStartTimeoutMs = 20 + try { + const access = await Instance.provide({ directory: project, fn: () => dbtAdapterFor(ctx) }) + expect(access).toEqual({ refusal: "not_started", reason: "the dbt adapter didn't start within 0.02 s" }) + expect(created).toBe(0) + } finally { + release() + dbtAdapterAccessInternals.adapterStartTimeoutMs = saved + await disposeInstance(project) + } + }) + + test("a call cancelled during a stalled dbt config read throws at once", async () => { + let release = () => {} + let entered = () => {} + const reading = new Promise((resolve) => (entered = resolve)) + dbtAdapterInternals.readConfig = () => { + entered() + return new Promise((resolve) => (release = () => resolve(null))) + } + const controller = new AbortController() + try { + const pending = Instance.provide({ + directory: project, + fn: () => dbtAdapterFor({ ...ctx, abort: controller.signal }), + }) + await reading + controller.abort(new Error("cancelled")) + await expect(pending).rejects.toThrow("cancelled") + } finally { + release() + await disposeInstance(project) + } + }) + + test("removes its abort listener and its timer whatever the outcome", async () => { + const controller = new AbortController() + const signal = controller.signal + let listening = 0 + const add = signal.addEventListener.bind(signal) + const remove = signal.removeEventListener.bind(signal) + signal.addEventListener = ((...a: Parameters) => { + if (a[0] === "abort") listening += 1 + return add(...a) + }) as typeof signal.addEventListener + signal.removeEventListener = ((...a: Parameters) => { + if (a[0] === "abort") listening -= 1 + return remove(...a) + }) as typeof signal.removeEventListener + const timers = new Set() + const set = globalThis.setTimeout + const clear = globalThis.clearTimeout + globalThis.setTimeout = ((fn: () => void, ms?: number) => { + const t = set(fn, ms) + timers.add(t) + return t + }) as typeof setTimeout + globalThis.clearTimeout = ((t: ReturnType) => { + timers.delete(t) + return clear(t) + }) as typeof clearTimeout + try { + expect((await dbtAdapterFor({ ...ctx, abort: signal })).adapter).toBeDefined() + dbtAdapterInternals.create = async () => { + throw new Error("dbt-integration missing") + } + resetDbtAdapter() + expect((await dbtAdapterFor({ ...ctx, abort: signal })).refusal).toBe("not_started") + } finally { + globalThis.setTimeout = set + globalThis.clearTimeout = clear + } + expect(listening).toBe(0) + expect(timers.size).toBe(0) + }) + test("a session in another dbt project than the adapter's says which", async () => { const other = await mkdtemp(path.join(os.tmpdir(), "dbt-adapter-other-")) await writeFile(path.join(other, "dbt_project.yml"), "name: other\n") @@ -323,10 +403,101 @@ describe("AltimateApi.apiRequest", () => { } }) - test("names the file when the stored credentials can't be read", async () => { - await Bun.write(path.join(home, ".altimate", "altimate.json"), "{not json") - await expect(AltimateApi.apiRequest("GET", "/dbt/v1/x")).rejects.toThrow( - `The Altimate credentials in ${path.join(home, ".altimate", "altimate.json")} can't be used`, + test("names the file and the failure, never the file's text, when the credentials aren't valid JSON", async () => { + const file = path.join(home, ".altimate", "altimate.json") + await Bun.write( + file, + '{"altimateUrl":"https://x.test","altimateInstanceName":"acme","altimateApiKey": sk_SECRET123}', + ) + const error = await AltimateApi.apiRequest("GET", "/dbt/v1/x").catch((e: Error) => e) + expect(error).toBeInstanceOf(Error) + expect(error.message).toBe(`The Altimate credentials in ${file} can't be used: the file is not valid JSON.`) + expect(error.message).not.toContain("sk_SECRET123") + }) + + test("names the missing field, never a value, when the credentials are incomplete", async () => { + const file = path.join(home, ".altimate", "altimate.json") + await Bun.write(file, JSON.stringify({ altimateUrl: "https://x.test", altimateApiKey: "sk_SECRET123" })) + const error = await AltimateApi.apiRequest("GET", "/dbt/v1/x").catch((e: Error) => e) + expect(error.message).toBe( + `The Altimate credentials in ${file} can't be used: altimateInstanceName is missing or not valid.`, ) + expect(error.message).not.toContain("sk_SECRET123") + }) + + test("never shows the stored key when sending the request fails", async () => { + const key = "sk_SECRET123\r\nX: y" + await Bun.write( + path.join(home, ".altimate", "altimate.json"), + JSON.stringify({ altimateUrl: "http://127.0.0.1:9", altimateInstanceName: "acme", altimateApiKey: key }), + ) + // The real fetch: it rejects a header value with CR/LF, quoting the value. + const error = await AltimateApi.apiRequest("GET", "/dbt/v1/x").catch((e: Error) => e) + expect(error).toBeInstanceOf(Error) + expect(error.message).not.toContain("sk_SECRET123") + expect(error.message).toContain("API GET /dbt/v1/x could not be sent") + }) + + test("never shows the stored key from any fetch failure", async () => { + await Bun.write( + path.join(home, ".altimate", "altimate.json"), + JSON.stringify({ + altimateUrl: "https://api.example.test", + altimateInstanceName: "acme", + altimateApiKey: "sk_SECRET123", + }), + ) + const original = globalThis.fetch + globalThis.fetch = (async (_url: string, init: RequestInit) => { + throw new TypeError(`bad header: '${(init.headers as Record).Authorization}'`) + }) as unknown as typeof fetch + try { + const error = await AltimateApi.apiRequest("GET", "/dbt/v1/x").catch((e: Error) => e) + expect(error.message).toBe("API GET /dbt/v1/x could not be sent: bad header: 'Bearer [redacted]'") + } finally { + globalThis.fetch = original + } + }) + + test("a timed-out request says it timed out", async () => { + await Bun.write( + path.join(home, ".altimate", "altimate.json"), + JSON.stringify({ altimateUrl: "https://api.example.test", altimateInstanceName: "acme", altimateApiKey: "k1" }), + ) + const original = globalThis.fetch + globalThis.fetch = ((_url: string, init: RequestInit) => + new Promise((_, reject) => { + init.signal?.addEventListener("abort", () => reject(init.signal?.reason), { once: true }) + })) as unknown as typeof fetch + const saved = AltimateApi.requestInternals.timeoutMs + AltimateApi.requestInternals.timeoutMs = 10 + try { + await expect(AltimateApi.apiRequest("GET", "/dbt/v1/x")).rejects.toThrow( + "API GET /dbt/v1/x timed out after 0.01 s", + ) + } finally { + AltimateApi.requestInternals.timeoutMs = saved + globalThis.fetch = original + } + }) + + test("a call cancelled before it starts reads no credentials and sends nothing", async () => { + const original = globalThis.fetch + let sent = 0 + globalThis.fetch = (async () => { + sent += 1 + return new Response("{}") + }) as unknown as typeof fetch + const controller = new AbortController() + controller.abort(new Error("cancelled by the user")) + try { + // No credentials are stored: reading them would fail with another message. + await expect(AltimateApi.apiRequest("GET", "/dbt/v1/x", undefined, controller.signal)).rejects.toThrow( + "cancelled by the user", + ) + expect(sent).toBe(0) + } finally { + globalThis.fetch = original + } }) }) From 6024ac9b208400ff2c70f8ef07e98b1568163276 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 06:47:20 +0530 Subject: [PATCH 16/31] fix: redact the API key when a refused header races the caller's abort; assert stub failure classification Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/api/client.ts | 5 ++-- .../test/altimate/dbt-adapter-access.test.ts | 27 +++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/api/client.ts b/packages/opencode/src/altimate/api/client.ts index d3cfd1a887..25a78d8bd0 100644 --- a/packages/opencode/src/altimate/api/client.ts +++ b/packages/opencode/src/altimate/api/client.ts @@ -342,8 +342,9 @@ export namespace AltimateApi { try { return await start() } catch (e) { - // A timeout or the caller's abort rejects with its own reason, which holds no header. - if (controller.signal.aborted || signal?.aborted) throw e + // A timeout or the caller's abort rejects with its own reason, which holds no header. An abort + // that raced a refused header leaves the header error, so match the reason, not the flag. + if (e === controller.signal.reason || e === signal?.reason) throw e // Others can quote a header: Bun's check of a header value with CR/LF quotes `Bearer `. const message = redact(e instanceof Error ? e.message : String(e), creds.altimateApiKey) throw new Error(`API ${method} ${endpoint} could not be sent: ${message}`) diff --git a/packages/opencode/test/altimate/dbt-adapter-access.test.ts b/packages/opencode/test/altimate/dbt-adapter-access.test.ts index 53592c8bc6..f998a83334 100644 --- a/packages/opencode/test/altimate/dbt-adapter-access.test.ts +++ b/packages/opencode/test/altimate/dbt-adapter-access.test.ts @@ -11,6 +11,7 @@ import type { Tool } from "@/tool/tool" import { SessionID, MessageID } from "@/session/schema" import { dbtAdapterInternals, resetDbtAdapter } from "@/altimate/native/connections/register" import { dbtAdapterAccessInternals, dbtAdapterFor } from "@/altimate/tools/dbt-adapter-access" +import { resultFailed } from "@/altimate/mcp-server/adapter" import { EXPOSED, MCP_OPEN_WRITE_TOOLS, WRITE_TOOLS } from "@/altimate/tool-cli/allow-list" import { AltimateApi } from "@/altimate/api/client" import { Instance } from "@/project/instance" @@ -89,6 +90,7 @@ describe("feature tools in the allow-list", () => { expect(result.title).toBe(`${id}: not implemented`) expect(result.metadata).toEqual({ success: false, error: "not implemented", truncated: false }) expect(result.output).toContain(id) + expect(resultFailed(result)).toBe(true) } }) }) @@ -438,6 +440,31 @@ describe("AltimateApi.apiRequest", () => { expect(error.message).toContain("API GET /dbt/v1/x could not be sent") }) + test("never shows the stored key when a header refusal races the caller's abort", async () => { + await Bun.write( + path.join(home, ".altimate", "altimate.json"), + JSON.stringify({ + altimateUrl: "https://api.example.test", + altimateInstanceName: "acme", + altimateApiKey: "sk_SECRET123", + }), + ) + const original = globalThis.fetch + const controller = new AbortController() + globalThis.fetch = (async (_url: string, init: RequestInit) => { + controller.abort(new Error("cancelled by the user")) + throw new TypeError(`bad header: '${(init.headers as Record).Authorization}'`) + }) as unknown as typeof fetch + try { + const error = await AltimateApi.apiRequest("GET", "/dbt/v1/x", undefined, controller.signal).catch( + (e: Error) => e, + ) + expect(error.message).toBe("API GET /dbt/v1/x could not be sent: bad header: 'Bearer [redacted]'") + } finally { + globalThis.fetch = original + } + }) + test("never shows the stored key from any fetch failure", async () => { await Bun.write( path.join(home, ".altimate", "altimate.json"), From f5159c51d1fcc7b8024a6d475ecc39106bbe8371 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 06:47:45 +0530 Subject: [PATCH 17/31] docs: say which tools use the dbt adapter helper Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/tools/dbt-adapter-access.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/opencode/src/altimate/tools/dbt-adapter-access.ts b/packages/opencode/src/altimate/tools/dbt-adapter-access.ts index df8fb597dc..7f93d822e9 100644 --- a/packages/opencode/src/altimate/tools/dbt-adapter-access.ts +++ b/packages/opencode/src/altimate/tools/dbt-adapter-access.ts @@ -18,7 +18,7 @@ export const dbtAdapterAccessInternals = { } /** - * The dbt adapter for a tool call, which every adapter-backed tool goes through. Starting the adapter + * The dbt adapter for a tool call, which the adapter-backed tools added after dbt_lineage go through. Starting the adapter * runs dbt deps and writes target/, and compiling renders Jinja, which can run SQL: a read-only call * (no write permission, or plan mode) never starts or uses it. Nor does a session in a dbt project the * adapter isn't set up for. Every wait, the project lookup and the adapter's start, is bounded by one From f57de3da23aab9065822038372fbb2eb5e120299 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 06:52:44 +0530 Subject: [PATCH 18/31] docs: rewrap and correct the adapter helper comments Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/tools/dbt-adapter-access.ts | 10 +++++----- .../opencode/test/altimate/dbt-adapter-access.test.ts | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/opencode/src/altimate/tools/dbt-adapter-access.ts b/packages/opencode/src/altimate/tools/dbt-adapter-access.ts index 7f93d822e9..2fc2aba423 100644 --- a/packages/opencode/src/altimate/tools/dbt-adapter-access.ts +++ b/packages/opencode/src/altimate/tools/dbt-adapter-access.ts @@ -18,11 +18,11 @@ export const dbtAdapterAccessInternals = { } /** - * The dbt adapter for a tool call, which the adapter-backed tools added after dbt_lineage go through. Starting the adapter - * runs dbt deps and writes target/, and compiling renders Jinja, which can run SQL: a read-only call - * (no write permission, or plan mode) never starts or uses it. Nor does a session in a dbt project the - * adapter isn't set up for. Every wait, the project lookup and the adapter's start, is bounded by one - * deadline and follows the call's abort. + * The dbt adapter for a tool call, which the adapter-backed tools added after dbt_lineage go through. + * Starting the adapter runs dbt deps and writes target/, and compiling renders Jinja, which can run + * SQL: a read-only call (no write permission, or plan mode) never starts or uses it. Nor does a + * session in a dbt project the adapter isn't set up for. Every wait, the project lookup and the + * adapter's start, is bounded by one deadline and follows the call's abort. */ export async function dbtAdapterFor(ctx: Pick): Promise { const signal = ctx.abort diff --git a/packages/opencode/test/altimate/dbt-adapter-access.test.ts b/packages/opencode/test/altimate/dbt-adapter-access.test.ts index f998a83334..ddcf0ea183 100644 --- a/packages/opencode/test/altimate/dbt-adapter-access.test.ts +++ b/packages/opencode/test/altimate/dbt-adapter-access.test.ts @@ -1,5 +1,5 @@ // The tools the dbt Power User features call: their allow-list entries and placeholder answers, the -// one gate every dbt-adapter-backed tool goes through, and the API helper for new endpoint files. The +// one gate the new dbt-adapter-backed tools go through, and the API helper for new endpoint files. The // dbt adapter is replaced through `dbtAdapterInternals`, so these tests need no Python or dbt. import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test" import { mkdtemp, rm, writeFile } from "node:fs/promises" From 191a968363f500e93d043324f93f076172b6b38d Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 07:55:14 +0530 Subject: [PATCH 19/31] fix(dbt-defer-state): say when the settings file cannot be read; keep expanded env values out of error reasons Co-Authored-By: Claude Sonnet 5.5 --- .../src/altimate/tools/dbt-defer-state.ts | 22 +++++++++++++------ .../test/altimate/dbt-defer-state.test.ts | 15 +++++++++++++ 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/packages/opencode/src/altimate/tools/dbt-defer-state.ts b/packages/opencode/src/altimate/tools/dbt-defer-state.ts index af9c4d2a84..31d0f5f817 100644 --- a/packages/opencode/src/altimate/tools/dbt-defer-state.ts +++ b/packages/opencode/src/altimate/tools/dbt-defer-state.ts @@ -69,7 +69,7 @@ function readSettings(file: string): Record | typeof UNREADABLE * project itself) whose `.vscode/settings.json` has an entry under the project's relative path. A settings * file that cannot be read or parsed ends the search. */ -export function findDeferSetting(projectDir: string, workspaceDir?: string) { +function lookupDeferSetting(projectDir: string, workspaceDir?: string) { const real = (p: string) => { try { return fs.realpathSync(path.resolve(p)) @@ -90,7 +90,7 @@ export function findDeferSetting(projectDir: string, workspaceDir?: string) { const file = path.join(folder, ".vscode", "settings.json") const settings = readSettings(file) // The nearest settings file that cannot be read ends the search: an outer folder's entry must not stand in for it. - if (settings === UNREADABLE) return UNREADABLE + if (settings === UNREADABLE) return { unreadable: file } const perProject = settings?.[SETTING] if (!perProject || typeof perProject !== "object") continue const key = path.relative(folder, start) @@ -114,8 +114,8 @@ export function findDeferSetting(projectDir: string, workspaceDir?: string) { for (const [i, [start, workspace]] of passes.entries()) { const found = search(start, workspace) // An unreadable file ends the search of its own pass; the pass over the real paths may still reach a readable one. - if (found === UNREADABLE) { - if (i === passes.length - 1) return undefined + if (found && "unreadable" in found) { + if (i === passes.length - 1) return found continue } if (found) return found @@ -176,12 +176,20 @@ function isDirectory(dir: string): boolean { } } +/** The entry for the project; undefined when there is none or the settings file cannot be trusted. */ +export function findDeferSetting(projectDir: string, workspaceDir?: string) { + const found = lookupDeferSetting(projectDir, workspaceDir) + return found && "unreadable" in found ? undefined : found +} + export async function resolveDeferState(projectDir: string, workspaceDir?: string): Promise { const root = path.resolve(projectDir) const targets = await readProfileTargets(root) const base: DeferStateResult = { enabled: false, favorState: false, mode: "none", ...targets } - const found = findDeferSetting(root, workspaceDir) + const found = lookupDeferSetting(root, workspaceDir) if (!found) return base + // Said outright: the same silence as "no setting" would send the caller on without --defer and no one the wiser. + if ("unreadable" in found) return { ...base, settingsFile: found.unreadable, reason: `The settings file could not be read or parsed, so defer is left off: ${found.unreadable}` } const { entry } = found const result: DeferStateResult = { @@ -212,10 +220,10 @@ export async function resolveDeferState(projectDir: string, workspaceDir?: strin const expanded = expandVariables(raw, root) const stateDir = path.isAbsolute(expanded) ? expanded : path.resolve(root, expanded) if (!isDirectory(stateDir)) { - return { ...result, reason: `manifestPathForDeferral is not a directory: ${stateDir}` } + return { ...result, reason: `manifestPathForDeferral is not a directory: ${raw}` } } if (!isFile(path.join(stateDir, "manifest.json"))) { - return { ...result, reason: `No manifest.json in manifestPathForDeferral: ${stateDir}` } + return { ...result, reason: `No manifest.json in manifestPathForDeferral: ${raw}` } } return { ...result, enabled: wanted, stateDir } } diff --git a/packages/opencode/test/altimate/dbt-defer-state.test.ts b/packages/opencode/test/altimate/dbt-defer-state.test.ts index d590a840fa..b47a4b5461 100644 --- a/packages/opencode/test/altimate/dbt-defer-state.test.ts +++ b/packages/opencode/test/altimate/dbt-defer-state.test.ts @@ -115,6 +115,21 @@ describe("dbt_defer_state", () => { settings({ analytics: { deferToProduction: true, manifestPathForDeferral: "${workspaceFolder}/prod-state" } }) const result = await resolveDeferState(path.join(root, "analytics")) expect(result).toMatchObject({ enabled: false, mode: "none" }) + expect(result.reason).toContain(path.join(root, "analytics", ".vscode", "settings.json")) + }) + + test("an error about the state path names the setting as written, not an expanded environment variable", async () => { + const saved = process.env.DEFER_TEST_SECRET + process.env.DEFER_TEST_SECRET = "s3cr3t-value" + try { + settings({ analytics: { deferToProduction: true, manifestPathForDeferral: "${env:DEFER_TEST_SECRET}" } }) + const result = await resolveDeferState(path.join(root, "analytics")) + expect(result.reason).toContain("${env:DEFER_TEST_SECRET}") + expect(result.reason).not.toContain("s3cr3t-value") + } finally { + if (saved === undefined) delete process.env.DEFER_TEST_SECRET + else process.env.DEFER_TEST_SECRET = saved + } }) test("an unknown manifest type does not enable defer", async () => { From 01c10b22390e02ba8a3d7ca0d4fe8c24bd84b706 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 07:58:31 +0530 Subject: [PATCH 20/31] fix(dbt-defer-state): keep an unreadable settings file's report when the real-path pass finds nothing Co-Authored-By: Claude Sonnet 5.5 --- .../src/altimate/tools/dbt-defer-state.ts | 11 ++++++----- .../test/altimate/dbt-defer-state.test.ts | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/packages/opencode/src/altimate/tools/dbt-defer-state.ts b/packages/opencode/src/altimate/tools/dbt-defer-state.ts index 31d0f5f817..f6ca9e7b95 100644 --- a/packages/opencode/src/altimate/tools/dbt-defer-state.ts +++ b/packages/opencode/src/altimate/tools/dbt-defer-state.ts @@ -24,7 +24,7 @@ export interface DeferStateResult { mode: "local" | "remote" | "none" /** Directory holding the manifest to defer to; set whenever the configured local one can be used, also while defer is off. */ stateDir?: string - /** Why the configured defer cannot be used: no usable state directory, remote mode, an unknown manifest type. */ + /** Why the configured defer cannot be used: no usable state directory, remote mode, an unknown manifest type, a settings file that cannot be read. */ reason?: string /** The settings key that matched, relative to the workspace folder. */ settingsKey?: string @@ -111,16 +111,17 @@ function lookupDeferSetting(projectDir: string, workspaceDir?: string) { const lexical = [path.resolve(projectDir), workspaceDir ? path.resolve(workspaceDir) : undefined] as const const resolved = [real(projectDir), workspaceDir ? real(workspaceDir) : undefined] as const const passes = lexical[0] === resolved[0] && lexical[1] === resolved[1] ? [lexical] : [lexical, resolved] - for (const [i, [start, workspace]] of passes.entries()) { + let unreadable: { unreadable: string } | undefined + for (const [start, workspace] of passes) { const found = search(start, workspace) // An unreadable file ends the search of its own pass; the pass over the real paths may still reach a readable one. - if (found && "unreadable" in found) { - if (i === passes.length - 1) return found + if (found && typeof found.unreadable === "string") { + unreadable ??= { unreadable: found.unreadable } continue } if (found) return found } - return undefined + return unreadable } function profilesFile(projectDir: string): string | undefined { diff --git a/packages/opencode/test/altimate/dbt-defer-state.test.ts b/packages/opencode/test/altimate/dbt-defer-state.test.ts index b47a4b5461..97b6d9c96d 100644 --- a/packages/opencode/test/altimate/dbt-defer-state.test.ts +++ b/packages/opencode/test/altimate/dbt-defer-state.test.ts @@ -144,6 +144,7 @@ describe("dbt_defer_state", () => { write(".vscode/settings.json", '{ "dbt.deferConfigPerProject": { "analytics": { "deferToProduction": true, "manifestPathForDeferral": "${workspaceFolder}/prod-state" } } } oops') const result = await resolveDeferState(path.join(root, "analytics")) expect(result).toMatchObject({ enabled: false, mode: "none" }) + expect(result.reason).toContain("could not be read or parsed") }) test("${env:NAME} in the state path is expanded, and an unset one is left as written", async () => { @@ -305,6 +306,24 @@ describe("dbt_defer_state", () => { } }) + test("an unparseable settings file above a symlinked project is named when the real path has no entry", async () => { + const real = fs.mkdtempSync(path.join(path.dirname(root), "real-")) + fs.mkdirSync(path.join(real, "analytics")) + const holder = fs.mkdtempSync(path.join(path.dirname(root), "hold-")) + fs.mkdirSync(path.join(holder, ".vscode")) + fs.writeFileSync(path.join(holder, ".vscode", "settings.json"), "{ not json") + const link = path.join(holder, "analytics") + fs.symlinkSync(path.join(real, "analytics"), link) + try { + const result = await resolveDeferState(link) + expect(result.enabled).toBe(false) + expect(result.reason).toContain("settings.json") + } finally { + fs.rmSync(real, { recursive: true, force: true }) + fs.rmSync(holder, { recursive: true, force: true }) + } + }) + test("settings with comments and trailing commas parse", () => { settings({ analytics: { deferToProduction: true } }) expect(findDeferSetting(path.join(root, "analytics"))?.key).toBe("analytics") From a6e04223d9a521fd89103237a0820b51a9b0705f Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 11:43:53 +0530 Subject: [PATCH 21/31] fix(dbt-defer-state): a settings file with an unclosed block comment is unreadable Co-Authored-By: Claude Sonnet 5.5 --- .../opencode/src/altimate/tools/dbt-defer-state.ts | 13 +++++++++++-- .../opencode/test/altimate/dbt-defer-state.test.ts | 7 +++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/tools/dbt-defer-state.ts b/packages/opencode/src/altimate/tools/dbt-defer-state.ts index f6ca9e7b95..9c4bf7cc39 100644 --- a/packages/opencode/src/altimate/tools/dbt-defer-state.ts +++ b/packages/opencode/src/altimate/tools/dbt-defer-state.ts @@ -1,7 +1,7 @@ import z from "zod" import fs from "fs" import path from "path" -import { parse as parseJsonc, stripComments, type ParseError } from "jsonc-parser" +import { createScanner, parse as parseJsonc, stripComments, ScanError, type ParseError } from "jsonc-parser" import { Tool } from "../../tool/tool" import { resolveEnvVars, resolveProfilesPath } from "../native/connections/dbt-profiles" @@ -41,6 +41,15 @@ function expandVariables(value: string, workspaceFolder: string): string { .replace(/\$\{workspaceFolder\}/g, () => workspaceFolder) } +/** A `/* ...` block comment that never closes: stripComments drops it silently, but VS Code cannot read the file. */ +function hasUnterminatedComment(text: string): boolean { + const scanner = createScanner(text, false) + while (scanner.scan() !== 17 /* SyntaxKind.EOF */) { + if (scanner.getTokenError() === ScanError.UnexpectedEndOfComment) return true + } + return false +} + const UNREADABLE = Symbol("unreadable settings") /** The parsed settings; undefined when there is no file, UNREADABLE when there is one that cannot be trusted. */ @@ -58,7 +67,7 @@ function readSettings(file: string): Record | typeof UNREADABLE const parsed = parseJsonc(text, errors, { allowTrailingComma: true }) // A file that does not parse cannot be trusted to say defer is on. // A file holding only comments has no value to parse, which VS Code reads as empty settings; a stray token is not that. - if (parsed === undefined && stripComments(text).trim() === "") return {} + if (parsed === undefined && stripComments(text).trim() === "" && !hasUnterminatedComment(text)) return {} if (errors.length > 0) return UNREADABLE if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return UNREADABLE return parsed as Record diff --git a/packages/opencode/test/altimate/dbt-defer-state.test.ts b/packages/opencode/test/altimate/dbt-defer-state.test.ts index 97b6d9c96d..4fb91c855c 100644 --- a/packages/opencode/test/altimate/dbt-defer-state.test.ts +++ b/packages/opencode/test/altimate/dbt-defer-state.test.ts @@ -215,6 +215,13 @@ describe("dbt_defer_state", () => { expect(findDeferSetting(path.join(root, "analytics"))).toBeUndefined() }) + test("a settings file with a block comment that never closes is unreadable and ends the search", () => { + settings({ analytics: { deferToProduction: true } }) + fs.mkdirSync(path.join(root, "analytics", ".vscode"), { recursive: true }) + fs.writeFileSync(path.join(root, "analytics", ".vscode", "settings.json"), "/* unfinished") + expect(findDeferSetting(path.join(root, "analytics"))).toBeUndefined() + }) + test("an env_var() default may hold the other quote character", async () => { write("analytics/dbt_project.yml", "name: shop\nprofile: shop\n") write("profiles/profiles.yml", "shop:\n target: \"{{ env_var('DEFER_TEST_Q', 'say \\\"hi\\\"') }}\"\n outputs:\n dev:\n type: duckdb\n") From 3f232ff4f17ce5bf13c2123eab6bbd68e51a8898 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 11:44:23 +0530 Subject: [PATCH 22/31] fix(dbt-defer-state): use the scan error code, not the const enum Co-Authored-By: Claude Sonnet 5.5 --- packages/opencode/src/altimate/tools/dbt-defer-state.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/tools/dbt-defer-state.ts b/packages/opencode/src/altimate/tools/dbt-defer-state.ts index 9c4bf7cc39..2bbfef2ef2 100644 --- a/packages/opencode/src/altimate/tools/dbt-defer-state.ts +++ b/packages/opencode/src/altimate/tools/dbt-defer-state.ts @@ -1,7 +1,7 @@ import z from "zod" import fs from "fs" import path from "path" -import { createScanner, parse as parseJsonc, stripComments, ScanError, type ParseError } from "jsonc-parser" +import { createScanner, parse as parseJsonc, stripComments, type ParseError } from "jsonc-parser" import { Tool } from "../../tool/tool" import { resolveEnvVars, resolveProfilesPath } from "../native/connections/dbt-profiles" @@ -45,7 +45,7 @@ function expandVariables(value: string, workspaceFolder: string): string { function hasUnterminatedComment(text: string): boolean { const scanner = createScanner(text, false) while (scanner.scan() !== 17 /* SyntaxKind.EOF */) { - if (scanner.getTokenError() === ScanError.UnexpectedEndOfComment) return true + if (scanner.getTokenError() === 1 /* ScanError.UnexpectedEndOfComment */) return true } return false } From aaff4148345d9e6735a119d27ea540a3d2929a9d Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 13:21:13 +0530 Subject: [PATCH 23/31] fix: never echo a send failure's text, so a trimmed key can't leak Bun trims a header value before quoting it in its validation error, so redacting exact copies of the stored key missed keys with a line break and trailing whitespace. A send failure now reports only a fixed reason for a refused header, or the error's name and code otherwise. Also: a missing ${env:...} variable no longer quotes its name from the credentials file; a credentials directory that can't be searched is reported as unreadable, not as no credentials; the adapter deadline says "wasn't ready" since it covers the config read too. Regression tests go through the real fetch for CR/LF and trailing-whitespace keys, via apiRequest and listDatamates, and check stubs still validate input. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/api/client.ts | 40 ++++-- .../src/altimate/tools/dbt-adapter-access.ts | 2 +- .../test/altimate/dbt-adapter-access.test.ts | 121 ++++++++++++++---- 3 files changed, 126 insertions(+), 37 deletions(-) diff --git a/packages/opencode/src/altimate/api/client.ts b/packages/opencode/src/altimate/api/client.ts index 25a78d8bd0..a7a668183e 100644 --- a/packages/opencode/src/altimate/api/client.ts +++ b/packages/opencode/src/altimate/api/client.ts @@ -1,6 +1,6 @@ import z from "zod" import path from "path" -import { rm } from "node:fs/promises" +import { rm, stat } from "node:fs/promises" import { Global } from "../../global" import { Filesystem } from "../../util/filesystem" import { currentCredentials } from "./credentials-context" @@ -86,11 +86,14 @@ export namespace AltimateApi { return Filesystem.exists(credentialsPath()) } + /** A `${env:NAME}` in the credentials file names a variable that isn't set. */ + class MissingEnvVar extends Error {} + function resolveEnvVars(obj: unknown): unknown { if (typeof obj === "string") { return obj.replace(/\$\{env:([^}]+)\}/g, (_, envVar) => { const value = process.env[envVar] - if (value === undefined) throw new Error(`Environment variable ${envVar} not found`) + if (value === undefined) throw new MissingEnvVar(`Environment variable ${envVar} not found`) return value }) } @@ -324,9 +327,18 @@ export namespace AltimateApi { timeoutMs: 15_000, } - /** `text` with every occurrence of `secret` replaced, so an error can be shown without the key. */ - function redact(text: string, secret: string): string { - return secret ? text.split(secret).join("[redacted]") : text + /** + * Why a request couldn't be sent, never quoting the error's text. Bun refuses a header value with a + * control character as a TypeError that quotes the value after trimming it, so no redaction of the + * stored key can be relied on: only the error's name and code are shown. + */ + function sendFailure(e: unknown): string { + if (e instanceof TypeError) + return "the request was refused before it was sent (TypeError): the stored API key or tenant name may not be a valid header value." + const word = (v: unknown) => (typeof v === "string" && /^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(v) ? v : undefined) + const name = (e instanceof Error && word(e.name)) || "Error" + const code = word((e as { code?: unknown } | null)?.code) + return code ? `${name} (${code}).` : `${name}.` } async function request( @@ -346,8 +358,7 @@ export namespace AltimateApi { // that raced a refused header leaves the header error, so match the reason, not the flag. if (e === controller.signal.reason || e === signal?.reason) throw e // Others can quote a header: Bun's check of a header value with CR/LF quotes `Bearer `. - const message = redact(e instanceof Error ? e.message : String(e), creds.altimateApiKey) - throw new Error(`API ${method} ${endpoint} could not be sent: ${message}`) + throw new Error(`API ${method} ${endpoint} could not be sent: ${sendFailure(e)}`) } } // altimate_change start — upstream_fix: bound every API request. Without a @@ -394,7 +405,9 @@ export namespace AltimateApi { if (fields.length === 0 || fields.includes("")) return "the file does not hold the credentials object." return `${fields.join(", ")} ${fields.length === 1 ? "is" : "are"} missing or not valid.` } - // A file system error or a missing ${env:NAME} variable: names a path or a variable, no value. + // The variable's name is the file's text, which can be a key written in its place. + if (e instanceof MissingEnvVar) return "an ${env:…} variable it refers to is not set." + // A file system error names a path, not a value. return e instanceof Error ? e.message : String(e) } @@ -403,7 +416,7 @@ export namespace AltimateApi { * returns the parsed JSON body. Endpoint functions in other files go through this. Fails with a * message naming the credentials file when none are stored or they can't be read. `signal` (a tool * call's `ctx.abort`) cancels the request as well as the 15 s timeout. No error it raises quotes the - * stored key. + * stored key or the credentials file's text. */ export async function apiRequest( method: string, @@ -417,7 +430,14 @@ export namespace AltimateApi { creds = await getCredentials() } catch (e) { const p = credentialsPath() - if (!(await Filesystem.exists(p))) + // Only a file that isn't there is "not stored": a directory without search permission hides it too. + const unseen = await stat(p).then( + () => undefined, + (err: NodeJS.ErrnoException) => err, + ) + if (unseen && unseen.code !== "ENOENT" && unseen.code !== "ENOTDIR") + throw new Error(`The Altimate credentials in ${p} can't be read (${unseen.code ?? unseen.name}).`) + if (unseen) throw new Error( `No Altimate credentials are stored: sign in to Altimate in altimate-code first (they are saved to ${p}).`, ) diff --git a/packages/opencode/src/altimate/tools/dbt-adapter-access.ts b/packages/opencode/src/altimate/tools/dbt-adapter-access.ts index 2fc2aba423..d51d2b4d2b 100644 --- a/packages/opencode/src/altimate/tools/dbt-adapter-access.ts +++ b/packages/opencode/src/altimate/tools/dbt-adapter-access.ts @@ -42,7 +42,7 @@ export async function dbtAdapterFor(ctx: Pick reject(new Error(`the dbt adapter didn't start within ${seconds} s`)), + () => reject(new Error(`the dbt adapter wasn't ready within ${seconds} s`)), dbtAdapterAccessInternals.adapterStartTimeoutMs, ) }) diff --git a/packages/opencode/test/altimate/dbt-adapter-access.test.ts b/packages/opencode/test/altimate/dbt-adapter-access.test.ts index ddcf0ea183..6e3d7958c6 100644 --- a/packages/opencode/test/altimate/dbt-adapter-access.test.ts +++ b/packages/opencode/test/altimate/dbt-adapter-access.test.ts @@ -2,7 +2,7 @@ // one gate the new dbt-adapter-backed tools go through, and the API helper for new endpoint files. The // dbt adapter is replaced through `dbtAdapterInternals`, so these tests need no Python or dbt. import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test" -import { mkdtemp, rm, writeFile } from "node:fs/promises" +import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises" import { realpathSync } from "node:fs" import os from "node:os" import path from "node:path" @@ -93,6 +93,25 @@ describe("feature tools in the allow-list", () => { expect(resultFailed(result)).toBe(true) } }) + + test("each placeholder still checks its arguments before it refuses", async () => { + for (const id of FEATURE_TOOLS) { + const tool = await initTool(EXPOSED[id] as any) + // A string where an object is expected fails every schema, whatever its required fields. + const failed = await Promise.resolve() + .then(() => tool.execute("not an object" as any, ctx)) + .then( + (result) => ({ result }), + (error: unknown) => ({ error }), + ) + if ("result" in failed) { + expect(failed.result.title).not.toBe(`${id}: not implemented`) + expect(resultFailed(failed.result)).toBe(true) + } else { + expect(String(failed.error)).toContain("invalid arguments") + } + } + }) }) describe("dbtAdapterFor", () => { @@ -157,7 +176,7 @@ describe("dbtAdapterFor", () => { dbtAdapterAccessInternals.adapterStartTimeoutMs = 20 try { const access = await dbtAdapterFor(ctx) - expect(access).toEqual({ refusal: "not_started", reason: "the dbt adapter didn't start within 0.02 s" }) + expect(access).toEqual({ refusal: "not_started", reason: "the dbt adapter wasn't ready within 0.02 s" }) } finally { dbtAdapterAccessInternals.adapterStartTimeoutMs = saved } @@ -224,7 +243,7 @@ describe("dbtAdapterFor", () => { dbtAdapterAccessInternals.adapterStartTimeoutMs = 20 try { const access = await Instance.provide({ directory: project, fn: () => dbtAdapterFor(ctx) }) - expect(access).toEqual({ refusal: "not_started", reason: "the dbt adapter didn't start within 0.02 s" }) + expect(access).toEqual({ refusal: "not_started", reason: "the dbt adapter wasn't ready within 0.02 s" }) expect(created).toBe(0) } finally { release() @@ -427,17 +446,53 @@ describe("AltimateApi.apiRequest", () => { expect(error.message).not.toContain("sk_SECRET123") }) - test("never shows the stored key when sending the request fails", async () => { - const key = "sk_SECRET123\r\nX: y" + const HEADER_REFUSED = + "could not be sent: the request was refused before it was sent (TypeError): the stored API key or tenant name may not be a valid header value." + + /** Every substring of `key` long enough to identify it, so a trimmed or split copy is caught too. */ + function expectNoPartOf(text: string, key: string) { + for (const part of key.split(/\s+/).filter((p) => p.length >= 4)) expect(text).not.toContain(part) + expect(text).not.toContain("Bearer") + } + + // The real fetch: Bun refuses a header value with CR/LF, quoting it after trimming its whitespace. + for (const key of [ + "sk_SECRET123\r\nX: y", + "sk_SECRET123ABCDEFGH\nPART2\n", + "sk_SECRET123ABCDEFGH\r\nX \t", + " sk_SECRET123ABCDEFGH\nPART2 ", + ]) { + test(`never shows any part of a key that isn't a valid header value: ${JSON.stringify(key)}`, async () => { + await Bun.write( + path.join(home, ".altimate", "altimate.json"), + JSON.stringify({ altimateUrl: "http://127.0.0.1:9", altimateInstanceName: "acme", altimateApiKey: key }), + ) + const viaRequest = await AltimateApi.apiRequest("GET", "/dbt/v1/x").catch((e: Error) => e) + expect(viaRequest).toBeInstanceOf(Error) + expect(viaRequest.message).toBe(`API GET /dbt/v1/x ${HEADER_REFUSED}`) + expectNoPartOf(`${viaRequest.message}\n${viaRequest.stack}`, key) + const viaList = (await AltimateApi.listDatamates().catch((e: Error) => e)) as Error + expect(viaList).toBeInstanceOf(Error) + expect(viaList.message).toBe(`API GET /datamates/ ${HEADER_REFUSED}`) + expectNoPartOf(`${viaList.message}\n${viaList.stack}`, key) + }) + } + + test("names a network failure by its code, never by the error's text", async () => { await Bun.write( path.join(home, ".altimate", "altimate.json"), - JSON.stringify({ altimateUrl: "http://127.0.0.1:9", altimateInstanceName: "acme", altimateApiKey: key }), + JSON.stringify({ altimateUrl: "http://127.0.0.1:9", altimateInstanceName: "acme", altimateApiKey: "k1" }), ) - // The real fetch: it rejects a header value with CR/LF, quoting the value. - const error = await AltimateApi.apiRequest("GET", "/dbt/v1/x").catch((e: Error) => e) - expect(error).toBeInstanceOf(Error) - expect(error.message).not.toContain("sk_SECRET123") - expect(error.message).toContain("API GET /dbt/v1/x could not be sent") + const original = globalThis.fetch + globalThis.fetch = (async () => { + throw Object.assign(new Error("Unable to connect: Bearer k1"), { code: "ConnectionRefused" }) + }) as unknown as typeof fetch + try { + const error = await AltimateApi.apiRequest("GET", "/dbt/v1/x").catch((e: Error) => e) + expect(error.message).toBe("API GET /dbt/v1/x could not be sent: Error (ConnectionRefused).") + } finally { + globalThis.fetch = original + } }) test("never shows the stored key when a header refusal races the caller's abort", async () => { @@ -459,33 +514,47 @@ describe("AltimateApi.apiRequest", () => { const error = await AltimateApi.apiRequest("GET", "/dbt/v1/x", undefined, controller.signal).catch( (e: Error) => e, ) - expect(error.message).toBe("API GET /dbt/v1/x could not be sent: bad header: 'Bearer [redacted]'") + expect(error.message).toBe(`API GET /dbt/v1/x ${HEADER_REFUSED}`) } finally { globalThis.fetch = original } }) - test("never shows the stored key from any fetch failure", async () => { + test("never quotes the credentials file when an ${env:…} variable it names isn't set", async () => { + const file = path.join(home, ".altimate", "altimate.json") await Bun.write( - path.join(home, ".altimate", "altimate.json"), + file, JSON.stringify({ - altimateUrl: "https://api.example.test", + altimateUrl: "https://x.test", altimateInstanceName: "acme", - altimateApiKey: "sk_SECRET123", + altimateApiKey: "${env:sk_SECRET123_UNSET}", }), ) - const original = globalThis.fetch - globalThis.fetch = (async (_url: string, init: RequestInit) => { - throw new TypeError(`bad header: '${(init.headers as Record).Authorization}'`) - }) as unknown as typeof fetch - try { - const error = await AltimateApi.apiRequest("GET", "/dbt/v1/x").catch((e: Error) => e) - expect(error.message).toBe("API GET /dbt/v1/x could not be sent: bad header: 'Bearer [redacted]'") - } finally { - globalThis.fetch = original - } + const error = await AltimateApi.apiRequest("GET", "/dbt/v1/x").catch((e: Error) => e) + expect(error.message).toBe( + `The Altimate credentials in ${file} can't be used: an \${env:…} variable it refers to is not set.`, + ) }) + test.skipIf(process.platform === "win32" || process.getuid?.() === 0)( + "says the credentials can't be read, not that none are stored, when their directory can't be searched", + async () => { + const dir = path.join(home, ".altimate") + const file = path.join(dir, "altimate.json") + await Bun.write( + file, + JSON.stringify({ altimateUrl: "https://x.test", altimateInstanceName: "a", altimateApiKey: "k" }), + ) + await chmod(dir, 0o600) + try { + const error = await AltimateApi.apiRequest("GET", "/dbt/v1/x").catch((e: Error) => e) + expect(error.message).toBe(`The Altimate credentials in ${file} can't be read (EACCES).`) + } finally { + await chmod(dir, 0o700) + } + }, + ) + test("a timed-out request says it timed out", async () => { await Bun.write( path.join(home, ".altimate", "altimate.json"), From 3a98dff47e9a501dae418bbe16098ee2fe742550 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 13:29:38 +0530 Subject: [PATCH 24/31] fix: a rejection with no reason is a send failure, not an abort Before either signal aborts, its reason is undefined, so a fetch that rejected with undefined matched it and was rethrown raw. Match a reason only once its signal has aborted. The cleanup test now also covers a timed-out and a cancelled call. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/api/client.ts | 4 +- .../test/altimate/dbt-adapter-access.test.ts | 79 +++++++++++++++---- 2 files changed, 68 insertions(+), 15 deletions(-) diff --git a/packages/opencode/src/altimate/api/client.ts b/packages/opencode/src/altimate/api/client.ts index a7a668183e..123630d58b 100644 --- a/packages/opencode/src/altimate/api/client.ts +++ b/packages/opencode/src/altimate/api/client.ts @@ -356,7 +356,9 @@ export namespace AltimateApi { } catch (e) { // A timeout or the caller's abort rejects with its own reason, which holds no header. An abort // that raced a refused header leaves the header error, so match the reason, not the flag. - if (e === controller.signal.reason || e === signal?.reason) throw e + // A signal that isn't aborted has no reason yet: a rejection with none is a send failure. + if ((controller.signal.aborted && e === controller.signal.reason) || (signal?.aborted && e === signal.reason)) + throw e // Others can quote a header: Bun's check of a header value with CR/LF quotes `Bearer `. throw new Error(`API ${method} ${endpoint} could not be sent: ${sendFailure(e)}`) } diff --git a/packages/opencode/test/altimate/dbt-adapter-access.test.ts b/packages/opencode/test/altimate/dbt-adapter-access.test.ts index 6e3d7958c6..d3a587135e 100644 --- a/packages/opencode/test/altimate/dbt-adapter-access.test.ts +++ b/packages/opencode/test/altimate/dbt-adapter-access.test.ts @@ -276,19 +276,26 @@ describe("dbtAdapterFor", () => { }) test("removes its abort listener and its timer whatever the outcome", async () => { - const controller = new AbortController() - const signal = controller.signal - let listening = 0 - const add = signal.addEventListener.bind(signal) - const remove = signal.removeEventListener.bind(signal) - signal.addEventListener = ((...a: Parameters) => { - if (a[0] === "abort") listening += 1 - return add(...a) - }) as typeof signal.addEventListener - signal.removeEventListener = ((...a: Parameters) => { - if (a[0] === "abort") listening -= 1 - return remove(...a) - }) as typeof signal.removeEventListener + /** A signal that counts the abort listeners still attached to it. */ + const tracked = () => { + const controller = new AbortController() + const signal = controller.signal + const state = { controller, signal, listening: 0 } + const add = signal.addEventListener.bind(signal) + const remove = signal.removeEventListener.bind(signal) + signal.addEventListener = ((...a: Parameters) => { + if (a[0] === "abort") state.listening += 1 + return add(...a) + }) as typeof signal.addEventListener + signal.removeEventListener = ((...a: Parameters) => { + if (a[0] === "abort") state.listening -= 1 + return remove(...a) + }) as typeof signal.removeEventListener + return state + } + const settled = tracked() + const cancelled = tracked() + const signal = settled.signal const timers = new Set() const set = globalThis.setTimeout const clear = globalThis.clearTimeout @@ -308,11 +315,37 @@ describe("dbtAdapterFor", () => { } resetDbtAdapter() expect((await dbtAdapterFor({ ...ctx, abort: signal })).refusal).toBe("not_started") + // Timed out. + dbtAdapterInternals.create = () => new Promise(() => {}) + resetDbtAdapter() + const saved = dbtAdapterAccessInternals.adapterStartTimeoutMs + dbtAdapterAccessInternals.adapterStartTimeoutMs = 20 + try { + expect(await dbtAdapterFor({ ...ctx, abort: signal })).toEqual({ + refusal: "not_started", + reason: "the dbt adapter wasn't ready within 0.02 s", + }) + } finally { + dbtAdapterAccessInternals.adapterStartTimeoutMs = saved + } + // Cancelled while waiting. + let entered = () => {} + const starting = new Promise((resolve) => (entered = resolve)) + dbtAdapterInternals.create = () => { + entered() + return new Promise(() => {}) + } + resetDbtAdapter() + const pending = dbtAdapterFor({ ...ctx, abort: cancelled.signal }) + await starting + cancelled.controller.abort(new Error("cancelled")) + await expect(pending).rejects.toThrow("cancelled") } finally { globalThis.setTimeout = set globalThis.clearTimeout = clear } - expect(listening).toBe(0) + expect(settled.listening).toBe(0) + expect(cancelled.listening).toBe(0) expect(timers.size).toBe(0) }) @@ -478,6 +511,24 @@ describe("AltimateApi.apiRequest", () => { }) } + test("a fetch that rejects with no reason is a send failure, not taken for an abort", async () => { + await Bun.write( + path.join(home, ".altimate", "altimate.json"), + JSON.stringify({ altimateUrl: "http://127.0.0.1:9", altimateInstanceName: "acme", altimateApiKey: "k1" }), + ) + const original = globalThis.fetch + globalThis.fetch = (() => Promise.reject(undefined)) as unknown as typeof fetch + try { + const error = await AltimateApi.apiRequest("GET", "/dbt/v1/x", undefined, new AbortController().signal).catch( + (e: unknown) => e, + ) + expect(error).toBeInstanceOf(Error) + expect((error as Error).message).toBe("API GET /dbt/v1/x could not be sent: Error.") + } finally { + globalThis.fetch = original + } + }) + test("names a network failure by its code, never by the error's text", async () => { await Bun.write( path.join(home, ".altimate", "altimate.json"), From 48a2af74451baeda45ccfa5614ad2aa94a635408 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 13:45:56 +0530 Subject: [PATCH 25/31] test(dbt-defer-state): assert the exact unreadable settings file the symlink case reports Co-Authored-By: Claude Sonnet 5.5 --- packages/opencode/test/altimate/dbt-defer-state.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/opencode/test/altimate/dbt-defer-state.test.ts b/packages/opencode/test/altimate/dbt-defer-state.test.ts index 4fb91c855c..9749aae901 100644 --- a/packages/opencode/test/altimate/dbt-defer-state.test.ts +++ b/packages/opencode/test/altimate/dbt-defer-state.test.ts @@ -324,7 +324,7 @@ describe("dbt_defer_state", () => { try { const result = await resolveDeferState(link) expect(result.enabled).toBe(false) - expect(result.reason).toContain("settings.json") + expect(result.reason).toContain(path.join(holder, ".vscode", "settings.json")) } finally { fs.rmSync(real, { recursive: true, force: true }) fs.rmSync(holder, { recursive: true, force: true }) From 686901d3514dded7d02c5a6ba7eb99e8f7d56d94 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 16:11:31 +0530 Subject: [PATCH 26/31] fix: a TypeError on send names the URL as a possible cause, not only the header values Co-Authored-By: Claude Sonnet 5.5 --- packages/opencode/src/altimate/api/client.ts | 2 +- packages/opencode/test/altimate/dbt-adapter-access.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/api/client.ts b/packages/opencode/src/altimate/api/client.ts index 123630d58b..669e2ecc2a 100644 --- a/packages/opencode/src/altimate/api/client.ts +++ b/packages/opencode/src/altimate/api/client.ts @@ -334,7 +334,7 @@ export namespace AltimateApi { */ function sendFailure(e: unknown): string { if (e instanceof TypeError) - return "the request was refused before it was sent (TypeError): the stored API key or tenant name may not be a valid header value." + return "the request was refused before it was sent (TypeError): the stored Altimate URL, API key or tenant name may be invalid." const word = (v: unknown) => (typeof v === "string" && /^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(v) ? v : undefined) const name = (e instanceof Error && word(e.name)) || "Error" const code = word((e as { code?: unknown } | null)?.code) diff --git a/packages/opencode/test/altimate/dbt-adapter-access.test.ts b/packages/opencode/test/altimate/dbt-adapter-access.test.ts index c59e8da396..203051c0de 100644 --- a/packages/opencode/test/altimate/dbt-adapter-access.test.ts +++ b/packages/opencode/test/altimate/dbt-adapter-access.test.ts @@ -490,7 +490,7 @@ describe("AltimateApi.apiRequest", () => { }) const HEADER_REFUSED = - "could not be sent: the request was refused before it was sent (TypeError): the stored API key or tenant name may not be a valid header value." + "could not be sent: the request was refused before it was sent (TypeError): the stored Altimate URL, API key or tenant name may be invalid." /** Every substring of `key` long enough to identify it, so a trimmed or split copy is caught too. */ function expectNoPartOf(text: string, key: string) { From be4fc52d11642cab08713c6f2ab7590fc9634e0c Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 21:00:29 +0530 Subject: [PATCH 27/31] test: the placeholder checks skip dbt_defer_state, which is implemented Co-Authored-By: Claude Sonnet 5.5 --- packages/opencode/test/altimate/dbt-adapter-access.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/opencode/test/altimate/dbt-adapter-access.test.ts b/packages/opencode/test/altimate/dbt-adapter-access.test.ts index 4317672e42..f93d560370 100644 --- a/packages/opencode/test/altimate/dbt-adapter-access.test.ts +++ b/packages/opencode/test/altimate/dbt-adapter-access.test.ts @@ -84,6 +84,7 @@ describe("feature tools in the allow-list", () => { test("each placeholder answers that it isn't implemented, as a failure", async () => { for (const id of FEATURE_TOOLS) { + if (id === "dbt_defer_state") continue // implemented in its own package const tool = await initTool(EXPOSED[id] as any) expect(tool.id).toBe(id) const result = await tool.execute(MINIMAL_ARGS[id], ctx) @@ -96,6 +97,7 @@ describe("feature tools in the allow-list", () => { test("each placeholder still checks its arguments before it refuses", async () => { for (const id of FEATURE_TOOLS) { + if (id === "dbt_defer_state") continue // implemented in its own package const tool = await initTool(EXPOSED[id] as any) // A string where an object is expected fails every schema, whatever its required fields. const failed = await Promise.resolve() From 7003d2d61b88abe230189128739f2a01ba57ba3a Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 21:24:06 +0530 Subject: [PATCH 28/31] fix: a settings BOM, YAML merge keys and an output named default are read as dbt and VS Code read them Co-Authored-By: Claude Sonnet 5.5 --- .../src/altimate/tools/dbt-defer-state.ts | 9 ++++++-- .../test/altimate/dbt-defer-state.test.ts | 21 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/tools/dbt-defer-state.ts b/packages/opencode/src/altimate/tools/dbt-defer-state.ts index 2bbfef2ef2..20fb7f5a04 100644 --- a/packages/opencode/src/altimate/tools/dbt-defer-state.ts +++ b/packages/opencode/src/altimate/tools/dbt-defer-state.ts @@ -60,6 +60,8 @@ function readSettings(file: string): Record | typeof UNREADABLE } catch (err) { return (err as NodeJS.ErrnoException).code === "ENOENT" || (err as NodeJS.ErrnoException).code === "ENOTDIR" ? undefined : UNREADABLE } + // VS Code reads a file with a leading byte order mark as it reads one without. + text = text.replace(/^\uFEFF/, "") // An empty or whitespace-only file is a settings file with nothing in it. if (text.trim() === "") return {} const errors: ParseError[] = [] @@ -140,7 +142,8 @@ function profilesFile(projectDir: string): string | undefined { async function parseYaml(text: string): Promise { const mod = await import("yaml") - return (mod.default ?? mod).parse(text) + // dbt reads YAML with PyYAML, which merges `<<` keys. + return (mod.default ?? mod).parse(text, { merge: true }) } /** The project's profile name, that profile's default `target` and its output names. */ @@ -161,8 +164,10 @@ export async function readProfileTargets(projectDir: string) { const profile = profiles?.[out.profile] if (profile && typeof profile === "object") { const target = resolveEnvVars(profile.target) - if (typeof target === "string" && target !== "") out.defaultTarget = target if (profile.outputs && typeof profile.outputs === "object") out.targets = Object.keys(profile.outputs) + if (typeof target === "string" && target !== "") out.defaultTarget = target + // With no `target`, dbt runs the output named "default". + else if (profile.target === undefined && out.targets.includes("default")) out.defaultTarget = "default" } } catch { // An unreadable profiles.yml leaves the target unknown. diff --git a/packages/opencode/test/altimate/dbt-defer-state.test.ts b/packages/opencode/test/altimate/dbt-defer-state.test.ts index 9749aae901..8995739ab9 100644 --- a/packages/opencode/test/altimate/dbt-defer-state.test.ts +++ b/packages/opencode/test/altimate/dbt-defer-state.test.ts @@ -51,6 +51,27 @@ describe("dbt_defer_state", () => { }) }) + test("a settings file with a byte order mark is read like one without", async () => { + write(".vscode/settings.json", "\uFEFF" + JSON.stringify({ "dbt.deferConfigPerProject": { analytics: { deferToProduction: true, manifestPathForDeferral: "${workspaceFolder}/prod-state" } } })) + const result = await resolveDeferState(path.join(root, "analytics")) + expect(result).toMatchObject({ enabled: true, mode: "local" }) + }) + + test("a profile that inherits its target and outputs through a YAML merge key keeps them", async () => { + write("profiles/profiles.yml", "base: &base\n target: dev\n outputs:\n dev:\n type: duckdb\nshop:\n <<: *base\n") + settings({ analytics: { deferToProduction: true, manifestPathForDeferral: "${workspaceFolder}/prod-state" } }) + const result = await resolveDeferState(path.join(root, "analytics")) + expect(result.defaultTarget).toBe("dev") + expect(result.targets).toEqual(["dev"]) + }) + + test("a profile with an output named default and no target runs that output, as dbt does", async () => { + write("profiles/profiles.yml", "shop:\n outputs:\n default:\n type: duckdb\n prod:\n type: duckdb\n") + settings({ analytics: { deferToProduction: true, manifestPathForDeferral: "${workspaceFolder}/prod-state" } }) + const result = await resolveDeferState(path.join(root, "analytics")) + expect(result.defaultTarget).toBe("default") + }) + test("defer off still returns the configured state dir, so a session can switch it on", async () => { settings({ analytics: { deferToProduction: false, manifestPathForDeferral: "${workspaceFolder}/prod-state" } }) const result = await resolveDeferState(path.join(root, "analytics")) From a9a9cfdb0c38f3c89991e13290d67116387285b2 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 21:48:12 +0530 Subject: [PATCH 29/31] fix: a profile target written as an expression this does not evaluate is unknown Co-Authored-By: Claude Sonnet 5.5 --- packages/opencode/src/altimate/tools/dbt-defer-state.ts | 3 ++- packages/opencode/test/altimate/dbt-defer-state.test.ts | 8 ++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/packages/opencode/src/altimate/tools/dbt-defer-state.ts b/packages/opencode/src/altimate/tools/dbt-defer-state.ts index 20fb7f5a04..2e6382ebab 100644 --- a/packages/opencode/src/altimate/tools/dbt-defer-state.ts +++ b/packages/opencode/src/altimate/tools/dbt-defer-state.ts @@ -165,7 +165,8 @@ export async function readProfileTargets(projectDir: string) { if (profile && typeof profile === "object") { const target = resolveEnvVars(profile.target) if (profile.outputs && typeof profile.outputs === "object") out.targets = Object.keys(profile.outputs) - if (typeof target === "string" && target !== "") out.defaultTarget = target + // A target dbt would render from an expression this does not evaluate is unknown, not that text. + if (typeof target === "string" && target !== "" && !/\{[{%#]/.test(target)) out.defaultTarget = target // With no `target`, dbt runs the output named "default". else if (profile.target === undefined && out.targets.includes("default")) out.defaultTarget = "default" } diff --git a/packages/opencode/test/altimate/dbt-defer-state.test.ts b/packages/opencode/test/altimate/dbt-defer-state.test.ts index 8995739ab9..3c55124908 100644 --- a/packages/opencode/test/altimate/dbt-defer-state.test.ts +++ b/packages/opencode/test/altimate/dbt-defer-state.test.ts @@ -65,6 +65,14 @@ describe("dbt_defer_state", () => { expect(result.targets).toEqual(["dev"]) }) + test("a target written as a Jinja expression this does not evaluate is unknown, not that text", async () => { + write("profiles/profiles.yml", "shop:\n target: '{{ env_var(\"DEFER_TEST_UNSET_ENV\", \"DEV\") | lower }}'\n outputs:\n dev:\n type: duckdb\n") + settings({ analytics: { deferToProduction: true, manifestPathForDeferral: "${workspaceFolder}/prod-state" } }) + const result = await resolveDeferState(path.join(root, "analytics")) + expect(result.defaultTarget).toBeUndefined() + expect(result.targets).toEqual(["dev"]) + }) + test("a profile with an output named default and no target runs that output, as dbt does", async () => { write("profiles/profiles.yml", "shop:\n outputs:\n default:\n type: duckdb\n prod:\n type: duckdb\n") settings({ analytics: { deferToProduction: true, manifestPathForDeferral: "${workspaceFolder}/prod-state" } }) From 1e976bf84f15814bac355815e3c2f185ff229426 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 22:54:27 +0530 Subject: [PATCH 30/31] refactor: keep the defer-state PR to its own files; no edits to dbt-profiles or the foundation test Co-Authored-By: Claude Sonnet 5.5 --- .../native/connections/dbt-profiles.ts | 8 +++--- .../src/altimate/tools/dbt-defer-state.ts | 27 +++++++++++++++++-- .../test/altimate/dbt-adapter-access.test.ts | 2 -- .../test/altimate/dbt-defer-state.test.ts | 2 +- 4 files changed, 30 insertions(+), 9 deletions(-) diff --git a/packages/opencode/src/altimate/native/connections/dbt-profiles.ts b/packages/opencode/src/altimate/native/connections/dbt-profiles.ts index e90c8edf9a..e36b5bd0f6 100644 --- a/packages/opencode/src/altimate/native/connections/dbt-profiles.ts +++ b/packages/opencode/src/altimate/native/connections/dbt-profiles.ts @@ -53,11 +53,11 @@ const KEY_MAP: Record = { } /** Resolve Jinja {{ env_var('NAME') }} and {{ env_var('NAME', 'default') }} patterns. */ -export function resolveEnvVars(value: unknown): unknown { +function resolveEnvVars(value: unknown): unknown { if (typeof value !== "string") return value return value.replace( - /\{\{\s*env_var\s*\(\s*(['"])((?:(?!\1)[\s\S])+)\1\s*(?:,\s*(['"])((?:(?!\3)[\s\S])*)\3\s*)?\)\s*\}\}/g, - (_match, _q1: string, envName: string, _q2?: string, defaultValue?: string) => { + /\{\{\s*env_var\s*\(\s*'([^']+)'\s*(?:,\s*'([^']*)'\s*)?\)\s*\}\}/g, + (_match, envName: string, defaultValue?: string) => { return process.env[envName] ?? defaultValue ?? "" }, ) @@ -102,7 +102,7 @@ function mapConfig(dbtType: string, dbtConfig: Record): Connect * 3. Project-local profiles.yml (in dbt project root) * 4. ~/.dbt/profiles.yml (default) */ -export function resolveProfilesPath(explicitPath?: string, projectDir?: string): string { +function resolveProfilesPath(explicitPath?: string, projectDir?: string): string { if (explicitPath) return explicitPath const envDir = process.env.DBT_PROFILES_DIR diff --git a/packages/opencode/src/altimate/tools/dbt-defer-state.ts b/packages/opencode/src/altimate/tools/dbt-defer-state.ts index 2e6382ebab..6ade98b796 100644 --- a/packages/opencode/src/altimate/tools/dbt-defer-state.ts +++ b/packages/opencode/src/altimate/tools/dbt-defer-state.ts @@ -1,9 +1,32 @@ import z from "zod" import fs from "fs" +import os from "os" import path from "path" import { createScanner, parse as parseJsonc, stripComments, type ParseError } from "jsonc-parser" import { Tool } from "../../tool/tool" -import { resolveEnvVars, resolveProfilesPath } from "../native/connections/dbt-profiles" + +/** Resolve Jinja `{{ env_var('NAME') }}` and `{{ env_var('NAME', 'default') }}`, in single or double quotes. */ +export function resolveEnvVars(value: unknown): unknown { + if (typeof value !== "string") return value + return value.replace( + /\{\{\s*env_var\s*\(\s*(['"])((?:(?!\1)[\s\S])+)\1\s*(?:,\s*(['"])((?:(?!\3)[\s\S])*)\3\s*)?\)\s*\}\}/g, + (_match, _q1: string, envName: string, _q2?: string, defaultValue?: string) => process.env[envName] ?? defaultValue ?? "", + ) +} + +/** dbt's profiles.yml lookup: DBT_PROFILES_DIR, then the project folder, then ~/.dbt. */ +function resolveProfilesPath(projectDir?: string): string { + const envDir = process.env.DBT_PROFILES_DIR + if (envDir) { + const envPath = path.join(envDir, "profiles.yml") + if (fs.existsSync(envPath)) return envPath + } + if (projectDir) { + const projectPath = path.join(projectDir, "profiles.yml") + if (fs.existsSync(projectPath)) return projectPath + } + return path.join(os.homedir(), ".dbt", "profiles.yml") +} // The Power User setting this tool reads: `dbt.deferConfigPerProject`, keyed by the dbt project's path // relative to its workspace folder. @@ -136,7 +159,7 @@ function lookupDeferSetting(projectDir: string, workspaceDir?: string) { } function profilesFile(projectDir: string): string | undefined { - const file = resolveProfilesPath(undefined, projectDir) + const file = resolveProfilesPath(projectDir) return fs.existsSync(file) ? file : undefined } diff --git a/packages/opencode/test/altimate/dbt-adapter-access.test.ts b/packages/opencode/test/altimate/dbt-adapter-access.test.ts index f93d560370..4317672e42 100644 --- a/packages/opencode/test/altimate/dbt-adapter-access.test.ts +++ b/packages/opencode/test/altimate/dbt-adapter-access.test.ts @@ -84,7 +84,6 @@ describe("feature tools in the allow-list", () => { test("each placeholder answers that it isn't implemented, as a failure", async () => { for (const id of FEATURE_TOOLS) { - if (id === "dbt_defer_state") continue // implemented in its own package const tool = await initTool(EXPOSED[id] as any) expect(tool.id).toBe(id) const result = await tool.execute(MINIMAL_ARGS[id], ctx) @@ -97,7 +96,6 @@ describe("feature tools in the allow-list", () => { test("each placeholder still checks its arguments before it refuses", async () => { for (const id of FEATURE_TOOLS) { - if (id === "dbt_defer_state") continue // implemented in its own package const tool = await initTool(EXPOSED[id] as any) // A string where an object is expected fails every schema, whatever its required fields. const failed = await Promise.resolve() diff --git a/packages/opencode/test/altimate/dbt-defer-state.test.ts b/packages/opencode/test/altimate/dbt-defer-state.test.ts index 3c55124908..b633c8799a 100644 --- a/packages/opencode/test/altimate/dbt-defer-state.test.ts +++ b/packages/opencode/test/altimate/dbt-defer-state.test.ts @@ -5,7 +5,7 @@ import path from "path" import { Effect } from "effect" import type { Tool } from "../../src/tool/tool" import { SessionID, MessageID } from "../../src/session/schema" -import { resolveEnvVars } from "../../src/altimate/native/connections/dbt-profiles" +import { resolveEnvVars } from "../../src/altimate/tools/dbt-defer-state" import { DbtDeferStateTool, resolveDeferState, findDeferSetting } from "../../src/altimate/tools/dbt-defer-state" import { initTool } from "./tool-fixture" From 7a546aeae16086d2725ac0741e2e920d224acbab Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Wed, 18 Nov 2026 07:00:50 +0530 Subject: [PATCH 31/31] fix: a profile written as an expression is unknown, and the env_var test clears the variables it depends on Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/tools/dbt-defer-state.ts | 3 ++- .../test/altimate/dbt-defer-state.test.ts | 18 ++++++++++++++++-- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/packages/opencode/src/altimate/tools/dbt-defer-state.ts b/packages/opencode/src/altimate/tools/dbt-defer-state.ts index 6ade98b796..c1ca71787b 100644 --- a/packages/opencode/src/altimate/tools/dbt-defer-state.ts +++ b/packages/opencode/src/altimate/tools/dbt-defer-state.ts @@ -175,7 +175,8 @@ export async function readProfileTargets(projectDir: string) { try { const project = await parseYaml(fs.readFileSync(path.join(projectDir, "dbt_project.yml"), "utf-8")) const profile = resolveEnvVars(project?.profile) - if (typeof profile === "string" && profile !== "") out.profile = profile + // A profile dbt would render from an expression this does not evaluate is unknown, not that text. + if (typeof profile === "string" && profile !== "" && !/\{[{%#]/.test(profile)) out.profile = profile } catch { return out } diff --git a/packages/opencode/test/altimate/dbt-defer-state.test.ts b/packages/opencode/test/altimate/dbt-defer-state.test.ts index b633c8799a..4fa0fb9500 100644 --- a/packages/opencode/test/altimate/dbt-defer-state.test.ts +++ b/packages/opencode/test/altimate/dbt-defer-state.test.ts @@ -202,14 +202,28 @@ describe("dbt_defer_state", () => { test("a project or target written as env_var() is resolved, with its default", async () => { write("analytics/dbt_project.yml", "name: shop\nprofile: \"{{ env_var('DEFER_TEST_PROFILE', 'shop') }}\"\n") write("profiles/profiles.yml", "shop:\n target: \"{{ env_var('DEFER_TEST_TARGET', 'dev') }}\"\n outputs:\n dev:\n type: duckdb\n qa:\n type: duckdb\n") + const saved = { profile: process.env.DEFER_TEST_PROFILE, target: process.env.DEFER_TEST_TARGET } + delete process.env.DEFER_TEST_PROFILE process.env.DEFER_TEST_TARGET = "qa" try { const result = await resolveDeferState(path.join(root, "analytics")) expect(result).toMatchObject({ profile: "shop", defaultTarget: "qa", targets: ["dev", "qa"] }) - } finally { delete process.env.DEFER_TEST_TARGET + expect((await resolveDeferState(path.join(root, "analytics"))).defaultTarget).toBe("dev") + } finally { + if (saved.profile === undefined) delete process.env.DEFER_TEST_PROFILE + else process.env.DEFER_TEST_PROFILE = saved.profile + if (saved.target === undefined) delete process.env.DEFER_TEST_TARGET + else process.env.DEFER_TEST_TARGET = saved.target } - expect((await resolveDeferState(path.join(root, "analytics"))).defaultTarget).toBe("dev") + }) + + test("a profile written as an expression this does not evaluate is unknown, not that text", async () => { + write("analytics/dbt_project.yml", "name: shop\nprofile: \"{{ var('p') }}\"\n") + write("profiles/profiles.yml", "shop:\n target: dev\n outputs:\n dev:\n type: duckdb\n") + const result = await resolveDeferState(path.join(root, "analytics")) + expect(result.profile).toBeUndefined() + expect(result.targets).toEqual([]) }) test("double-quoted env_var() names and defaults are resolved too", async () => {