Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 21 additions & 14 deletions packages/opencode/src/altimate/native/altimate-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,14 @@ function toData(obj: unknown): Record<string, unknown> {
return JSON.parse(JSON.stringify(obj)) as Record<string, unknown>
}

/** Wrap a handler body into the standard AltimateCoreResult envelope. */
/**
* Wrap a handler body into the standard AltimateCoreResult envelope.
*
* Contract: ok(true, data) means "the operation completed." Semantic results
* (e.g., SQL is invalid, queries are not equivalent) live in the data fields,
* NOT in the success flag. success=false only when the handler throws (fail()).
* This prevents semantic findings from being misreported as tool crashes.
*/
function ok(
success: boolean,
data: Record<string, unknown>,
Expand Down Expand Up @@ -92,7 +99,7 @@ register("altimate_core.validate", async (params) => {
const schema = schemaOrEmpty(params.schema_path, params.schema_context)
const raw = await core.validate(params.sql, schema)
const data = toData(raw)
return ok(data.valid !== false, data)
return ok(true, data)
} catch (e) {
return fail(e)
}
Expand All @@ -104,7 +111,7 @@ register("altimate_core.lint", async (params) => {
const schema = schemaOrEmpty(params.schema_path, params.schema_context)
const raw = core.lint(params.sql, schema)
const data = toData(raw)
return ok(data.clean !== false, data)
return ok(true, data)
} catch (e) {
return fail(e)
}
Expand All @@ -115,7 +122,7 @@ register("altimate_core.safety", async (params) => {
try {
const raw = core.scanSql(params.sql)
const data = toData(raw)
return ok(data.safe !== false, data)
return ok(true, data)
} catch (e) {
return fail(e)
}
Expand Down Expand Up @@ -147,7 +154,7 @@ register("altimate_core.transpile", async (params) => {
}
}

return ok(data.success !== false, data)
return ok(true, data)
} catch (e) {
return fail(e)
}
Expand All @@ -159,7 +166,7 @@ register("altimate_core.explain", async (params) => {
const schema = schemaOrEmpty(params.schema_path, params.schema_context)
const raw = await core.explain(params.sql, schema)
const data = toData(raw)
return ok(data.valid !== false, data)
return ok(true, data)
} catch (e) {
return fail(e)
}
Expand Down Expand Up @@ -193,7 +200,7 @@ register("altimate_core.fix", async (params) => {
params.max_iterations ?? undefined,
)
const data = toData(raw)
return ok(data.fixed !== false, data)
return ok(true, data)
} catch (e) {
return fail(e)
}
Expand All @@ -205,7 +212,7 @@ register("altimate_core.policy", async (params) => {
const schema = schemaOrEmpty(params.schema_path, params.schema_context)
const raw = await core.checkPolicy(params.sql, schema, params.policy_json)
const data = toData(raw)
return ok(data.allowed !== false, data)
return ok(true, data)
} catch (e) {
return fail(e)
}
Expand All @@ -217,7 +224,7 @@ register("altimate_core.semantics", async (params) => {
const schema = schemaOrEmpty(params.schema_path, params.schema_context)
const raw = await core.checkSemantics(params.sql, schema)
const data = toData(raw)
return ok(data.valid !== false, data)
return ok(true, data)
} catch (e) {
return fail(e)
}
Expand All @@ -240,7 +247,7 @@ register("altimate_core.equivalence", async (params) => {
const schema = schemaOrEmpty(params.schema_path, params.schema_context)
const raw = await core.checkEquivalence(params.sql1, params.sql2, schema)
const data = toData(raw)
return ok(data.equivalent !== false, data)
return ok(true, data)
} catch (e) {
return fail(e)
}
Expand All @@ -256,7 +263,7 @@ register("altimate_core.migration", async (params) => {
)
const raw = core.analyzeMigration(params.new_ddl, schema)
const data = toData(raw)
return ok(data.safe !== false, data)
return ok(true, data)
} catch (e) {
return fail(e)
}
Expand Down Expand Up @@ -291,7 +298,7 @@ register("altimate_core.correct", async (params) => {
const schema = schemaOrEmpty(params.schema_path, params.schema_context)
const raw = await core.correct(params.sql, schema)
const data = toData(raw)
return ok(data.status !== "unfixable", data)
return ok(true, data)
} catch (e) {
return fail(e)
}
Expand Down Expand Up @@ -337,7 +344,7 @@ register("altimate_core.resolve_term", async (params) => {
const raw = core.resolveTerm(params.term, schema)
// Rust returns an array of matches — wrap for consistent object shape
const matches = Array.isArray(raw) ? JSON.parse(JSON.stringify(raw)) : []
return ok(matches.length > 0, { matches })
return ok(true, { matches })
} catch (e) {
return fail(e)
}
Expand Down Expand Up @@ -374,7 +381,7 @@ register("altimate_core.format", async (params) => {
try {
const raw = core.formatSql(params.sql, params.dialect || undefined)
const data = toData(raw)
return ok(data.success !== false, data)
return ok(true, data)
} catch (e) {
return fail(e)
}
Expand Down
10 changes: 10 additions & 0 deletions packages/opencode/src/altimate/native/sql/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,13 +215,23 @@ register("sql.fix", async (params) => {
fixed_sql: f.fixed_sql ?? f.rewritten_sql,
}))

const unfixableMessages = Array.isArray(result.unfixable_errors)
? result.unfixable_errors
.map((e: any) => e.error?.message ?? e.message ?? e.reason ?? String(e))
.filter((msg: any) => typeof msg === "string" ? msg.trim().length > 0 : Boolean(msg))
: []
const unfixableError = !result.fixed && unfixableMessages.length > 0
? unfixableMessages.join("; ")
: undefined

return {
success: result.fixed ?? true,
original_sql: result.original_sql ?? params.sql,
fixed_sql: result.fixed_sql ?? params.sql,
error_message: params.error_message ?? "",
suggestions,
suggestion_count: suggestions.length,
...(unfixableError && { error: unfixableError }),
}
} catch (e) {
return {
Expand Down
2 changes: 2 additions & 0 deletions packages/opencode/src/altimate/native/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export interface SqlExecuteResult {
export interface SqlAnalyzeParams {
sql: string
dialect?: string
schema_path?: string
schema_context?: Record<string, any>
}

Expand Down Expand Up @@ -385,6 +386,7 @@ export interface SqlFixResult {
error_message: string
suggestions: SqlFixSuggestion[]
suggestion_count: number
error?: string
}

// --- SQL Autocomplete ---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Dispatcher } from "../native"

export const AltimateCoreCheckTool = Tool.define("altimate_core_check", {
description:
"Run full analysis pipeline: validate + lint + safety scan + PII check using the Rust-based altimate-core engine. Single call for comprehensive SQL analysis.",
"Run full analysis pipeline: validate + lint + safety scan + PII check. Single call for comprehensive SQL analysis. Provide schema_context or schema_path for accurate table/column resolution.",
parameters: z.object({
sql: z.string().describe("SQL query to analyze"),
schema_path: z.string().optional().describe("Path to YAML/JSON schema file"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Dispatcher } from "../native"

export const AltimateCoreClassifyPiiTool = Tool.define("altimate_core_classify_pii", {
description:
"Classify PII columns in a schema using the Rust-based altimate-core engine. Identifies columns likely containing personal identifiable information by name patterns and data types.",
"Classify PII columns in a schema. Identifies columns likely containing personal identifiable information by name patterns and data types. Provide schema_context or schema_path for accurate table/column resolution.",
parameters: z.object({
schema_path: z.string().optional().describe("Path to YAML/JSON schema file"),
schema_context: z.record(z.string(), z.any()).optional().describe("Inline schema definition"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Dispatcher } from "../native"

export const AltimateCoreColumnLineageTool = Tool.define("altimate_core_column_lineage", {
description:
"Trace schema-aware column lineage using the Rust-based altimate-core engine. Maps how columns flow through a query from source tables to output. Requires altimate_core.init() with API key.",
"Trace schema-aware column lineage. Maps how columns flow through a query from source tables to output. Requires altimate_core.init() with API key. Provide schema_context or schema_path for accurate table/column resolution.",
parameters: z.object({
sql: z.string().describe("SQL query to trace lineage for"),
dialect: z.string().optional().describe("SQL dialect (e.g. snowflake, bigquery)"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Dispatcher } from "../native"

export const AltimateCoreCompareTool = Tool.define("altimate_core_compare", {
description:
"Structurally compare two SQL queries using the Rust-based altimate-core engine. Identifies differences in table references, join conditions, filters, projections, and aggregations.",
"Structurally compare two SQL queries. Identifies differences in table references, join conditions, filters, projections, and aggregations.",
parameters: z.object({
left_sql: z.string().describe("First SQL query"),
right_sql: z.string().describe("Second SQL query"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Dispatcher } from "../native"

export const AltimateCoreCompleteTool = Tool.define("altimate_core_complete", {
description:
"Get cursor-aware SQL completion suggestions using the Rust-based altimate-core engine. Returns table names, column names, functions, and keywords relevant to the cursor position.",
"Get cursor-aware SQL completion suggestions. Returns table names, column names, functions, and keywords relevant to the cursor position. Provide schema_context or schema_path for accurate table/column resolution.",
parameters: z.object({
sql: z.string().describe("Partial SQL query"),
cursor_pos: z.number().describe("Cursor position (0-indexed character offset)"),
Expand All @@ -21,14 +21,15 @@ export const AltimateCoreCompleteTool = Tool.define("altimate_core_complete", {
})
const data = result.data as Record<string, any>
const count = data.items?.length ?? data.suggestions?.length ?? 0
const error = result.error ?? (data as any).error
return {
title: `Complete: ${count} suggestion(s)`,
metadata: { success: result.success, suggestion_count: count },
metadata: { success: result.success, suggestion_count: count, ...(error && { error }) },
output: formatComplete(data),
}
} catch (e) {
const msg = e instanceof Error ? e.message : String(e)
return { title: "Complete: ERROR", metadata: { success: false, suggestion_count: 0 }, output: `Failed: ${msg}` }
return { title: "Complete: ERROR", metadata: { success: false, suggestion_count: 0, error: msg }, output: `Failed: ${msg}` }
}
},
})
Expand Down
21 changes: 17 additions & 4 deletions packages/opencode/src/altimate/tools/altimate-core-correct.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Dispatcher } from "../native"

export const AltimateCoreCorrectTool = Tool.define("altimate_core_correct", {
description:
"Iteratively correct SQL using a propose-verify-refine loop via the Rust-based altimate-core engine. More thorough than fix — applies multiple correction rounds to produce valid SQL.",
"Iteratively correct SQL using a propose-verify-refine loop. More thorough than fix — applies multiple correction rounds to produce valid SQL. Provide schema_context or schema_path for accurate table/column resolution.",
parameters: z.object({
sql: z.string().describe("SQL query to correct"),
schema_path: z.string().optional().describe("Path to YAML/JSON schema file"),
Expand All @@ -17,19 +17,32 @@ export const AltimateCoreCorrectTool = Tool.define("altimate_core_correct", {
schema_path: args.schema_path ?? "",
schema_context: args.schema_context,
})
const data = result.data as Record<string, any>
const data = (result.data ?? {}) as Record<string, any>
const error = result.error ?? data.error ?? extractCorrectErrors(data)
return {
title: `Correct: ${data.success ? "CORRECTED" : "COULD NOT CORRECT"}`,
metadata: { success: result.success, iterations: data.iterations },
metadata: { success: result.success, iterations: data.iterations, ...(error && { error }) },
output: formatCorrect(data),
}
} catch (e) {
const msg = e instanceof Error ? e.message : String(e)
return { title: "Correct: ERROR", metadata: { success: false, iterations: 0 }, output: `Failed: ${msg}` }
return { title: "Correct: ERROR", metadata: { success: false, iterations: 0, error: msg }, output: `Failed: ${msg}` }
}
},
})

function extractCorrectErrors(data: Record<string, any>): string | undefined {
if (data.final_validation?.errors?.length > 0) {
const msgs = data.final_validation.errors.map((e: any) => e.message ?? String(e)).filter(Boolean)
if (msgs.length > 0) return msgs.join("; ")
}
if (Array.isArray(data.errors) && data.errors.length > 0) {
const msgs = data.errors.map((e: any) => e.message ?? String(e)).filter(Boolean)
if (msgs.length > 0) return msgs.join("; ")
}
return undefined
}

function formatCorrect(data: Record<string, any>): string {
if (data.error) return `Error: ${data.error}`
const lines: string[] = []
Expand Down
28 changes: 23 additions & 5 deletions packages/opencode/src/altimate/tools/altimate-core-equivalence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,34 +4,52 @@ import { Dispatcher } from "../native"

export const AltimateCoreEquivalenceTool = Tool.define("altimate_core_equivalence", {
description:
"Check semantic equivalence of two SQL queries using the Rust-based altimate-core engine. Determines if two queries produce the same result set regardless of syntactic differences.",
"Check semantic equivalence of two SQL queries. Determines if two queries produce the same result set regardless of syntactic differences. Provide schema_context or schema_path for accurate table/column resolution.",
parameters: z.object({
sql1: z.string().describe("First SQL query"),
sql2: z.string().describe("Second SQL query"),
schema_path: z.string().optional().describe("Path to YAML/JSON schema file"),
schema_context: z.record(z.string(), z.any()).optional().describe("Inline schema definition"),
}),
async execute(args, ctx) {
if (!args.schema_path && (!args.schema_context || Object.keys(args.schema_context).length === 0)) {
const error = "No schema provided. Provide schema_context or schema_path so table/column references can be resolved."
return { title: "Equivalence: NO SCHEMA", metadata: { success: false, equivalent: false, error }, output: `Error: ${error}` }
}
try {
const result = await Dispatcher.call("altimate_core.equivalence", {
sql1: args.sql1,
sql2: args.sql2,
schema_path: args.schema_path ?? "",
schema_context: args.schema_context,
})
const data = result.data as Record<string, any>
const data = (result.data ?? {}) as Record<string, any>
const error = result.error ?? data.error ?? extractEquivalenceErrors(data)
// "Not equivalent" is a valid analysis result, not a failure.
// Only treat it as failure when there's an actual error.
const isRealFailure = !!error
return {
title: `Equivalence: ${data.equivalent ? "EQUIVALENT" : "DIFFERENT"}`,
metadata: { success: result.success, equivalent: data.equivalent },
title: isRealFailure ? "Equivalence: ERROR" : `Equivalence: ${data.equivalent ? "EQUIVALENT" : "DIFFERENT"}`,
metadata: { success: !isRealFailure, equivalent: data.equivalent, ...(error && { error }) },
output: formatEquivalence(data),
}
} catch (e) {
const msg = e instanceof Error ? e.message : String(e)
return { title: "Equivalence: ERROR", metadata: { success: false, equivalent: false }, output: `Failed: ${msg}` }
return { title: "Equivalence: ERROR", metadata: { success: false, equivalent: false, error: msg }, output: `Failed: ${msg}` }
}
},
})

function extractEquivalenceErrors(data: Record<string, any>): string | undefined {
if (Array.isArray(data.validation_errors) && data.validation_errors.length > 0) {
const msgs = data.validation_errors
.map((e: any) => (typeof e === "string" ? e : e.message ?? String(e)))
.filter(Boolean)
return msgs.length > 0 ? msgs.join("; ") : undefined
}
return undefined
}

function formatEquivalence(data: Record<string, any>): string {
if (data.error) return `Error: ${data.error}`
const lines: string[] = []
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Dispatcher } from "../native"

export const AltimateCoreExportDdlTool = Tool.define("altimate_core_export_ddl", {
description:
"Export a YAML/JSON schema as CREATE TABLE DDL statements using the Rust-based altimate-core engine.",
"Export a YAML/JSON schema as CREATE TABLE DDL statements. Provide schema_context or schema_path for accurate table/column resolution.",
parameters: z.object({
schema_path: z.string().optional().describe("Path to YAML/JSON schema file"),
schema_context: z.record(z.string(), z.any()).optional().describe("Inline schema definition"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Dispatcher } from "../native"

export const AltimateCoreExtractMetadataTool = Tool.define("altimate_core_extract_metadata", {
description:
"Extract metadata from SQL using the Rust-based altimate-core engine. Identifies tables, columns, functions, CTEs, and other structural elements referenced in a query.",
"Extract metadata from SQL. Identifies tables, columns, functions, CTEs, and other structural elements referenced in a query.",
parameters: z.object({
sql: z.string().describe("SQL query to extract metadata from"),
dialect: z.string().optional().describe("SQL dialect (e.g. snowflake, bigquery, postgres)"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Dispatcher } from "../native"

export const AltimateCoreFingerprintTool = Tool.define("altimate_core_fingerprint", {
description:
"Compute a SHA-256 fingerprint of a schema using the Rust-based altimate-core engine. Useful for cache invalidation and change detection.",
"Compute a SHA-256 fingerprint of a schema. Useful for cache invalidation and change detection. Provide schema_context or schema_path for accurate table/column resolution.",
parameters: z.object({
schema_path: z.string().optional().describe("Path to YAML/JSON schema file"),
schema_context: z.record(z.string(), z.any()).optional().describe("Inline schema definition"),
Expand Down
Loading
Loading