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 1ee47f392ac908d8f254acd1d4e67581c5ff7614 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Fri, 13 Nov 2026 16:47:48 +0530 Subject: [PATCH 02/11] feat(tool): dbt_run_results reads the last dbt run's id, timings and per-node results Co-Authored-By: Claude Sonnet 5.5 --- .../src/altimate/tools/dbt-run-results.ts | 120 ++++++++++++++- .../test/altimate/dbt-run-results.test.ts | 143 ++++++++++++++++++ 2 files changed, 257 insertions(+), 6 deletions(-) create mode 100644 packages/opencode/test/altimate/dbt-run-results.test.ts diff --git a/packages/opencode/src/altimate/tools/dbt-run-results.ts b/packages/opencode/src/altimate/tools/dbt-run-results.ts index 86e68a1668..c3802a5f2e 100644 --- a/packages/opencode/src/altimate/tools/dbt-run-results.ts +++ b/packages/opencode/src/altimate/tools/dbt-run-results.ts @@ -1,16 +1,124 @@ +import fs from "node:fs/promises" import z from "zod" import { Tool } from "../../tool/tool" +import { projectRoot } from "../native/connections/registry" +import { readRunResults } from "../validators/validator-utils" + +/** A message longer than this is cut: a build of thousands of nodes must stay readable and small. */ +const MAX_MESSAGE = 2000 + +export interface DbtRunResultRow { + uniqueId: string + name: string + status: string + executionTimeSec: number | null + message: string | null +} + +export interface DbtRunResultsView { + found: boolean + invocationId: string | null + command: string | null + elapsedSec: number | null + /** The artifact's modification time, ISO 8601. */ + completedAt: string | null + results: DbtRunResultRow[] +} + +const NONE: DbtRunResultsView = { + found: false, + invocationId: null, + command: null, + elapsedSec: null, + completedAt: null, + results: [], +} + +/** A test's unique id ends in a hash (`test.shop.not_null_orders_id.f3a1c`): its name is the part before it. */ +function displayName(uniqueId: string, name: string): string { + const parts = uniqueId.split(".") + return parts[0] === "test" && parts.length === 4 ? (parts[2] ?? name) : name +} + +const num = (value: unknown): number | null => (typeof value === "number" && Number.isFinite(value) ? value : null) + +function cut(text: string | null): string | null { + if (text === null) return null + return text.length > MAX_MESSAGE ? `${text.slice(0, MAX_MESSAGE)}…` : text +} + +/** + * The last dbt run of a project: `readRunResults` gives the artifact's path, its command and its rows; + * the invocation id, the elapsed time and each row's execution time are read from the same file here, + * because the validators that share `readRunResults` have no use for them. + */ +export async function readRunView(dbtRoot: string): Promise { + const artifact = await readRunResults(dbtRoot) + if (!artifact) return NONE + let raw: { metadata?: unknown; elapsed_time?: unknown; results?: unknown } = {} + try { + raw = JSON.parse(await fs.readFile(artifact.path, "utf8")) + } catch { + // The file changed or went away after it was parsed: the rows are still good, the timings are not known. + } + const meta = typeof raw.metadata === "object" && raw.metadata !== null ? (raw.metadata as Record) : {} + const invocation = typeof meta["invocation_id"] === "string" && meta["invocation_id"] ? meta["invocation_id"] : null + // `readRunResults` keeps the rows that are objects with a unique_id; the same rows, in the same order, here. + const rows = (Array.isArray(raw.results) ? raw.results : []).filter( + (row): row is Record => + typeof row === "object" && row !== null && typeof (row as Record)["unique_id"] === "string" && !!(row as Record)["unique_id"], + ) + return { + found: true, + invocationId: invocation, + command: artifact.command, + elapsedSec: num(raw.elapsed_time), + completedAt: new Date(artifact.mtimeMs).toISOString(), + results: artifact.results.map((node, at) => ({ + uniqueId: node.uniqueId, + name: displayName(node.uniqueId, node.name), + status: node.status, + executionTimeSec: rows[at]?.["unique_id"] === node.uniqueId ? num(rows[at]?.["execution_time"]) : null, + message: cut(node.message), + })), + } +} 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.", + description: + "Read the last dbt run of a project from its target/run_results.json: the invocation id, the dbt command, the elapsed seconds, when it finished, and one row per node with its status, execution seconds and message. Read-only; runs nothing. A compile or parse writes success rows without building anything, so look at `command`.", parameters: z.object({ - project_dir: z.string().optional().describe("dbt project folder (default: the dbt project found from the working directory)"), + project_dir: z + .string() + .optional() + .describe("The dbt project folder (default: the project the session's directory is in)"), }), - async execute() { + async execute(args) { + const root = args.project_dir ?? (await defaultRoot()) + const view = await readRunView(root) + if (!view.found) { + return { + title: "dbt run results: none", + metadata: { ...view }, + output: `No run_results.json under ${root}: no dbt command has written one there yet.`, + } + } + const failed = view.results.filter((row) => !["success", "pass", "warn"].includes(row.status)) return { - title: "dbt_run_results: not implemented", - metadata: { success: false }, - output: "dbt_run_results is not implemented in this build of altimate-code yet.", + title: `dbt ${view.command ?? "run"}: ${view.results.length - failed.length}/${view.results.length} ok`, + metadata: { ...view }, + output: [ + `dbt ${view.command ?? "(unknown command)"} · invocation ${view.invocationId ?? "unknown"} · ${view.elapsedSec ?? "?"}s · ${view.completedAt}`, + ...view.results.map( + (row) => `${row.status} ${row.name} ${row.executionTimeSec ?? "-"}s${row.message ? ` · ${row.message}` : ""}`, + ), + ].join("\n"), } }, }) + +async function defaultRoot(): Promise { + const { findProjectRoot } = await import("../../../../dbt-tools/src/config") + const base = projectRoot() + return findProjectRoot(base) ?? base +} diff --git a/packages/opencode/test/altimate/dbt-run-results.test.ts b/packages/opencode/test/altimate/dbt-run-results.test.ts new file mode 100644 index 0000000000..d6db3e18eb --- /dev/null +++ b/packages/opencode/test/altimate/dbt-run-results.test.ts @@ -0,0 +1,143 @@ +// dbt_run_results reads the last run of a project from fixture run_results.json files: a build +// (nodes that ran), a compile (success rows that ran nothing) and no file at all. No dbt, no warehouse. +import { afterAll, beforeAll, describe, expect, test } from "bun:test" +import { mkdtemp, mkdir, rm, utimes, writeFile } from "node:fs/promises" +import os from "node:os" +import path from "node:path" +import { Effect } from "effect" +import { SessionID, MessageID } from "@/session/schema" +import type { Tool } from "@/tool/tool" +import { DbtRunResultsTool } from "@/altimate/tools/dbt-run-results" +import { initTool } from "./tool-fixture" + +const ctx: Tool.Context = { + sessionID: SessionID.make("ses_dbt_run_results"), + messageID: MessageID.make("msg_dbt_run_results"), + agent: "analyst", + abort: new AbortController().signal, + messages: [], + metadata: () => Effect.void, + ask: () => Effect.void, +} + +const BUILD = { + metadata: { invocation_id: "11111111-aaaa-bbbb-cccc-000000000001" }, + args: { which: "build" }, + elapsed_time: 12.5, + results: [ + { unique_id: "model.shop.stg_orders", status: "error", message: "Database Error: relation missing", execution_time: 1.25 }, + { unique_id: "model.shop.fct_sales", status: "success", message: "CREATE TABLE (10 rows)", execution_time: 3.5 }, + { unique_id: "test.shop.not_null_orders_id.abc", status: "pass", message: null, execution_time: 0.5 }, + { unique_id: "model.shop.dim_accounts.v2", status: "skipped", message: "SKIP", execution_time: 0 }, + ], +} + +const COMPILE = { + metadata: { invocation_id: "22222222-aaaa-bbbb-cccc-000000000002" }, + args: { which: "compile" }, + elapsed_time: 2, + results: [{ unique_id: "model.shop.fct_sales", status: "success", message: null, execution_time: 0.01 }], +} + +let root: string +const run = async (dir: string | undefined) => + (await initTool(DbtRunResultsTool)).execute(dir === undefined ? {} : { project_dir: dir }, ctx) + +async function project(name: string, artifact?: unknown) { + const dir = path.join(root, name) + await mkdir(path.join(dir, "target"), { recursive: true }) + await writeFile(path.join(dir, "dbt_project.yml"), `name: ${name}\n`) + if (artifact !== undefined) await writeFile(path.join(dir, "target", "run_results.json"), JSON.stringify(artifact)) + return dir +} + +beforeAll(async () => { + root = await mkdtemp(path.join(os.tmpdir(), "dbt-run-results-")) +}) +afterAll(async () => { + await rm(root, { recursive: true, force: true }) +}) + +describe("dbt_run_results", () => { + test("a build: invocation id, command, elapsed seconds, per-node status, seconds and message", async () => { + const dir = await project("build", BUILD) + const when = new Date("2026-11-01T10:00:00.000Z") + await utimes(path.join(dir, "target", "run_results.json"), when, when) + + const result = await run(dir) + + expect(result.metadata).toEqual({ + truncated: false, + found: true, + invocationId: "11111111-aaaa-bbbb-cccc-000000000001", + command: "build", + elapsedSec: 12.5, + completedAt: "2026-11-01T10:00:00.000Z", + results: [ + { uniqueId: "model.shop.stg_orders", name: "stg_orders", status: "error", executionTimeSec: 1.25, message: "Database Error: relation missing" }, + { uniqueId: "model.shop.fct_sales", name: "fct_sales", status: "success", executionTimeSec: 3.5, message: "CREATE TABLE (10 rows)" }, + { uniqueId: "test.shop.not_null_orders_id.abc", name: "not_null_orders_id", status: "pass", executionTimeSec: 0.5, message: null }, + { uniqueId: "model.shop.dim_accounts.v2", name: "dim_accounts", status: "skipped", executionTimeSec: 0, message: "SKIP" }, + ], + }) + expect(result.title).toBe("dbt build: 2/4 ok") + expect(result.output).toContain("error stg_orders 1.25s") + }) + + test("a compile is reported as a compile: its success rows ran nothing", async () => { + const dir = await project("compile", COMPILE) + + const result = await run(dir) + + expect((result.metadata as any).command).toBe("compile") + expect((result.metadata as any).invocationId).toBe("22222222-aaaa-bbbb-cccc-000000000002") + expect((result.metadata as any).results).toHaveLength(1) + }) + + test("no run_results.json: found is false and the answer is empty, not an error", async () => { + const dir = await project("empty") + + const result = await run(dir) + + expect(result.metadata).toEqual({ + truncated: false, + found: false, + invocationId: null, + command: null, + elapsedSec: null, + completedAt: null, + results: [], + }) + expect(result.title).toBe("dbt run results: none") + }) + + test("an artifact without an invocation id or timings keeps its rows", async () => { + const dir = await project("bare", { args: { which: "run" }, results: [{ unique_id: "model.shop.a", status: "success" }] }) + + const result = await run(dir) + + expect(result.metadata).toEqual({ + truncated: false, + found: true, + invocationId: null, + command: "run", + elapsedSec: null, + completedAt: expect.any(String), + results: [{ uniqueId: "model.shop.a", name: "a", status: "success", executionTimeSec: null, message: null }], + }) + }) + + test("a long message is cut", async () => { + const dir = await project("long", { + metadata: { invocation_id: "x" }, + args: { which: "run" }, + results: [{ unique_id: "model.shop.a", status: "error", message: "e".repeat(5000), execution_time: 1 }], + }) + + const result = await run(dir) + + const message = (result.metadata as any).results[0].message as string + expect(message.length).toBeLessThan(2100) + expect(message.endsWith("…")).toBe(true) + }) +}) From 21d0494cfbb1c87a2b1b3ba6e347f4f1be149856 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Fri, 13 Nov 2026 17:01:49 +0530 Subject: [PATCH 03/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 3728f952688110829244fec8513b0bc1346c36c7 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Fri, 13 Nov 2026 17:26:35 +0530 Subject: [PATCH 04/11] fix(tool): dbt_run_results reads one coherent run, bounds its answer and finds the configured project Co-Authored-By: Claude Sonnet 5.5 --- .../src/altimate/tools/dbt-run-results.ts | 108 ++++++++++++------ .../test/altimate/dbt-adapter-access.test.ts | 4 +- .../test/altimate/dbt-run-results.test.ts | 80 ++++++++++++- 3 files changed, 153 insertions(+), 39 deletions(-) diff --git a/packages/opencode/src/altimate/tools/dbt-run-results.ts b/packages/opencode/src/altimate/tools/dbt-run-results.ts index c3802a5f2e..7a3c66398d 100644 --- a/packages/opencode/src/altimate/tools/dbt-run-results.ts +++ b/packages/opencode/src/altimate/tools/dbt-run-results.ts @@ -1,11 +1,14 @@ import fs from "node:fs/promises" +import path from "node:path" import z from "zod" import { Tool } from "../../tool/tool" import { projectRoot } from "../native/connections/registry" -import { readRunResults } from "../validators/validator-utils" +import { isFailedRunStatus, readRunResults } from "../validators/validator-utils" /** A message longer than this is cut: a build of thousands of nodes must stay readable and small. */ const MAX_MESSAGE = 2000 +/** The rows one answer carries: a plugin reads at most 4 MiB of it, so a bigger build is counted, not listed. */ +const MAX_ROWS = 200 export interface DbtRunResultRow { uniqueId: string @@ -22,6 +25,11 @@ export interface DbtRunResultsView { elapsedSec: number | null /** The artifact's modification time, ISO 8601. */ completedAt: string | null + /** Every node dbt reported; `results` holds at most MAX_ROWS of them, the failures first. */ + total: number + passed: number + failed: number + skipped: number results: DbtRunResultRow[] } @@ -31,15 +39,22 @@ const NONE: DbtRunResultsView = { command: null, elapsedSec: null, completedAt: null, + total: 0, + passed: 0, + failed: 0, + skipped: 0, results: [], } /** A test's unique id ends in a hash (`test.shop.not_null_orders_id.f3a1c`): its name is the part before it. */ function displayName(uniqueId: string, name: string): string { const parts = uniqueId.split(".") - return parts[0] === "test" && parts.length === 4 ? (parts[2] ?? name) : name + return parts[0] === "test" && parts.length === 4 ? (parts[2] ?? name).toLowerCase() : name } +/** Statuses of a node dbt did not run. */ +const NOT_RUN = new Set(["skipped", "no-op"]) + const num = (value: unknown): number | null => (typeof value === "number" && Number.isFinite(value) ? value : null) function cut(text: string | null): string | null { @@ -47,46 +62,68 @@ function cut(text: string | null): string | null { return text.length > MAX_MESSAGE ? `${text.slice(0, MAX_MESSAGE)}…` : text } +const isRecord = (value: unknown): value is Record => typeof value === "object" && value !== null + /** * The last dbt run of a project: `readRunResults` gives the artifact's path, its command and its rows; * the invocation id, the elapsed time and each row's execution time are read from the same file here, - * because the validators that share `readRunResults` have no use for them. + * because the validators that share `readRunResults` have no use for them. Another dbt command may + * rewrite the file between the two reads: the second counts only when the file is the same one (same + * modification time and same rows), else both are read again, and a file that keeps changing gives its + * rows without an identity rather than another run's. */ export async function readRunView(dbtRoot: string): Promise { - const artifact = await readRunResults(dbtRoot) - if (!artifact) return NONE - let raw: { metadata?: unknown; elapsed_time?: unknown; results?: unknown } = {} - try { - raw = JSON.parse(await fs.readFile(artifact.path, "utf8")) - } catch { - // The file changed or went away after it was parsed: the rows are still good, the timings are not known. - } - const meta = typeof raw.metadata === "object" && raw.metadata !== null ? (raw.metadata as Record) : {} - const invocation = typeof meta["invocation_id"] === "string" && meta["invocation_id"] ? meta["invocation_id"] : null - // `readRunResults` keeps the rows that are objects with a unique_id; the same rows, in the same order, here. - const rows = (Array.isArray(raw.results) ? raw.results : []).filter( - (row): row is Record => - typeof row === "object" && row !== null && typeof (row as Record)["unique_id"] === "string" && !!(row as Record)["unique_id"], - ) - return { - found: true, - invocationId: invocation, - command: artifact.command, - elapsedSec: num(raw.elapsed_time), - completedAt: new Date(artifact.mtimeMs).toISOString(), - results: artifact.results.map((node, at) => ({ + for (let attempt = 0; attempt < 3; attempt++) { + const artifact = await readRunResults(dbtRoot) + if (!artifact) return NONE + let raw: Record = {} + let same = false + try { + const parsed: unknown = JSON.parse(await fs.readFile(artifact.path, "utf8")) + if (isRecord(parsed)) raw = parsed + same = (await fs.stat(artifact.path)).mtimeMs === artifact.mtimeMs + } catch { + // The file went away after it was parsed: the rows are still good, the timings are not known. + } + // `readRunResults` keeps the rows that are objects with a unique_id; the same rows, in the same order, here. + const rows = (Array.isArray(raw["results"]) ? raw["results"] : []).filter( + (row): row is Record => isRecord(row) && typeof row["unique_id"] === "string" && !!row["unique_id"], + ) + same = same && rows.length === artifact.results.length && rows.every((row, at) => row["unique_id"] === artifact.results[at]?.uniqueId) + if (!same && attempt < 2) continue + const meta = isRecord(raw["metadata"]) ? raw["metadata"] : {} + const invocation = same && typeof meta["invocation_id"] === "string" && meta["invocation_id"] ? meta["invocation_id"] : null + const all = artifact.results.map((node, at): DbtRunResultRow => ({ uniqueId: node.uniqueId, name: displayName(node.uniqueId, node.name), status: node.status, - executionTimeSec: rows[at]?.["unique_id"] === node.uniqueId ? num(rows[at]?.["execution_time"]) : null, + executionTimeSec: same ? num(rows[at]?.["execution_time"]) : null, message: cut(node.message), - })), + })) + const failed = all.filter((row) => isFailedRunStatus(row.status) && !NOT_RUN.has(row.status)) + const skipped = all.filter((row) => NOT_RUN.has(row.status)).length + const failing = new Set(failed) + // The failures first, then the rest in the file's order, whatever the size: a reader that stops early still sees them. + const listed = [...failed, ...all.filter((row) => !failing.has(row))].slice(0, MAX_ROWS) + return { + found: true, + invocationId: invocation, + command: artifact.command, + elapsedSec: same ? num(raw["elapsed_time"]) : null, + completedAt: new Date(artifact.mtimeMs).toISOString(), + total: all.length, + passed: all.length - failed.length - skipped, + failed: failed.length, + skipped, + results: listed, + } } + return NONE } export const DbtRunResultsTool = Tool.define("dbt_run_results", { description: - "Read the last dbt run of a project from its target/run_results.json: the invocation id, the dbt command, the elapsed seconds, when it finished, and one row per node with its status, execution seconds and message. Read-only; runs nothing. A compile or parse writes success rows without building anything, so look at `command`.", + "Read the last dbt run of a project from its target/run_results.json: the invocation id, the dbt command, the elapsed seconds, when it finished, the counts, and one row per node (the failures first, at most 200) with its status, execution seconds and message. Read-only; runs nothing. A compile or parse writes success rows without building anything, so look at `command`.", parameters: z.object({ project_dir: z .string() @@ -94,30 +131,35 @@ export const DbtRunResultsTool = Tool.define("dbt_run_results", { .describe("The dbt project folder (default: the project the session's directory is in)"), }), async execute(args) { - const root = args.project_dir ?? (await defaultRoot()) + const root = args.project_dir ? path.resolve(projectRoot(), args.project_dir) : await defaultRoot() const view = await readRunView(root) if (!view.found) { return { title: "dbt run results: none", metadata: { ...view }, - output: `No run_results.json under ${root}: no dbt command has written one there yet.`, + output: `No readable run_results.json for the dbt project at ${root}: no dbt command has written one there yet, or the file is not a run artifact.`, } } - const failed = view.results.filter((row) => !["success", "pass", "warn"].includes(row.status)) + const command = view.command ? `dbt ${view.command}` : "dbt (unknown command)" return { - title: `dbt ${view.command ?? "run"}: ${view.results.length - failed.length}/${view.results.length} ok`, + title: `${command}: ${view.passed}/${view.total} ok`, metadata: { ...view }, output: [ - `dbt ${view.command ?? "(unknown command)"} · invocation ${view.invocationId ?? "unknown"} · ${view.elapsedSec ?? "?"}s · ${view.completedAt}`, + `${command} · invocation ${view.invocationId ?? "unknown"} · ${view.elapsedSec ?? "?"}s · ${view.completedAt}`, ...view.results.map( (row) => `${row.status} ${row.name} ${row.executionTimeSec ?? "-"}s${row.message ? ` · ${row.message}` : ""}`, ), + ...(view.total > view.results.length ? [`… and ${view.total - view.results.length} more nodes not listed`] : []), ].join("\n"), } }, }) +/** The project the dbt adapter is configured for, else the one the session's directory is in. */ async function defaultRoot(): Promise { + const { getDbtProjectRoot } = await import("../native/connections/register") + const configured = await getDbtProjectRoot() + if (configured) return configured const { findProjectRoot } = await import("../../../../dbt-tools/src/config") const base = projectRoot() return findProjectRoot(base) ?? base diff --git a/packages/opencode/test/altimate/dbt-adapter-access.test.ts b/packages/opencode/test/altimate/dbt-adapter-access.test.ts index b565e5a58a..730d52356a 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 whose placeholder has been replaced by the real tool: their own test file covers them. */ +const IMPLEMENTED = new Set(["dbt_run_results"]) 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-run-results.test.ts b/packages/opencode/test/altimate/dbt-run-results.test.ts index d6db3e18eb..4cc925e326 100644 --- a/packages/opencode/test/altimate/dbt-run-results.test.ts +++ b/packages/opencode/test/altimate/dbt-run-results.test.ts @@ -7,6 +7,7 @@ import path from "node:path" import { Effect } from "effect" import { SessionID, MessageID } from "@/session/schema" import type { Tool } from "@/tool/tool" +import { dbtAdapterInternals, resetDbtAdapter } from "@/altimate/native/connections/register" import { DbtRunResultsTool } from "@/altimate/tools/dbt-run-results" import { initTool } from "./tool-fixture" @@ -73,6 +74,10 @@ describe("dbt_run_results", () => { command: "build", elapsedSec: 12.5, completedAt: "2026-11-01T10:00:00.000Z", + total: 4, + passed: 2, + failed: 1, + skipped: 1, results: [ { uniqueId: "model.shop.stg_orders", name: "stg_orders", status: "error", executionTimeSec: 1.25, message: "Database Error: relation missing" }, { uniqueId: "model.shop.fct_sales", name: "fct_sales", status: "success", executionTimeSec: 3.5, message: "CREATE TABLE (10 rows)" }, @@ -89,9 +94,20 @@ describe("dbt_run_results", () => { const result = await run(dir) - expect((result.metadata as any).command).toBe("compile") - expect((result.metadata as any).invocationId).toBe("22222222-aaaa-bbbb-cccc-000000000002") - expect((result.metadata as any).results).toHaveLength(1) + expect(result.metadata).toEqual({ + truncated: false, + found: true, + invocationId: "22222222-aaaa-bbbb-cccc-000000000002", + command: "compile", + elapsedSec: 2, + completedAt: expect.any(String), + total: 1, + passed: 1, + failed: 0, + skipped: 0, + results: [{ uniqueId: "model.shop.fct_sales", name: "fct_sales", status: "success", executionTimeSec: 0.01, message: null }], + }) + expect(result.title).toBe("dbt compile: 1/1 ok") }) test("no run_results.json: found is false and the answer is empty, not an error", async () => { @@ -106,6 +122,10 @@ describe("dbt_run_results", () => { command: null, elapsedSec: null, completedAt: null, + total: 0, + passed: 0, + failed: 0, + skipped: 0, results: [], }) expect(result.title).toBe("dbt run results: none") @@ -123,6 +143,10 @@ describe("dbt_run_results", () => { command: "run", elapsedSec: null, completedAt: expect.any(String), + total: 1, + passed: 1, + failed: 0, + skipped: 0, results: [{ uniqueId: "model.shop.a", name: "a", status: "success", executionTimeSec: null, message: null }], }) }) @@ -137,7 +161,53 @@ describe("dbt_run_results", () => { const result = await run(dir) const message = (result.metadata as any).results[0].message as string - expect(message.length).toBeLessThan(2100) - expect(message.endsWith("…")).toBe(true) + expect(message).toBe(`${"e".repeat(2000)}…`) + }) + + test("a build of many nodes lists the failures first, at most 200 rows, and counts every node", async () => { + const results = Array.from({ length: 450 }, (_, i) => ({ + unique_id: `model.shop.m${i}`, + status: i >= 400 ? "error" : "success", + message: null, + execution_time: 1, + })) + const dir = await project("many", { metadata: { invocation_id: "m" }, args: { which: "build" }, elapsed_time: 9, results }) + + const view = (await run(dir)).metadata as any + + expect([view.total, view.passed, view.failed, view.skipped]).toEqual([450, 400, 50, 0]) + expect(view.results).toHaveLength(200) + expect(view.results.slice(0, 50).every((row: any) => row.status === "error")).toBe(true) + expect(view.results[50].name).toBe("m0") + }) + + test("an artifact with no command is titled as unknown, not as a run", async () => { + const dir = await project("nocmd", { results: [{ unique_id: "model.shop.a", status: "success" }] }) + + expect((await run(dir)).title).toBe("dbt (unknown command): 1/1 ok") + }) + + test("a corrupt artifact is not found, and the answer says it may not be a run artifact", async () => { + const dir = await project("corrupt") + await writeFile(path.join(dir, "target", "run_results.json"), "{not json") + + const result = await run(dir) + + expect((result.metadata as any).found).toBe(false) + expect(result.output).toContain("not a run artifact") + }) + + test("with no project_dir, the project the dbt adapter is configured for is read", async () => { + const dir = await project("configured", BUILD) + dbtAdapterInternals.readConfig = async () => ({ projectRoot: dir }) + resetDbtAdapter() + try { + const result = await run(undefined) + + expect((result.metadata as any).invocationId).toBe("11111111-aaaa-bbbb-cccc-000000000001") + } finally { + delete dbtAdapterInternals.readConfig + resetDbtAdapter() + } }) }) From 2c46312eb61b6a88793bfe43eb5a509ed4a988db Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Fri, 13 Nov 2026 17:33:26 +0530 Subject: [PATCH 05/11] fix(tool): dbt_run_results looks for the project above the folder it is given and names it Co-Authored-By: Claude Sonnet 5.5 --- .../src/altimate/tools/dbt-run-results.ts | 18 +++++++++++++----- .../test/altimate/dbt-run-results.test.ts | 14 ++++++++++++++ 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/packages/opencode/src/altimate/tools/dbt-run-results.ts b/packages/opencode/src/altimate/tools/dbt-run-results.ts index 7a3c66398d..aa6aab9807 100644 --- a/packages/opencode/src/altimate/tools/dbt-run-results.ts +++ b/packages/opencode/src/altimate/tools/dbt-run-results.ts @@ -20,6 +20,8 @@ export interface DbtRunResultRow { export interface DbtRunResultsView { found: boolean + /** The dbt project folder the artifact was read from. */ + projectDir: string | null invocationId: string | null command: string | null elapsedSec: number | null @@ -35,6 +37,7 @@ export interface DbtRunResultsView { const NONE: DbtRunResultsView = { found: false, + projectDir: null, invocationId: null, command: null, elapsedSec: null, @@ -107,6 +110,7 @@ export async function readRunView(dbtRoot: string): Promise { const listed = [...failed, ...all.filter((row) => !failing.has(row))].slice(0, MAX_ROWS) return { found: true, + projectDir: dbtRoot, invocationId: invocation, command: artifact.command, elapsedSec: same ? num(raw["elapsed_time"]) : null, @@ -128,10 +132,10 @@ export const DbtRunResultsTool = Tool.define("dbt_run_results", { project_dir: z .string() .optional() - .describe("The dbt project folder (default: the project the session's directory is in)"), + .describe("A folder in the dbt project (its dbt_project.yml is looked for there and above; default: the project the dbt adapter is configured for, else the session's directory's)"), }), async execute(args) { - const root = args.project_dir ? path.resolve(projectRoot(), args.project_dir) : await defaultRoot() + const root = args.project_dir ? await projectAbove(path.resolve(projectRoot(), args.project_dir)) : await defaultRoot() const view = await readRunView(root) if (!view.found) { return { @@ -155,12 +159,16 @@ export const DbtRunResultsTool = Tool.define("dbt_run_results", { }, }) +/** The dbt project `dir` is in: the closest folder at or above it holding dbt_project.yml, else `dir`. */ +async function projectAbove(dir: string): Promise { + const { findProjectRoot } = await import("../../../../dbt-tools/src/config") + return findProjectRoot(dir) ?? dir +} + /** The project the dbt adapter is configured for, else the one the session's directory is in. */ async function defaultRoot(): Promise { const { getDbtProjectRoot } = await import("../native/connections/register") const configured = await getDbtProjectRoot() if (configured) return configured - const { findProjectRoot } = await import("../../../../dbt-tools/src/config") - const base = projectRoot() - return findProjectRoot(base) ?? base + return projectAbove(projectRoot()) } diff --git a/packages/opencode/test/altimate/dbt-run-results.test.ts b/packages/opencode/test/altimate/dbt-run-results.test.ts index 4cc925e326..84786fe888 100644 --- a/packages/opencode/test/altimate/dbt-run-results.test.ts +++ b/packages/opencode/test/altimate/dbt-run-results.test.ts @@ -70,6 +70,7 @@ describe("dbt_run_results", () => { expect(result.metadata).toEqual({ truncated: false, found: true, + projectDir: expect.any(String), invocationId: "11111111-aaaa-bbbb-cccc-000000000001", command: "build", elapsedSec: 12.5, @@ -97,6 +98,7 @@ describe("dbt_run_results", () => { expect(result.metadata).toEqual({ truncated: false, found: true, + projectDir: expect.any(String), invocationId: "22222222-aaaa-bbbb-cccc-000000000002", command: "compile", elapsedSec: 2, @@ -118,6 +120,7 @@ describe("dbt_run_results", () => { expect(result.metadata).toEqual({ truncated: false, found: false, + projectDir: null, invocationId: null, command: null, elapsedSec: null, @@ -139,6 +142,7 @@ describe("dbt_run_results", () => { expect(result.metadata).toEqual({ truncated: false, found: true, + projectDir: expect.any(String), invocationId: null, command: "run", elapsedSec: null, @@ -197,6 +201,16 @@ describe("dbt_run_results", () => { expect(result.output).toContain("not a run artifact") }) + test("a folder inside the project reads that project; a relative one resolves against the session's project", async () => { + const dir = await project("nested", BUILD) + await mkdir(path.join(dir, "models", "marts"), { recursive: true }) + + const view = (await run(path.join(dir, "models", "marts"))).metadata as any + + expect(view.projectDir).toBe(dir) + expect(view.invocationId).toBe("11111111-aaaa-bbbb-cccc-000000000001") + }) + test("with no project_dir, the project the dbt adapter is configured for is read", async () => { const dir = await project("configured", BUILD) dbtAdapterInternals.readConfig = async () => ({ projectRoot: dir }) From 60bca0f2a8286caa2227e7ee3e947757ebd73984 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Fri, 13 Nov 2026 17:36:49 +0530 Subject: [PATCH 06/11] test(tool): name the nested-folder case as what it checks Co-Authored-By: Claude Sonnet 5.5 --- packages/opencode/test/altimate/dbt-run-results.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/opencode/test/altimate/dbt-run-results.test.ts b/packages/opencode/test/altimate/dbt-run-results.test.ts index 84786fe888..080c7c240f 100644 --- a/packages/opencode/test/altimate/dbt-run-results.test.ts +++ b/packages/opencode/test/altimate/dbt-run-results.test.ts @@ -201,7 +201,7 @@ describe("dbt_run_results", () => { expect(result.output).toContain("not a run artifact") }) - test("a folder inside the project reads that project; a relative one resolves against the session's project", async () => { + test("a folder inside the project reads that project", async () => { const dir = await project("nested", BUILD) await mkdir(path.join(dir, "models", "marts"), { recursive: true }) From 1aec5aca724c5d4c0eab4da0ead19842d5e4aa17 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Fri, 13 Nov 2026 22:08:24 +0530 Subject: [PATCH 07/11] fix(tool): dbt_run_results reads each run from one parse, takes a target folder and bounds every field readRunResults now takes an optional target folder and also returns the invocation id, the elapsed time and each node's execution time, so dbt_run_results reads one file once and no field can come from another run. A run written with --target-path is read from that folder. The id, name, status, invocation id and command are cut at 300 characters. With no project_dir the project the session's folder is in is read first, as the other dbt tools do. The artifact's modification time is taken after the read. Co-Authored-By: Claude Sonnet 5.5 --- .../src/altimate/tools/dbt-run-results.ts | 116 ++++++++---------- .../altimate/validators/validator-utils.ts | 44 +++++-- .../test/altimate/dbt-run-results.test.ts | 62 +++++++++- 3 files changed, 144 insertions(+), 78 deletions(-) diff --git a/packages/opencode/src/altimate/tools/dbt-run-results.ts b/packages/opencode/src/altimate/tools/dbt-run-results.ts index aa6aab9807..bfb677dde7 100644 --- a/packages/opencode/src/altimate/tools/dbt-run-results.ts +++ b/packages/opencode/src/altimate/tools/dbt-run-results.ts @@ -1,4 +1,3 @@ -import fs from "node:fs/promises" import path from "node:path" import z from "zod" import { Tool } from "../../tool/tool" @@ -7,6 +6,8 @@ import { isFailedRunStatus, readRunResults } from "../validators/validator-utils /** A message longer than this is cut: a build of thousands of nodes must stay readable and small. */ const MAX_MESSAGE = 2000 +/** An id, name, status or command longer than this is cut: the artifact decides how long they are, the answer must not follow. */ +const MAX_IDENTIFIER = 300 /** The rows one answer carries: a plugin reads at most 4 MiB of it, so a bigger build is counted, not listed. */ const MAX_ROWS = 200 @@ -58,90 +59,70 @@ function displayName(uniqueId: string, name: string): string { /** Statuses of a node dbt did not run. */ const NOT_RUN = new Set(["skipped", "no-op"]) -const num = (value: unknown): number | null => (typeof value === "number" && Number.isFinite(value) ? value : null) - -function cut(text: string | null): string | null { +function cut(text: string | null, max = MAX_MESSAGE): string | null { if (text === null) return null - return text.length > MAX_MESSAGE ? `${text.slice(0, MAX_MESSAGE)}…` : text + return text.length > max ? `${text.slice(0, max)}…` : text } -const isRecord = (value: unknown): value is Record => typeof value === "object" && value !== null - /** - * The last dbt run of a project: `readRunResults` gives the artifact's path, its command and its rows; - * the invocation id, the elapsed time and each row's execution time are read from the same file here, - * because the validators that share `readRunResults` have no use for them. Another dbt command may - * rewrite the file between the two reads: the second counts only when the file is the same one (same - * modification time and same rows), else both are read again, and a file that keeps changing gives its - * rows without an identity rather than another run's. + * The last dbt run of a project, from one read of its run_results.json: `readRunResults` gives the path, + * the command, the invocation id, the elapsed time and each row's status, execution time and message, + * so every field belongs to the same file. `targetPath` names the folder a run with `--target-path` + * wrote to. */ -export async function readRunView(dbtRoot: string): Promise { - for (let attempt = 0; attempt < 3; attempt++) { - const artifact = await readRunResults(dbtRoot) - if (!artifact) return NONE - let raw: Record = {} - let same = false - try { - const parsed: unknown = JSON.parse(await fs.readFile(artifact.path, "utf8")) - if (isRecord(parsed)) raw = parsed - same = (await fs.stat(artifact.path)).mtimeMs === artifact.mtimeMs - } catch { - // The file went away after it was parsed: the rows are still good, the timings are not known. - } - // `readRunResults` keeps the rows that are objects with a unique_id; the same rows, in the same order, here. - const rows = (Array.isArray(raw["results"]) ? raw["results"] : []).filter( - (row): row is Record => isRecord(row) && typeof row["unique_id"] === "string" && !!row["unique_id"], - ) - same = same && rows.length === artifact.results.length && rows.every((row, at) => row["unique_id"] === artifact.results[at]?.uniqueId) - if (!same && attempt < 2) continue - const meta = isRecord(raw["metadata"]) ? raw["metadata"] : {} - const invocation = same && typeof meta["invocation_id"] === "string" && meta["invocation_id"] ? meta["invocation_id"] : null - const all = artifact.results.map((node, at): DbtRunResultRow => ({ - uniqueId: node.uniqueId, - name: displayName(node.uniqueId, node.name), - status: node.status, - executionTimeSec: same ? num(rows[at]?.["execution_time"]) : null, +export async function readRunView(dbtRoot: string, targetPath?: string): Promise { + const artifact = await readRunResults(dbtRoot, targetPath) + if (!artifact) return NONE + const all = artifact.results.map( + (node): DbtRunResultRow => ({ + uniqueId: cut(node.uniqueId, MAX_IDENTIFIER) ?? "", + name: cut(displayName(node.uniqueId, node.name), MAX_IDENTIFIER) ?? "", + status: cut(node.status, MAX_IDENTIFIER) ?? "", + executionTimeSec: node.executionTimeSec, message: cut(node.message), - })) - const failed = all.filter((row) => isFailedRunStatus(row.status) && !NOT_RUN.has(row.status)) - const skipped = all.filter((row) => NOT_RUN.has(row.status)).length - const failing = new Set(failed) - // The failures first, then the rest in the file's order, whatever the size: a reader that stops early still sees them. - const listed = [...failed, ...all.filter((row) => !failing.has(row))].slice(0, MAX_ROWS) - return { - found: true, - projectDir: dbtRoot, - invocationId: invocation, - command: artifact.command, - elapsedSec: same ? num(raw["elapsed_time"]) : null, - completedAt: new Date(artifact.mtimeMs).toISOString(), - total: all.length, - passed: all.length - failed.length - skipped, - failed: failed.length, - skipped, - results: listed, - } + }), + ) + const failed = all.filter((row) => isFailedRunStatus(row.status) && !NOT_RUN.has(row.status)) + const skipped = all.filter((row) => NOT_RUN.has(row.status)).length + const failing = new Set(failed) + // The failures first, then the rest in the file's order, whatever the size: a reader that stops early still sees them. + const listed = [...failed, ...all.filter((row) => !failing.has(row))].slice(0, MAX_ROWS) + return { + found: true, + projectDir: dbtRoot, + invocationId: cut(artifact.invocationId, MAX_IDENTIFIER), + command: cut(artifact.command, MAX_IDENTIFIER), + elapsedSec: artifact.elapsedSec, + completedAt: new Date(artifact.mtimeMs).toISOString(), + total: all.length, + passed: all.length - failed.length - skipped, + failed: failed.length, + skipped, + results: listed, } - return NONE } export const DbtRunResultsTool = Tool.define("dbt_run_results", { description: - "Read the last dbt run of a project from its target/run_results.json: the invocation id, the dbt command, the elapsed seconds, when it finished, the counts, and one row per node (the failures first, at most 200) with its status, execution seconds and message. Read-only; runs nothing. A compile or parse writes success rows without building anything, so look at `command`.", + "Read the last dbt run of a project from its target/run_results.json (or the folder `target_path` names): the invocation id, the dbt command, the elapsed seconds, when it finished, the counts, and one row per node (the failures first, at most 200) with its status, execution seconds and message. Read-only; runs nothing. A compile or parse writes success rows without building anything, so look at `command`.", parameters: z.object({ project_dir: z .string() .optional() - .describe("A folder in the dbt project (its dbt_project.yml is looked for there and above; default: the project the dbt adapter is configured for, else the session's directory's)"), + .describe("A folder in the dbt project (its dbt_project.yml is looked for there and above; default: the project the session's directory is in, else the one the dbt adapter is configured for)"), + target_path: z + .string() + .optional() + .describe("The folder the dbt run wrote its artifacts to when it was not the project's own target folder (a relative one is from the project)"), }), async execute(args) { const root = args.project_dir ? await projectAbove(path.resolve(projectRoot(), args.project_dir)) : await defaultRoot() - const view = await readRunView(root) + const view = await readRunView(root, args.target_path) if (!view.found) { return { title: "dbt run results: none", metadata: { ...view }, - output: `No readable run_results.json for the dbt project at ${root}: no dbt command has written one there yet, or the file is not a run artifact.`, + output: `No readable run_results.json for the dbt project at ${root}${args.target_path ? ` (in ${args.target_path})` : ""}: no dbt command has written one there yet, or the file is not a run artifact.`, } } const command = view.command ? `dbt ${view.command}` : "dbt (unknown command)" @@ -165,10 +146,11 @@ async function projectAbove(dir: string): Promise { return findProjectRoot(dir) ?? dir } -/** The project the dbt adapter is configured for, else the one the session's directory is in. */ +/** The dbt project the session's directory is in, else the one the dbt adapter is configured for (as the other dbt tools choose). */ async function defaultRoot(): Promise { + const { findProjectRoot } = await import("../../../../dbt-tools/src/config") + const here = findProjectRoot(projectRoot()) + if (here) return here const { getDbtProjectRoot } = await import("../native/connections/register") - const configured = await getDbtProjectRoot() - if (configured) return configured - return projectAbove(projectRoot()) + return (await getDbtProjectRoot()) ?? projectRoot() } diff --git a/packages/opencode/src/altimate/validators/validator-utils.ts b/packages/opencode/src/altimate/validators/validator-utils.ts index e1d85c476e..1dd42f6508 100644 --- a/packages/opencode/src/altimate/validators/validator-utils.ts +++ b/packages/opencode/src/altimate/validators/validator-utils.ts @@ -838,10 +838,15 @@ function collectDeliverableTokens(tokens: string[]): { models: string[]; files: // --------------------------------------------------------------------------- /** - * Resolve the project's artifact directory. Honours `DBT_TARGET_PATH` and a - * `target-path:` key in `dbt_project.yml`; defaults to `target`. - */ -export async function resolveDbtTargetPath(dbtRoot: string): Promise { + * Resolve the project's artifact directory. A `targetPath` the caller names (the + * folder a `--target-path` run wrote to) wins; else `DBT_TARGET_PATH` and a + * `target-path:` key in `dbt_project.yml` are honoured; defaults to `target`. + */ +export async function resolveDbtTargetPath(dbtRoot: string, targetPath?: string): Promise { + // A folder the caller names (the one a `--target-path` run wrote to) wins over the environment and the project file. + if (targetPath && targetPath.trim().length > 0) { + return isAbsolutePath(targetPath) ? targetPath : join(dbtRoot, targetPath) + } const fromEnv = process.env.DBT_TARGET_PATH if (fromEnv && fromEnv.trim().length > 0) { return isAbsolutePath(fromEnv) ? fromEnv : join(dbtRoot, fromEnv) @@ -1191,6 +1196,8 @@ export interface RunResultNode { status: string /** dbt's message for the node, when present. */ message: string | null + /** Seconds dbt spent on the node (`execution_time`), when it wrote a number. */ + executionTimeSec: number | null } /** A parsed `run_results.json` plus its freshness. */ @@ -1212,6 +1219,10 @@ export interface RunResultsArtifact { * not evidence that anything was built. */ command: string | null + /** `metadata.invocation_id`, when the file carries one. */ + invocationId: string | null + /** The run's `elapsed_time` in seconds, when the file carries one. */ + elapsedSec: number | null } /** @@ -1348,14 +1359,16 @@ export function isFailedRunStatus(status: string): boolean { * Read and parse `/run_results.json`. Returns null when the artifact * is absent or unparseable — callers decide what that means for their gate. */ -export async function readRunResults(dbtRoot: string): Promise { - const targetPath = await resolveDbtTargetPath(dbtRoot) +export async function readRunResults(dbtRoot: string, targetPathOverride?: string): Promise { + const targetPath = await resolveDbtTargetPath(dbtRoot, targetPathOverride) const path = join(targetPath, "run_results.json") try { const stat = await fs.stat(path) if (!stat.isFile()) return null const raw = await fs.readFile(path, "utf8") - const parsed = JSON.parse(raw) as { results?: unknown; args?: unknown } + // The modification time is taken after the read: a rewrite in between never leaves an older time with newer rows. + const mtimeMs = (await fs.stat(path)).mtimeMs + const parsed = JSON.parse(raw) as { results?: unknown; args?: unknown; metadata?: unknown; elapsed_time?: unknown } // A file that parses but carries no `results` array is not a run artifact. // Returning an empty one would read as "a build happened and recorded // nothing", which lets an unbuilt model through; null means "no evidence". @@ -1383,9 +1396,24 @@ export async function readRunResults(dbtRoot: string): Promise) + : null + const invocation = meta && typeof meta["invocation_id"] === "string" ? meta["invocation_id"] : "" + const elapsed = typeof parsed.elapsed_time === "number" && Number.isFinite(parsed.elapsed_time) ? parsed.elapsed_time : null + return { + path, + mtimeMs, + results, + command, + invocationId: invocation || null, + elapsedSec: elapsed, + } } catch { return null } diff --git a/packages/opencode/test/altimate/dbt-run-results.test.ts b/packages/opencode/test/altimate/dbt-run-results.test.ts index 080c7c240f..d753c463af 100644 --- a/packages/opencode/test/altimate/dbt-run-results.test.ts +++ b/packages/opencode/test/altimate/dbt-run-results.test.ts @@ -9,6 +9,7 @@ import { SessionID, MessageID } from "@/session/schema" import type { Tool } from "@/tool/tool" import { dbtAdapterInternals, resetDbtAdapter } from "@/altimate/native/connections/register" import { DbtRunResultsTool } from "@/altimate/tools/dbt-run-results" +import { Instance } from "@/project/instance" import { initTool } from "./tool-fixture" const ctx: Tool.Context = { @@ -41,8 +42,8 @@ const COMPILE = { } let root: string -const run = async (dir: string | undefined) => - (await initTool(DbtRunResultsTool)).execute(dir === undefined ? {} : { project_dir: dir }, ctx) +const run = async (dir: string | undefined, target_path?: string) => + (await initTool(DbtRunResultsTool)).execute({ ...(dir === undefined ? {} : { project_dir: dir }), ...(target_path ? { target_path } : {}) }, ctx) async function project(name: string, artifact?: unknown) { const dir = path.join(root, name) @@ -201,6 +202,40 @@ describe("dbt_run_results", () => { expect(result.output).toContain("not a run artifact") }) + test("a run that wrote to another target folder is read from that folder, whatever DBT_TARGET_PATH says", async () => { + const dir = await project("custom-target", COMPILE) + await mkdir(path.join(dir, "ci-out"), { recursive: true }) + await writeFile(path.join(dir, "ci-out", "run_results.json"), JSON.stringify(BUILD)) + const before = process.env["DBT_TARGET_PATH"] + process.env["DBT_TARGET_PATH"] = "elsewhere" + let view: any + try { + view = (await run(dir, "ci-out")).metadata + } finally { + if (before === undefined) delete process.env["DBT_TARGET_PATH"] + else process.env["DBT_TARGET_PATH"] = before + } + const own = (await run(dir)).metadata as any + + expect(view.invocationId).toBe("11111111-aaaa-bbbb-cccc-000000000001") + expect(own.invocationId).toBe("22222222-aaaa-bbbb-cccc-000000000002") + }) + + test("a node id longer than the bound is cut, so the answer stays small", async () => { + const long = "x".repeat(5000) + const dir = await project("long-id", { + metadata: { invocation_id: "33333333-aaaa-bbbb-cccc-000000000003" }, + args: { which: "run" }, + elapsed_time: 1, + results: [{ unique_id: `model.shop.${long}`, status: "success", message: null, execution_time: 1 }], + }) + + const row = ((await run(dir)).metadata as any).results[0] + + expect(row.uniqueId).toBe(`model.shop.${"x".repeat(5000)}`.slice(0, 300) + "…") + expect(row.name).toBe("x".repeat(300) + "…") + }) + test("a folder inside the project reads that project", async () => { const dir = await project("nested", BUILD) await mkdir(path.join(dir, "models", "marts"), { recursive: true }) @@ -211,7 +246,28 @@ describe("dbt_run_results", () => { expect(view.invocationId).toBe("11111111-aaaa-bbbb-cccc-000000000001") }) - test("with no project_dir, the project the dbt adapter is configured for is read", async () => { + test("with no project_dir, the project the session's folder is in is read before the adapter's", async () => { + const here = await project("session-project", BUILD) + const other = await project("adapter-project", COMPILE) + dbtAdapterInternals.readConfig = async () => ({ projectRoot: other }) + resetDbtAdapter() + try { + const result = await Instance.provide({ directory: here, fn: () => run(undefined) }) + + expect((result.metadata as any).invocationId).toBe("11111111-aaaa-bbbb-cccc-000000000001") + } finally { + delete dbtAdapterInternals.readConfig + resetDbtAdapter() + } + }) + + test("an invocation id longer than the bound is cut", async () => { + const dir = await project("long-invocation", { ...BUILD, metadata: { invocation_id: "i".repeat(5000) } }) + + expect(((await run(dir)).metadata as any).invocationId).toBe("i".repeat(300) + "…") + }) + + test("with no project_dir and none around the session's folder, the project the dbt adapter is configured for is read", async () => { const dir = await project("configured", BUILD) dbtAdapterInternals.readConfig = async () => ({ projectRoot: dir }) resetDbtAdapter() From b1e36d6c152f5e4e9f7f8f256a86a199fbd63d36 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Sat, 14 Nov 2026 07:57:52 +0530 Subject: [PATCH 08/11] fix(validators): a run_results.json rewritten during the read is no evidence Co-Authored-By: Claude Sonnet 5.5 --- .../opencode/src/altimate/validators/validator-utils.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/validators/validator-utils.ts b/packages/opencode/src/altimate/validators/validator-utils.ts index 1dd42f6508..26d855df31 100644 --- a/packages/opencode/src/altimate/validators/validator-utils.ts +++ b/packages/opencode/src/altimate/validators/validator-utils.ts @@ -1366,8 +1366,10 @@ export async function readRunResults(dbtRoot: string, targetPathOverride?: strin const stat = await fs.stat(path) if (!stat.isFile()) return null const raw = await fs.readFile(path, "utf8") - // The modification time is taken after the read: a rewrite in between never leaves an older time with newer rows. - const mtimeMs = (await fs.stat(path)).mtimeMs + // A rewrite during the read leaves the time before and after unequal: the rows and the time would belong to different runs, so there is no evidence. + const after = await fs.stat(path) + if (after.mtimeMs !== stat.mtimeMs) return null + const mtimeMs = stat.mtimeMs const parsed = JSON.parse(raw) as { results?: unknown; args?: unknown; metadata?: unknown; elapsed_time?: unknown } // A file that parses but carries no `results` array is not a run artifact. // Returning an empty one would read as "a build happened and recorded From 8c677255b61f6ffa6921cb078a6ec3d47fd870fe Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Sat, 14 Nov 2026 09:10:18 +0530 Subject: [PATCH 09/11] fix(validators): detect a rewrite during the run_results.json read by identity, size and nanosecond times Co-Authored-By: Claude Sonnet 5.5 --- .../src/altimate/validators/validator-utils.ts | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/packages/opencode/src/altimate/validators/validator-utils.ts b/packages/opencode/src/altimate/validators/validator-utils.ts index 26d855df31..764e32ee19 100644 --- a/packages/opencode/src/altimate/validators/validator-utils.ts +++ b/packages/opencode/src/altimate/validators/validator-utils.ts @@ -1363,13 +1363,19 @@ export async function readRunResults(dbtRoot: string, targetPathOverride?: strin const targetPath = await resolveDbtTargetPath(dbtRoot, targetPathOverride) const path = join(targetPath, "run_results.json") try { - const stat = await fs.stat(path) + const stat = await fs.stat(path, { bigint: true }) if (!stat.isFile()) return null const raw = await fs.readFile(path, "utf8") - // A rewrite during the read leaves the time before and after unequal: the rows and the time would belong to different runs, so there is no evidence. - const after = await fs.stat(path) - if (after.mtimeMs !== stat.mtimeMs) return null - const mtimeMs = stat.mtimeMs + // A rewrite during the read changes the file's identity, size or times (nanosecond precision): the rows and the time would belong to different runs, so there is no evidence. + const after = await fs.stat(path, { bigint: true }) + if ( + after.ino !== stat.ino || + after.size !== stat.size || + after.mtimeNs !== stat.mtimeNs || + after.ctimeNs !== stat.ctimeNs + ) + return null + const mtimeMs = Number(stat.mtimeNs) / 1e6 const parsed = JSON.parse(raw) as { results?: unknown; args?: unknown; metadata?: unknown; elapsed_time?: unknown } // A file that parses but carries no `results` array is not a run artifact. // Returning an empty one would read as "a build happened and recorded From a609c638afaa8254444f64aabcc490304f7c061e Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Sat, 14 Nov 2026 13:16:24 +0530 Subject: [PATCH 10/11] fix(validators): run_results.json keeps the filesystem's own mtime rounding so an equal-instant model is not read as edited after the build Co-Authored-By: Claude Sonnet 5.5 --- .../src/altimate/validators/validator-utils.ts | 4 +++- .../altimate/validators/dbt-build-green.test.ts | 13 +++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/packages/opencode/src/altimate/validators/validator-utils.ts b/packages/opencode/src/altimate/validators/validator-utils.ts index 764e32ee19..6b7e1d4708 100644 --- a/packages/opencode/src/altimate/validators/validator-utils.ts +++ b/packages/opencode/src/altimate/validators/validator-utils.ts @@ -1363,6 +1363,8 @@ export async function readRunResults(dbtRoot: string, targetPathOverride?: strin const targetPath = await resolveDbtTargetPath(dbtRoot, targetPathOverride) const path = join(targetPath, "run_results.json") try { + // The time keeps the plain stat's own rounding: every other caller compares it with mtimes read the same way, and a different rounding of equal timestamps would order them apart. + const plain = await fs.stat(path) const stat = await fs.stat(path, { bigint: true }) if (!stat.isFile()) return null const raw = await fs.readFile(path, "utf8") @@ -1375,7 +1377,7 @@ export async function readRunResults(dbtRoot: string, targetPathOverride?: strin after.ctimeNs !== stat.ctimeNs ) return null - const mtimeMs = Number(stat.mtimeNs) / 1e6 + const mtimeMs = plain.mtimeMs const parsed = JSON.parse(raw) as { results?: unknown; args?: unknown; metadata?: unknown; elapsed_time?: unknown } // A file that parses but carries no `results` array is not a run artifact. // Returning an empty one would read as "a build happened and recorded diff --git a/packages/opencode/test/altimate/validators/dbt-build-green.test.ts b/packages/opencode/test/altimate/validators/dbt-build-green.test.ts index df91fd655a..fbacda0529 100644 --- a/packages/opencode/test/altimate/validators/dbt-build-green.test.ts +++ b/packages/opencode/test/altimate/validators/dbt-build-green.test.ts @@ -113,6 +113,19 @@ describe("DbtBuildGreenValidator — fresh artifact", () => { expect(r.details!["verdict"]).toBe("fresh-build") }) + test("a model and an artifact stamped with the same instant read as built, not edited after the build", async () => { + await makeProject() + await writeModel("stg_orders") + await writeRunResults([{ id: "model.t.stg_orders", status: "success" }]) + // A coarse filesystem clock gives writes in one tick the same nanosecond timestamp. + const t = 1_800_000_000.004123 + await fs.utimes(join(dir, "models", "stg_orders.sql"), t, t) + await fs.utimes(join(dir, "target", "run_results.json"), t, t) + const r = await DbtBuildGreenValidator.check(ctx()) + expect(r.ok).toBe(true) + expect(r.details!["verdict"]).toBe("fresh-build") + }) + test("treats warn as a clean build", async () => { await makeProject() await writeModel("stg_orders") From 4845d65ad32a3d39d68d27d238a2396456439f1a Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Sun, 15 Nov 2026 22:14:47 +0530 Subject: [PATCH 11/11] =?UTF-8?q?fix(tool):=20review=20follow-ups=20?= =?UTF-8?q?=E2=80=94=20falsey=20API=20bodies,=20one=20stat=20snapshot=20fo?= =?UTF-8?q?r=20run=5Fresults,=20shared=20sessionProject,=20placeholder=20t?= =?UTF-8?q?ools=20labelled?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- packages/opencode/src/altimate/api/client.ts | 2 +- .../src/altimate/tools/dbt-adapter-access.ts | 25 +------------------ .../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 | 2 +- .../opencode/src/altimate/tools/dbt-health.ts | 2 +- .../src/altimate/tools/dbt-lineage.ts | 2 +- .../src/altimate/tools/dbt-map-relations.ts | 2 +- .../src/altimate/tools/dbt-sql-graph.ts | 2 +- .../src/altimate/tools/docs-share-comments.ts | 2 +- .../altimate/validators/validator-utils.ts | 4 +-- .../test/altimate/dbt-adapter-access.test.ts | 20 +++++++++++++++ .../test/altimate/dbt-run-results.test.ts | 3 +++ .../validators/dbt-nothing-built.test.ts | 21 +++++++++++++++- 15 files changed, 56 insertions(+), 37 deletions(-) diff --git a/packages/opencode/src/altimate/api/client.ts b/packages/opencode/src/altimate/api/client.ts index cb53c0ec7b..2541ed93b2 100644 --- a/packages/opencode/src/altimate/api/client.ts +++ b/packages/opencode/src/altimate/api/client.ts @@ -335,7 +335,7 @@ export namespace AltimateApi { "x-tenant": creds.altimateInstanceName, ...clientHeaders(), }, - ...(body ? { body: JSON.stringify(body) } : {}), + ...(body !== undefined ? { body: JSON.stringify(body) } : {}), }) if (!res.ok) { throw new Error(`API ${method} ${endpoint} failed with status ${res.status}`) diff --git a/packages/opencode/src/altimate/tools/dbt-adapter-access.ts b/packages/opencode/src/altimate/tools/dbt-adapter-access.ts index d73dd7e9c5..5260dca415 100644 --- a/packages/opencode/src/altimate/tools/dbt-adapter-access.ts +++ b/packages/opencode/src/altimate/tools/dbt-adapter-access.ts @@ -2,6 +2,7 @@ import fs from "fs" import path from "path" import type { Tool } from "../../tool/tool" import { projectRoot } from "../native/connections/registry" +import { sessionProject } from "./dbt-lineage" /** Why a tool may not use the dbt adapter. */ export type DbtAdapterRefusal = "read_only" | "other_project" | "no_project" | "not_started" | "not_loaded" @@ -75,27 +76,3 @@ export async function dbtAdapterFor(ctx: Pick { - 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 index 1b113f1994..7e90c39101 100644 --- a/packages/opencode/src/altimate/tools/dbt-cost-estimate.ts +++ b/packages/opencode/src/altimate/tools/dbt-cost-estimate.ts @@ -2,7 +2,7 @@ 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).", + description: "Not implemented yet: always returns an error. 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"), diff --git a/packages/opencode/src/altimate/tools/dbt-cte-profile.ts b/packages/opencode/src/altimate/tools/dbt-cte-profile.ts index 0e4913f06d..ede4eae8fb 100644 --- a/packages/opencode/src/altimate/tools/dbt-cte-profile.ts +++ b/packages/opencode/src/altimate/tools/dbt-cte-profile.ts @@ -2,7 +2,7 @@ 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.", + description: "Not implemented yet: always returns an error. 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"), diff --git a/packages/opencode/src/altimate/tools/dbt-defer-state.ts b/packages/opencode/src/altimate/tools/dbt-defer-state.ts index 9df344ec1b..0cd7207bc7 100644 --- a/packages/opencode/src/altimate/tools/dbt-defer-state.ts +++ b/packages/opencode/src/altimate/tools/dbt-defer-state.ts @@ -2,7 +2,7 @@ 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.", + description: "Not implemented yet: always returns an error. 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"), }), diff --git a/packages/opencode/src/altimate/tools/dbt-docs-coverage.ts b/packages/opencode/src/altimate/tools/dbt-docs-coverage.ts index 8990306b72..927da81c86 100644 --- a/packages/opencode/src/altimate/tools/dbt-docs-coverage.ts +++ b/packages/opencode/src/altimate/tools/dbt-docs-coverage.ts @@ -3,7 +3,7 @@ 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.", + "Not implemented yet: always returns an error. 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 diff --git a/packages/opencode/src/altimate/tools/dbt-health.ts b/packages/opencode/src/altimate/tools/dbt-health.ts index 096e2bc3f4..397700927b 100644 --- a/packages/opencode/src/altimate/tools/dbt-health.ts +++ b/packages/opencode/src/altimate/tools/dbt-health.ts @@ -2,7 +2,7 @@ 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.", + description: "Not implemented yet: always returns an error. DataPilot project health insights for the dbt project.", parameters: z.object({ config_path: z.string().optional().describe("DataPilot config file to use"), }), diff --git a/packages/opencode/src/altimate/tools/dbt-lineage.ts b/packages/opencode/src/altimate/tools/dbt-lineage.ts index a83efb84ae..5c300bc759 100644 --- a/packages/opencode/src/altimate/tools/dbt-lineage.ts +++ b/packages/opencode/src/altimate/tools/dbt-lineage.ts @@ -366,7 +366,7 @@ async function defaultManifestPath(session: () => ReturnType { +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-map-relations.ts b/packages/opencode/src/altimate/tools/dbt-map-relations.ts index f949274620..e4d8642e4f 100644 --- a/packages/opencode/src/altimate/tools/dbt-map-relations.ts +++ b/packages/opencode/src/altimate/tools/dbt-map-relations.ts @@ -2,7 +2,7 @@ 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.", + description: "Not implemented yet: always returns an error. 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"), diff --git a/packages/opencode/src/altimate/tools/dbt-sql-graph.ts b/packages/opencode/src/altimate/tools/dbt-sql-graph.ts index 0c4db3c980..c98d1c0a16 100644 --- a/packages/opencode/src/altimate/tools/dbt-sql-graph.ts +++ b/packages/opencode/src/altimate/tools/dbt-sql-graph.ts @@ -2,7 +2,7 @@ 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.", + description: "Not implemented yet: always returns an error. 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"), }), diff --git a/packages/opencode/src/altimate/tools/docs-share-comments.ts b/packages/opencode/src/altimate/tools/docs-share-comments.ts index 8963268cdd..a309265a9d 100644 --- a/packages/opencode/src/altimate/tools/docs-share-comments.ts +++ b/packages/opencode/src/altimate/tools/docs-share-comments.ts @@ -2,7 +2,7 @@ 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.", + description: "Not implemented yet: always returns an error. 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"), diff --git a/packages/opencode/src/altimate/validators/validator-utils.ts b/packages/opencode/src/altimate/validators/validator-utils.ts index 6b7e1d4708..1e87ef7a4b 100644 --- a/packages/opencode/src/altimate/validators/validator-utils.ts +++ b/packages/opencode/src/altimate/validators/validator-utils.ts @@ -1363,11 +1363,11 @@ export async function readRunResults(dbtRoot: string, targetPathOverride?: strin const targetPath = await resolveDbtTargetPath(dbtRoot, targetPathOverride) const path = join(targetPath, "run_results.json") try { - // The time keeps the plain stat's own rounding: every other caller compares it with mtimes read the same way, and a different rounding of equal timestamps would order them apart. - const plain = await fs.stat(path) const stat = await fs.stat(path, { bigint: true }) if (!stat.isFile()) return null const raw = await fs.readFile(path, "utf8") + // The time keeps the plain stat's own rounding: every other caller compares it with mtimes read the same way, and a different rounding of equal timestamps would order them apart. It is taken between the two bigint stats, so the comparison below proves it describes the same file version as the rows. + const plain = await fs.stat(path) // A rewrite during the read changes the file's identity, size or times (nanosecond precision): the rows and the time would belong to different runs, so there is no evidence. const after = await fs.stat(path, { bigint: true }) if ( diff --git a/packages/opencode/test/altimate/dbt-adapter-access.test.ts b/packages/opencode/test/altimate/dbt-adapter-access.test.ts index 963f53b656..a9ae7406e0 100644 --- a/packages/opencode/test/altimate/dbt-adapter-access.test.ts +++ b/packages/opencode/test/altimate/dbt-adapter-access.test.ts @@ -239,6 +239,26 @@ describe("AltimateApi.apiRequest", () => { ) }) + test("sends a falsey body (false, 0, empty string, null) unchanged", async () => { + await Bun.write( + path.join(home, ".altimate", "altimate.json"), + JSON.stringify({ altimateUrl: "https://api.example.test/", altimateInstanceName: "acme", altimateApiKey: "k1" }), + ) + const original = globalThis.fetch + const bodies: unknown[] = [] + globalThis.fetch = (async (_url: string, init: RequestInit) => { + bodies.push(init.body) + return new Response("{}", { status: 200 }) + }) as unknown as typeof fetch + try { + for (const v of [false, 0, "", null]) await AltimateApi.apiRequest("POST", "/dbt/v1/x", v) + await AltimateApi.apiRequest("GET", "/dbt/v1/x") + expect(bodies).toEqual(["false", "0", '""', "null", undefined]) + } finally { + globalThis.fetch = original + } + }) + test("sends the stored key and tenant and returns the JSON body", async () => { await Bun.write( path.join(home, ".altimate", "altimate.json"), diff --git a/packages/opencode/test/altimate/dbt-run-results.test.ts b/packages/opencode/test/altimate/dbt-run-results.test.ts index d753c463af..4ee5e14be4 100644 --- a/packages/opencode/test/altimate/dbt-run-results.test.ts +++ b/packages/opencode/test/altimate/dbt-run-results.test.ts @@ -53,10 +53,13 @@ async function project(name: string, artifact?: unknown) { return dir } +const savedTarget = process.env["DBT_TARGET_PATH"] beforeAll(async () => { + delete process.env["DBT_TARGET_PATH"] root = await mkdtemp(path.join(os.tmpdir(), "dbt-run-results-")) }) afterAll(async () => { + if (savedTarget !== undefined) process.env["DBT_TARGET_PATH"] = savedTarget await rm(root, { recursive: true, force: true }) }) diff --git a/packages/opencode/test/altimate/validators/dbt-nothing-built.test.ts b/packages/opencode/test/altimate/validators/dbt-nothing-built.test.ts index 7dfaef7d38..fa03785e65 100644 --- a/packages/opencode/test/altimate/validators/dbt-nothing-built.test.ts +++ b/packages/opencode/test/altimate/validators/dbt-nothing-built.test.ts @@ -1,5 +1,5 @@ // altimate_change start — tests for the nothing-built inverse completion gate -import { describe, expect, test, beforeEach, afterEach } from "bun:test" +import { describe, expect, test, beforeEach, afterEach, spyOn } from "bun:test" import { promises as fs } from "fs" import { tmpdir } from "os" import { join } from "path" @@ -274,6 +274,25 @@ describe("run_results and inventory helpers", () => { expect(await resolveDbtTargetPath(dir)).toBe(join(dir, "alt_target")) }) + test("readRunResults takes the time from between the two identity stats, so it describes the version the rows came from", async () => { + const dir = await fs.mkdtemp(join(tmpdir(), "rr-order-")) + await fs.mkdir(join(dir, "target"), { recursive: true }) + await fs.writeFile(join(dir, "target", "run_results.json"), JSON.stringify({ args: { which: "build" }, results: [] })) + const real = fs.stat + const kinds: string[] = [] + const spy = spyOn(fs, "stat").mockImplementation(((p: any, o?: any) => { + if (String(p).endsWith("run_results.json")) kinds.push(o?.bigint ? "bigint" : "plain") + return real(p, o) + }) as any) + try { + await readRunResults(dir) + } finally { + spy.mockRestore() + await fs.rm(dir, { recursive: true, force: true }) + } + expect(kinds).toEqual(["bigint", "plain", "bigint"]) + }) + test("readRunResults returns null when the artifact is missing", async () => { await makeProject() expect(await readRunResults(dir)).toBeNull()