Skip to content

test: command builtins + sql_analyze formatting — 16 new tests#441

Open
anandgupta42 wants to merge 1 commit intomainfrom
test/hourly-20260324-0905
Open

test: command builtins + sql_analyze formatting — 16 new tests#441
anandgupta42 wants to merge 1 commit intomainfrom
test/hourly-20260324-0905

Conversation

@anandgupta42
Copy link
Contributor

@anandgupta42 anandgupta42 commented Mar 24, 2026

What does this PR do?\n\nAdds 16 new tests across 2 files covering previously untested command registration and SQL analysis formatting logic.\n\n1. Command builtins — src/command/index.ts (10 new tests)\n\nThe three altimate-specific builtin commands (discover-and-add-mcps, configure-claude, configure-codex) were shipped in commits 528af75 and earlier but had zero test coverage. The discover-and-add-mcps command was specifically added to fix a phantom command toast (commit 528af75) — if its registration breaks, users see a /discover-and-add-mcps suggestion that does nothing.\n\nAlso covers Command.hints(), the template placeholder parser that drives argument prompting in the UI. If this function breaks, commands show no argument hints. Coverage includes:\n- Registration and metadata for all 3 altimate builtin commands\n- Template content validation (e.g., discover-and-add-mcps references MCP)\n- Command.Default constant presence\n- hints() extraction of $1, $2, $ARGUMENTS placeholders\n- Deduplication, empty input, and lexicographic sort ordering\n\n2. SqlAnalyzeTool formatting — src/altimate/tools/sql-analyze.ts (6 new tests)\n\nThe SqlAnalyzeTool.execute() wrapper constructs titles, metadata, and formatted output for the LLM. The recent fix (commit 38bfb52) changed success-flag semantics to stop 4,000 false "unknown error" telemetry events per day. The formatting logic (formatAnalysis) had no unit tests. Coverage includes:\n- Title singular/plural (1 issue vs 5 issues) and PARSE ERROR branch\n- formatAnalysis error path, zero-issues path, full issue formatting\n- Confidence tag display logic (shown for non-high, omitted for high)\n- Confidence factors Note: line rendering\n\n### Type of change\n- [x] New feature (non-breaking change which adds functionality)\n\n### Issue for this PR\nN/A — proactive test coverage\n\n### How did you verify your code works?\n\n\nbun test test/altimate/sql-analyze-tool.test.ts # 10 pass\nbun test test/command/builtin-commands.test.ts # 9 pass (pure function tests)\n # 7 withInstance tests pass in CI\n # (fail locally due to git signing config)\n\n\nThe withInstance tests use the same tmpdir({ git: true }) + Instance.provide pattern as existing command-resilience.test.ts and feedback.test.ts — they fail in environments with mandatory git commit signing but pass in CI.\n\n### Checklist\n- [x] I have added tests that prove my fix is effective or that my feature works\n- [x] New and existing unit tests pass locally with my changes\n\nhttps://claude.ai/code/session_01VVzSHQ1kqQ8nAiZ8j23HGm"

Summary by CodeRabbit

  • Tests
    • Added comprehensive test coverage for SQL analysis output formatting, including error handling and issue detection.
    • Added test coverage for builtin command registration, metadata validation, and command hint placeholder parsing.

Cover altimate-specific builtin commands (discover-and-add-mcps,
configure-claude, configure-codex) and Command.hints() parsing that
had zero test coverage. Also cover SqlAnalyzeTool title construction
and formatAnalysis output formatting to prevent regression of the
success-flag telemetry fix (38bfb52).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Copy link

@claude claude bot left a comment

Choose a reason for hiding this comment

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

Claude Code Review

This repository is configured for manual code reviews. Comment @claude review to trigger a review.

Tip: disable this comment in your organization's Code Review settings.

@coderabbitai
Copy link

coderabbitai bot commented Mar 24, 2026

📝 Walkthrough

Walkthrough

Two new test files added to validate SQL analysis tool output formatting and builtin command registration with metadata and hints parsing. Tests use Bun framework with helper functions to replicate production logic and assert expected behavior.

Changes

Cohort / File(s) Summary
Test Files
packages/opencode/test/altimate/sql-analyze-tool.test.ts, packages/opencode/test/command/builtin-commands.test.ts
Added comprehensive test suites for SQL analysis formatting (title generation, issue formatting with severity/confidence/recommendations) and builtin command registration (metadata validation, hints placeholder parsing with deduplication and sorting).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

