Skip to content
Closed
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
193 changes: 193 additions & 0 deletions packages/opencode/test/altimate/tools/sql-analyze-tool.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
/**
* Tests for SqlAnalyzeTool.execute — success flag semantics and output formatting.
*
* The bug fix AI-5975 changed sql_analyze to report success:true when analysis
* completes (even when issues are found). Regression would cause ~4000 false
* "unknown error" telemetry events per day.
*/
import { describe, test, expect, spyOn, afterAll, beforeEach } from "bun:test"
import * as Dispatcher from "../../../src/altimate/native/dispatcher"
import { SqlAnalyzeTool } from "../../../src/altimate/tools/sql-analyze"
import { SessionID, MessageID } from "../../../src/session/schema"

beforeEach(() => {
process.env.ALTIMATE_TELEMETRY_DISABLED = "true"
})
Comment on lines +13 to +15
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Preserve the original telemetry env value during teardown

Cleanup currently always deletes ALTIMATE_TELEMETRY_DISABLED, which can clobber a pre-existing test-runner/CI setting. Capture the original value and restore it in teardown instead of unconditional delete.

Suggested patch
+const originalTelemetryDisabled = process.env.ALTIMATE_TELEMETRY_DISABLED
+
 beforeEach(() => {
   process.env.ALTIMATE_TELEMETRY_DISABLED = "true"
 })
@@
 afterAll(() => {
   dispatcherSpy?.mockRestore()
-  delete process.env.ALTIMATE_TELEMETRY_DISABLED
+  if (originalTelemetryDisabled === undefined) {
+    delete process.env.ALTIMATE_TELEMETRY_DISABLED
+  } else {
+    process.env.ALTIMATE_TELEMETRY_DISABLED = originalTelemetryDisabled
+  }
 })

