From b7cfc0426d60963a83f22a8f5c6053c7b7fce8e4 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Fri, 13 Nov 2026 16:30:43 +0530 Subject: [PATCH 01/11] 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/11] 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/11] 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/11] 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/11] 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/11] 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/11] 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/11] 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/11] 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/11] 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/11] 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"))