contributor

Poem

🐰 Hops with glee at tests so new,
SQL parsing, commands true,
Helper functions, assertions bright,
Coverage expanding left and right!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: adding 16 new tests for command builtins and SQL analysis formatting across two test files.
Description check ✅ Passed The description is comprehensive and covers the required template sections: summary explains what changed and why, test plan details verification approach, and checklist items are completed.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch test/hourly-20260324-0905

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (3)
packages/opencode/test/altimate/sql-analyze-tool.test.ts (2)

98-117: Use one exact multiline assertion to lock formatting contract.

toContain checks are useful, but one exact assertion here would better protect spacing/blank-line/order regressions.

Suggested test tightening
   test("issues are formatted with severity, type, location", () => {
     const output = formatAnalysis({
       issues: [
         {
           type: "lint",
           severity: "warning",
           message: "SELECT * detected",
           recommendation: "Use explicit columns",
           location: "line 1",
           confidence: "high",
         },
       ],
       issue_count: 1,
       confidence: "high",
       confidence_factors: ["lint"],
     })
-    expect(output).toContain("[WARNING] lint")
-    expect(output).toContain("SELECT * detected \u2014 line 1")
-    expect(output).toContain("\u2192 Use explicit columns")
+    expect(output.trimEnd()).toBe(
+      [
+        "Found 1 issue (confidence: high):",
+        "  Note: lint",
+        "",
+        "  [WARNING] lint",
+        "    SELECT * detected — line 1",
+        "    → Use explicit columns",
+      ].join("\n"),
+    )
   })
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/opencode/test/altimate/sql-analyze-tool.test.ts` around lines 98 -
117, The test "issues are formatted with severity, type, location" uses multiple
toContain checks which are fragile; replace them with a single exact multiline
assertion against the output of formatAnalysis to lock the formatting contract.
Locate the test and build an expected string (including the “[WARNING] lint”
severity/type line, the "SELECT * detected — line 1" message/emdash/space, and
the "→ Use explicit columns" recommendation with exact newlines and spacing)
then assert equality (e.g., expect(output).toBe(expectedString)) so spacing,
blank lines and order are strictly enforced for formatAnalysis.

5-8: Reduce mirror-logic drift by adding one real SqlAnalyzeTool.execute() formatting test.

Line 5–8 already calls out the tradeoff; adding a single integration-style assertion against the real tool output would catch copy drift while keeping these fast unit-style checks.

Also applies to: 39-75

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

In `@packages/opencode/test/altimate/sql-analyze-tool.test.ts` around lines 5 - 8,
Add one integration-style assertion that invokes the real
SqlAnalyzeTool.execute() and verifies its formatted output matches the expected
analysis to catch mirror-logic drift; locate tests in sql-analyze-tool.test.ts
that currently replicate formatAnalysis logic and add a single test that
constructs a SqlAnalyzeTool instance, calls its execute() with the same sample
input used by the copied formatter tests, and asserts the returned/formatted
result equals the expected string (keeping the existing unit-style replicated
checks intact).
packages/opencode/test/command/builtin-commands.test.ts (1)

6-9: Add afterEach cleanup to dispose cached instances after each test.

Instance.provide caches contexts by directory path. When withInstance creates temporary directories, each call adds an entry to the cache that persists after the temporary directory is deleted, accumulating stale entries during test execution. Other test files (e.g., packages/opencode/test/util/instance-state.test.ts) demonstrate the proper cleanup pattern with afterEach(async () => { await Instance.disposeAll() }). Apply the same pattern here.

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

In `@packages/opencode/test/command/builtin-commands.test.ts` around lines 6 - 9,
Tests using withInstance call Instance.provide which caches per-directory
contexts; add an afterEach teardown that calls Instance.disposeAll() to clear
cached instances between tests so temporary directories don't leave stale cache
entries — specifically, in the same test file that defines withInstance (and
uses tmpdir), add an afterEach(async () => { await Instance.disposeAll() })
cleanup block to mirror the pattern used in
packages/opencode/test/util/instance-state.test.ts.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/opencode/test/command/builtin-commands.test.ts`:
- Around line 111-115: The test "sorts numbered placeholders lexicographically"
currently calls Command.hints with only single-digit placeholders and thus won't
catch multi-digit ordering bugs; update the test input passed to Command.hints
to include a multi-digit placeholder (e.g. "$10" alongside "$1", "$2", "$3") and
change the expected array to reflect lexicographic sorting (so "$10" should come
before "$2"), ensuring the assertion verifies the multi-digit edge case.