Also applies to: 35-38

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/opencode/test/altimate/tools/sql-analyze-tool.test.ts` around lines
13 - 15, Change the test setup/teardown to preserve any pre-existing
ALTIMATE_TELEMETRY_DISABLED value: in the beforeEach that sets
process.env.ALTIMATE_TELEMETRY_DISABLED = "true", capture the original value
into a module-scoped variable (e.g., origTelemetryDisabled) and then set the env
var; in the corresponding afterEach (and the similar teardown at the second
location around lines 35-38) restore process.env.ALTIMATE_TELEMETRY_DISABLED to
origTelemetryDisabled if it is defined, otherwise delete it, rather than always
deleting it unconditionally.


const ctx = {
sessionID: SessionID.make("ses_test"),
messageID: MessageID.make("msg_test"),
callID: "call_test",
agent: "build",
abort: AbortSignal.any([]),
messages: [],
metadata: () => {},
ask: async () => {},
}

let dispatcherSpy: ReturnType<typeof spyOn>

function mockDispatcher(response: any) {
dispatcherSpy?.mockRestore()
dispatcherSpy = spyOn(Dispatcher, "call").mockImplementation(async () => response)
}

afterAll(() => {
dispatcherSpy?.mockRestore()
delete process.env.ALTIMATE_TELEMETRY_DISABLED
})

describe("SqlAnalyzeTool.execute: success semantics", () => {
test("issues found → success:true, no error in metadata", async () => {
mockDispatcher({
success: true,
issues: [
{
type: "lint",
severity: "warning",
message: "SELECT * detected",
recommendation: "List columns explicitly",
confidence: "high",
},
],
issue_count: 1,
confidence: "high",
confidence_factors: ["lint"],
})

const tool = await SqlAnalyzeTool.init()
const result = await tool.execute(
{ sql: "SELECT * FROM t", dialect: "snowflake" },
ctx as any,
)

expect(result.metadata.success).toBe(true)
expect(result.metadata.error).toBeUndefined()
expect(result.title).toContain("1 issue")
expect(result.title).not.toContain("PARSE ERROR")
})

test("zero issues → success:true, 'No anti-patterns' output", async () => {
mockDispatcher({
success: true,
issues: [],
issue_count: 0,
confidence: "high",
confidence_factors: [],
})

const tool = await SqlAnalyzeTool.init()
const result = await tool.execute(
{ sql: "SELECT id FROM t", dialect: "snowflake" },
ctx as any,
)

expect(result.metadata.success).toBe(true)
expect(result.output).toContain("No anti-patterns")
expect(result.title).toContain("0 issues")
})

test("parse error → success:false, error in metadata and title", async () => {
mockDispatcher({
success: false,
issues: [],
issue_count: 0,
confidence: "low",
confidence_factors: [],
error: "syntax error near SELECT",
})

const tool = await SqlAnalyzeTool.init()
const result = await tool.execute(
{ sql: "SELEC FROM", dialect: "snowflake" },
ctx as any,
)

expect(result.metadata.success).toBe(false)
expect(result.metadata.error).toBe("syntax error near SELECT")
expect(result.title).toContain("PARSE ERROR")
})

test("dispatcher throws → catch block returns ERROR title", async () => {
dispatcherSpy?.mockRestore()
dispatcherSpy = spyOn(Dispatcher, "call").mockRejectedValue(new Error("native crash"))

const tool = await SqlAnalyzeTool.init()
const result = await tool.execute(
{ sql: "SELECT 1", dialect: "snowflake" },
ctx as any,
)

expect(result.title).toBe("Analyze: ERROR")
expect(result.metadata.success).toBe(false)
expect(result.metadata.error).toBe("native crash")
expect(result.output).toContain("Failed to analyze SQL: native crash")
})
})

describe("SqlAnalyzeTool.execute: formatAnalysis output", () => {
test("singular issue → '1 issue' not '1 issues'", async () => {
mockDispatcher({
success: true,
issues: [
{
type: "lint",
severity: "warning",
message: "test issue",
recommendation: "fix it",
confidence: "high",
},
],
issue_count: 1,
confidence: "high",
confidence_factors: ["lint"],
})

const tool = await SqlAnalyzeTool.init()
const result = await tool.execute(
{ sql: "x", dialect: "snowflake" },
ctx as any,
)

expect(result.output).toContain("Found 1 issue ")
expect(result.output).not.toContain("1 issues")
})

test("multiple issues with location, confidence, and factors", async () => {
mockDispatcher({
success: true,
issues: [
{
type: "lint",
severity: "warning",
message: "SELECT * used",
recommendation: "List columns",
confidence: "high",
},
{
type: "safety",
severity: "high",
message: "DROP TABLE detected",
recommendation: "Use caution",
location: "chars 0-5",
confidence: "medium",
},
],
issue_count: 2,
confidence: "high",
confidence_factors: ["lint", "safety"],
})

const tool = await SqlAnalyzeTool.init()
const result = await tool.execute(
{ sql: "x", dialect: "snowflake" },
ctx as any,
)

expect(result.output).toContain("2 issues")
expect(result.output).toContain("[WARNING] lint")
expect(result.output).toContain("[HIGH] safety [medium confidence]")
expect(result.output).toContain("chars 0-5")
expect(result.output).toContain("Note: lint; safety")
})
})
39 changes: 39 additions & 0 deletions packages/opencode/test/command/hints.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { describe, test, expect } from "bun:test"
import { Command } from "../../src/command/index"

describe("Command.hints: template placeholder parsing", () => {
test("extracts numbered placeholders in order", () => {
expect(Command.hints("run $1 with $2")).toEqual(["$1", "$2"])
})

test("deduplicates repeated placeholders", () => {
expect(Command.hints("compare $1 to $1")).toEqual(["$1"])
})

test("sorts numbered placeholders lexicographically", () => {
// String sort: "$1" < "$2" < "$3"
expect(Command.hints("$3 then $1 then $2")).toEqual(["$1", "$2", "$3"])
})

test("$ARGUMENTS appears after numbered placeholders", () => {
expect(Command.hints("do $1 $ARGUMENTS")).toEqual(["$1", "$ARGUMENTS"])
})

test("returns only $ARGUMENTS when no numbered placeholders", () => {
expect(Command.hints("run $ARGUMENTS")).toEqual(["$ARGUMENTS"])
})

test("returns empty array when no placeholders", () => {
expect(Command.hints("static template with no args")).toEqual([])
})

test("multi-digit placeholders sort lexicographically, not numerically", () => {
// String sort puts "$10" before "$2" — this is the actual behavior.
// If a template uses $10+, the TUI hint order will be $1, $10, $2.
expect(Command.hints("$10 $2 $1")).toEqual(["$1", "$10", "$2"])
})

test("empty template returns empty array", () => {
expect(Command.hints("")).toEqual([])
})
})
Loading