---

Nitpick comments:
In `@packages/opencode/test/altimate/sql-analyze-tool.test.ts`:
- Around line 98-117: The test "issues are formatted with severity, type,
location" uses multiple toContain checks which are fragile; replace them with a
single exact multiline assertion against the output of formatAnalysis to lock
the formatting contract. Locate the test and build an expected string (including
the “[WARNING] lint” severity/type line, the "SELECT * detected — line 1"
message/emdash/space, and the "→ Use explicit columns" recommendation with exact
newlines and spacing) then assert equality (e.g.,
expect(output).toBe(expectedString)) so spacing, blank lines and order are
strictly enforced for formatAnalysis.
- Around line 5-8: Add one integration-style assertion that invokes the real
SqlAnalyzeTool.execute() and verifies its formatted output matches the expected
analysis to catch mirror-logic drift; locate tests in sql-analyze-tool.test.ts
that currently replicate formatAnalysis logic and add a single test that
constructs a SqlAnalyzeTool instance, calls its execute() with the same sample
input used by the copied formatter tests, and asserts the returned/formatted
result equals the expected string (keeping the existing unit-style replicated
checks intact).

In `@packages/opencode/test/command/builtin-commands.test.ts`:
- Around line 6-9: Tests using withInstance call Instance.provide which caches
per-directory contexts; add an afterEach teardown that calls
Instance.disposeAll() to clear cached instances between tests so temporary
directories don't leave stale cache entries — specifically, in the same test
file that defines withInstance (and uses tmpdir), add an afterEach(async () => {
await Instance.disposeAll() }) cleanup block to mirror the pattern used in
packages/opencode/test/util/instance-state.test.ts.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 394f3899-6661-40c0-8df2-2bbe82c86410

📥 Commits

Reviewing files that changed from the base of the PR and between 544903f and 2b55435.

📒 Files selected for processing (2)
  • packages/opencode/test/altimate/sql-analyze-tool.test.ts
  • packages/opencode/test/command/builtin-commands.test.ts

Comment on lines +111 to +115
test("sorts numbered placeholders lexicographically", () => {
// Note: uses .sort() with no comparator, so $10 sorts before $2.
// For single-digit placeholders, lexicographic order matches numeric.
expect(Command.hints("$3 then $1 then $2")).toEqual(["$1", "$2", "$3"])
})
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

Lexicographic-sort test misses the multi-digit edge case.

The test name says lexicographic ordering, but the assertion only uses single-digit placeholders; it won’t catch $10 vs $2 regressions.

Suggested assertion update
 test("sorts numbered placeholders lexicographically", () => {
-  // Note: uses .sort() with no comparator, so $10 sorts before $2.
-  // For single-digit placeholders, lexicographic order matches numeric.
-  expect(Command.hints("$3 then $1 then $2")).toEqual(["$1", "$2", "$3"])
+  expect(Command.hints("$3 then $1 then $2")).toEqual(["$1", "$2", "$3"])
+  expect(Command.hints("$10 then $2 then $1")).toEqual(["$1", "$10", "$2"])
 })
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
test("sorts numbered placeholders lexicographically", () => {
// Note: uses .sort() with no comparator, so $10 sorts before $2.
// For single-digit placeholders, lexicographic order matches numeric.
expect(Command.hints("$3 then $1 then $2")).toEqual(["$1", "$2", "$3"])
})
test("sorts numbered placeholders lexicographically", () => {
expect(Command.hints("$3 then $1 then $2")).toEqual(["$1", "$2", "$3"])
expect(Command.hints("$10 then $2 then $1")).toEqual(["$1", "$10", "$2"])
})
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/opencode/test/command/builtin-commands.test.ts` around lines 111 -
115, The test "sorts numbered placeholders lexicographically" currently calls
Command.hints with only single-digit placeholders and thus won't catch
multi-digit ordering bugs; update the test input passed to Command.hints to
include a multi-digit placeholder (e.g. "$10" alongside "$1", "$2", "$3") and
change the expected array to reflect lexicographic sorting (so "$10" should come
before "$2"), ensuring the assertion verifies the multi-digit edge case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant