Skip to content

feat: Add SQL Query Generator AgentKit#159

Open
aakritipp wants to merge 1 commit into
Lamatic:mainfrom
aakritipp:feat/sql-query-generator
Open

feat: Add SQL Query Generator AgentKit#159
aakritipp wants to merge 1 commit into
Lamatic:mainfrom
aakritipp:feat/sql-query-generator

Conversation

@aakritipp
Copy link
Copy Markdown

@aakritipp aakritipp commented May 16, 2026

What This Kit Does

An AI-powered agent that converts natural language questions into optimized SQL queries. Users paste their database schema and ask questions in plain English. The agent returns production-ready SELECT queries with explanations, confidence scores, and assumption tracking.

Problem It Solves

Writing SQL from scratch is time-consuming, especially for complex joins and aggregations. This tool lets developers and analysts quickly get a working query by describing what they need in plain English.

Key Features

  • Generates read-only SELECT queries only (never INSERT/UPDATE/DELETE/DROP)
  • Returns structured output: SQL, explanation, tables used, assumptions, confidence
  • Cross-database compatible (PostgreSQL, MySQL, SQLite)
  • Handles ambiguous questions gracefully

Providers & Prerequisites

  • Any LLM provider configured in Lamatic (e.g., Anthropic, OpenAI, Google)

How to Run Locally

  1. cd kits/sql-query-generator/apps
  2. npm install
  3. cp .env.example .env.local and fill in values
  4. npm run dev

Live Preview

https://agent-kit-git-vercel-react-server-co-47ca9a-aakritipps-projects.vercel.app

Lamatic Flow

Flow ID: 26053fbe-e183-48b9-a6a1-a2eb14dac2aa

Checklist

  • Kit runs locally with npm run dev
  • .env.example has no secrets, only placeholders
  • README.md documents setup and usage
  • Folder structure follows kits/sql-query-generator/
  • lamatic.config.ts is present and valid
  • All flows exported in flows/ folder
  • Vercel deployment works
  • Live preview URL works end-to-end

Files Added

Documentation

  • README.md - Complete setup and usage guide including prerequisites, local run instructions, deployment steps, and environment variable reference
  • agent.md - Architecture overview describing the SQL Query Generator Agent and its design decisions (read-only enforcement, structured JSON output, cross-database compatibility)

Flow Configuration

  • flows/sql-query-generator.ts - Core flow definition exporting metadata, inputs, references, nodes, and edges
  • lamatic.config.ts - Kit configuration with metadata, author info, required step configuration, and links
  • prompts/sql-query-generator_system.md - System prompt instructing the LLM to generate optimized SELECT-only SQL queries with structured JSON output
  • prompts/sql-query-generator_user.md - User prompt template with input variables for schema and question
  • constitutions/default.md - Safety constitution emphasizing accuracy and avoiding data-modifying statements
  • model-configs/sql-query-generator_model.ts - Model configuration with text generator settings

Next.js Application

  • apps/package.json - Project dependencies (lamatic, next, react, tailwind, typescript)
  • apps/tsconfig.json - TypeScript configuration with strict type-checking and path aliases
  • apps/next.config.mjs - Next.js configuration file
  • apps/postcss.config.mjs - PostCSS configuration with Tailwind CSS
  • apps/.env.example - Environment variable placeholders (flow ID, API URL, project ID, API key)
  • apps/.gitignore - Git ignore rules for Next.js build artifacts and environment files
  • apps/app/layout.tsx - Root layout with metadata (page title: "SQL Query Generator")
  • apps/app/page.tsx - Interactive UI component with schema/question inputs, result display with confidence badge, SQL with copy button, explanation, tables list, and assumptions
  • apps/app/globals.css - Global stylesheet importing Tailwind CSS
  • apps/lib/lamatic-client.ts - Lamatic SDK client initialization
  • apps/actions/orchestrate.ts - Server action generateQuery() that validates inputs, calls the Lamatic flow, parses JSON response, and returns typed result

Flow Architecture & Node Types

The SQL Query Generator uses a 3-node sequential flow:

  1. triggerNode ("API Request") - Entry point accepting schema and question as JSON inputs
  2. LLMNode ("Generate Text") - Processes inputs through an LLM using:
    • System prompt defining SQL generation rules and JSON output format
    • User prompt containing the database schema and natural language question
    • Configurable text generation model
  3. responseNode ("API Response") - Maps LLM output to a result field and returns JSON response

The flow transforms natural language questions into structured SQL outputs containing: SQL query, explanation, tables used, assumptions, and confidence score (high/medium/low). It enforces read-only SELECT queries, supports PostgreSQL/MySQL/SQLite, and handles ambiguous questions gracefully.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 16, 2026

Review Change Stack

Walkthrough

This pull request delivers the complete SQL Query Generator kit—a new Lamatic agent that translates natural-language database questions into optimized, read-only SELECT queries. It bundles a schema-constrained LLM flow, server-side orchestration, and a Next.js UI frontend with sample data, error handling, and result display including confidence scoring and SQL explanation.

Changes

SQL Query Generator Kit

Layer / File(s) Summary
Flow definition and LLM prompts
kits/sql-query-generator/flows/sql-query-generator.ts, kits/sql-query-generator/prompts/*, kits/sql-query-generator/model-configs/*, kits/sql-query-generator/constitutions/default.md
The flow wires schema and question inputs to an LLM node configured with system and user prompts that enforce schema-safe, SELECT-only SQL generation with deterministic JSON output (sql, explanation, tables_used, assumptions, confidence).
Server orchestration and response parsing
kits/sql-query-generator/apps/lib/lamatic-client.ts, kits/sql-query-generator/apps/actions/orchestrate.ts
Lamatic client is initialized from environment variables, and the exported generateQuery server action validates inputs, executes the flow, parses markdown-wrapped JSON responses, and returns typed success/error tuples.
Next.js app infrastructure and configuration
kits/sql-query-generator/apps/package.json, kits/sql-query-generator/apps/tsconfig.json, kits/sql-query-generator/apps/next.config.mjs, kits/sql-query-generator/apps/postcss.config.mjs, kits/sql-query-generator/apps/app/globals.css, kits/sql-query-generator/apps/app/layout.tsx, kits/sql-query-generator/apps/.env.example, kits/sql-query-generator/apps/.gitignore
Next.js app is configured with TypeScript strict mode, Tailwind CSS, PostCSS, ES2017 targets, and path aliases; root layout sets metadata and document structure; environment variables and ignore patterns are declared.
Interactive UI page and result display
kits/sql-query-generator/apps/app/page.tsx
Home component manages schema and question state, calls generateQuery on submit with loading/error feedback, and renders confidence badges, copy-able SQL blocks, explanations, table-used chips, and optional assumptions.
Kit configuration and documentation
kits/sql-query-generator/lamatic.config.ts, kits/sql-query-generator/README.md, kits/sql-query-generator/agent.md
Kit metadata, author, tags, and required flow-ID step configuration are declared; README documents prerequisites, setup, local/Vercel deployment, and architecture; agent.md outlines design constraints and flow responsibilities.

Suggested reviewers

  • amanintech
  • d-pamneja
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat: Add SQL Query Generator AgentKit' clearly and concisely describes the main change—adding a complete new SQL Query Generator AgentKit with all supporting files, flows, and UI components.
Description check ✅ Passed The description comprehensively covers the kit's purpose, problem solved, key features, prerequisites, local run instructions, and includes a detailed checklist confirming all repository requirements are met.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@github-actions
Copy link
Copy Markdown

PR Validation Results

New Contributions Detected

  • Kit: kits/sql-query-generator/constitutions
  • Kit: kits/sql-query-generator/flows
  • Kit: kits/sql-query-generator/README.md
  • Kit: kits/sql-query-generator/model-configs
  • Kit: kits/sql-query-generator/lamatic.config.ts
  • Kit: kits/sql-query-generator/prompts
  • Kit: kits/sql-query-generator/agent.md
  • Kit: kits/sql-query-generator/apps

Check Results

Check Status
No edits to existing projects ✅ Pass
Required root files present ❌ Fail
Flow folder structure valid ✅ Pass
No changes outside contribution dirs ✅ Pass

Errors

  • ❌ Missing config.json in kits/sql-query-generator/constitutions
  • ❌ Missing README.md in kits/sql-query-generator/constitutions
  • ❌ Missing flows/ directory in kits/sql-query-generator/constitutions
  • ❌ Missing config.json in kits/sql-query-generator/flows
  • ❌ Missing README.md in kits/sql-query-generator/flows
  • ❌ Missing flows/ directory in kits/sql-query-generator/flows
  • ❌ Missing config.json in kits/sql-query-generator/README.md
  • ❌ Missing README.md in kits/sql-query-generator/README.md
  • ❌ Missing flows/ directory in kits/sql-query-generator/README.md
  • ❌ Missing config.json in kits/sql-query-generator/model-configs
  • ❌ Missing README.md in kits/sql-query-generator/model-configs
  • ❌ Missing flows/ directory in kits/sql-query-generator/model-configs
  • ❌ Missing config.json in kits/sql-query-generator/lamatic.config.ts
  • ❌ Missing README.md in kits/sql-query-generator/lamatic.config.ts
  • ❌ Missing flows/ directory in kits/sql-query-generator/lamatic.config.ts
  • ❌ Missing config.json in kits/sql-query-generator/prompts
  • ❌ Missing README.md in kits/sql-query-generator/prompts
  • ❌ Missing flows/ directory in kits/sql-query-generator/prompts
  • ❌ Missing config.json in kits/sql-query-generator/agent.md
  • ❌ Missing README.md in kits/sql-query-generator/agent.md
  • ❌ Missing flows/ directory in kits/sql-query-generator/agent.md
  • ❌ Missing config.json in kits/sql-query-generator/apps
  • ❌ Missing README.md in kits/sql-query-generator/apps
  • ❌ Missing flows/ directory in kits/sql-query-generator/apps

🛑 Please fix the errors above before this PR can be merged.

Refer to CONTRIBUTING.md and CLAUDE.md for the expected folder structure.

@github-actions
Copy link
Copy Markdown

github-actions Bot commented Jun 3, 2026

:robot_face: AgentKit Structural Validation

New Contributions Detected

  • Kit: kits/sql-query-generator

Check Results

Check Status
No edits to existing kits ✅ Pass
Required root files present ✅ Pass
Flow .ts files present ✅ Pass
lamatic.config.ts valid ✅ Pass
No changes outside kits/ ✅ Pass

⚠️ Warnings

  • kits/sql-query-generator is missing .env.example — bundles and kits should include one

🎉 All checks passed! This contribution follows the AgentKit structure.

Copy link
Copy Markdown
Contributor

@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: 12

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@kits/sql-query-generator/agent.md`:
- Around line 3-4: The "## Overview" heading in agent.md needs a blank line
after it to satisfy MD022; insert a single empty line immediately following the
"## Overview" heading so the heading is separated from the paragraph that
follows, and if this file is generated from a template (e.g., the
constitutions/default.md template used by kits/*), apply the same change in that
template (update the "## Overview" heading in constitutions/default.md) so
future kits inherit the correct spacing.
- Around line 6-19: Add a blank line after each Markdown heading in this
document (e.g., after "Architecture", "Key Design Decisions", and "Flows") to
satisfy MD022; update the file's headings so there is one empty line between
each heading and the following paragraph/list. Also fix the source template
(kits/*/constitutions/default.md) that generates these kit README/constitution
files so future kits are created with correct blank lines after headings.

In `@kits/sql-query-generator/apps/.env.example`:
- Around line 1-4: Update the .env example to remove spaces around the equals
sign so entries follow KEY=VALUE convention; specifically change lines for
SQL_QUERY_GENERATOR_FLOW_ID, LAMATIC_API_URL, LAMATIC_PROJECT_ID, and
LAMATIC_API_KEY to use SQL_QUERY_GENERATOR_FLOW_ID="YOUR_FLOW_ID",
LAMATIC_API_URL="YOUR_API_ENDPOINT", LAMATIC_PROJECT_ID="YOUR_PROJECT_ID", and
LAMATIC_API_KEY="YOUR_API_KEY" (no spaces around =).

In `@kits/sql-query-generator/apps/actions/orchestrate.ts`:
- Around line 19-31: parseResponse currently returns JSON.parse(cleaned) cast to
SQLGeneratorResult without runtime shape checks; add defensive validation after
parsing in parseResponse to ensure the returned object conforms to
SQLGeneratorResult: verify parsed.sql and parsed.explanation are strings (or set
safe defaults), ensure parsed.tables_used is an array (or []), ensure
parsed.assumptions is a string (or null/empty), and validate parsed.confidence
against allowed values ["high","medium","low"] (default to "low" if invalid);
construct and return a sanitized object matching SQLGeneratorResult rather than
returning the raw parsed value so downstream calls like
confidenceColor(result.confidence) and table/assumption rendering cannot crash.

In `@kits/sql-query-generator/apps/app/page.tsx`:
- Around line 46-60: The form allows editing the schema and question while
handleSubmit is running (loading true), which can confuse users; update the UI
to disable the input controls when loading is true: wire the loading state
(loading) into the textarea/input elements that bind to schema and question so
they receive disabled={loading} (and apply any existing disabled styling) and
ensure any buttons or interactive controls related to generateQuery also respect
loading; adjust any client-side handlers that mutate schema/question during
loading to be no-ops or blocked while loading is true.
- Around line 95-100: Import the required icons from lucide-react (e.g.,
FileCode and Sparkles or Zap) at the top of the module and add them to the two
button JSX elements that call loadSample and the generate handler (e.g.,
generateSql/generate) so the "Load sample" and "Generate SQL" buttons render
icons alongside their labels; update the button markup to include the icon
components and adjust spacing classes (e.g., add a small gap and align items) to
match existing styling while keeping the onClick handlers (loadSample and
generate*) unchanged.
- Around line 6-12: QueryResult is a duplicate of SQLGeneratorResult; remove the
local QueryResult type and instead export SQLGeneratorResult from
actions/orchestrate.ts (ensure it's exported as a named export) and import that
type into this file, then update any usages/state declarations that referenced
QueryResult to use SQLGeneratorResult (references: QueryResult,
SQLGeneratorResult, actions/orchestrate.ts, and any state variables in page.tsx
that were typed with QueryResult).
- Around line 102-117: The two textarea controls bound to value={schema} and
value={question} lack semantic linkage to their visual labels; add unique id
attributes (e.g., "schema-textarea" and "question-textarea") to those textarea
elements, update the corresponding <label> elements to include htmlFor set to
those ids, and also add either aria-label or aria-labelledby on each textarea
for screen readers (or use aria-labelledby pointing to the label text) so the
schema and question inputs (the elements using setSchema and setQuestion) are
properly announced.
- Around line 160-167: Update the Copy button to use the lucide-react Copy icon
and add accessibility attributes: import Copy from 'lucide-react' at the top of
page.tsx, replace the button content so the icon is rendered (e.g., <Copy .../>)
alongside or instead of the "Copy" text, and add an aria-label like
aria-label="Copy SQL to clipboard" (optionally title="Copy SQL") to the <button>
element; keep the existing onClick handler
(navigator.clipboard.writeText(result.sql)) and existing classes but adjust icon
sizing via className on the Copy component for visual parity.

In `@kits/sql-query-generator/apps/package.json`:
- Line 17: The dependency "lamatic": "latest" in package.json is unpinned and
must be fixed; replace the "latest" specifier with an explicit, immutable
version (e.g., the version from this app's lockfile or the current npm registry)
so the entry reads "lamatic": "<exact-version>"; update package.json accordingly
and run npm/yarn install to refresh the lockfile so the kit has a pinned,
reproducible dependency.

In `@kits/sql-query-generator/README.md`:
- Around line 46-51: Add a language identifier to the markdown code fence that
shows the environment variables (the block containing
SQL_QUERY_GENERATOR_FLOW_ID, LAMATIC_API_URL, LAMATIC_PROJECT_ID,
LAMATIC_API_KEY) so editors render proper syntax highlighting; change the
opening triple backticks to include a language like env or bash (e.g., ```env)
and keep the variable lines unchanged.
- Line 41: Replace the README's local env copy step so developers create a
Next.js safe local file: change the instruction that runs "cp .env.example .env"
to copy into ".env.local" instead (update the line that currently reads cp
.env.example .env to use .env.local); also verify the repository .gitignore
excludes both .env and .env.local to avoid committing secrets.
🪄 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 (base), Organization UI (inherited)

Review profile: ASSERTIVE

Plan: Pro

Run ID: 51f5c30c-b072-4e4f-82e8-0534afb447c2

📥 Commits

Reviewing files that changed from the base of the PR and between 6e60d64 and c95301c.

⛔ Files ignored due to path filters (1)
  • kits/sql-query-generator/apps/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (19)
  • kits/sql-query-generator/README.md
  • kits/sql-query-generator/agent.md
  • kits/sql-query-generator/apps/.env.example
  • kits/sql-query-generator/apps/.gitignore
  • kits/sql-query-generator/apps/actions/orchestrate.ts
  • kits/sql-query-generator/apps/app/globals.css
  • kits/sql-query-generator/apps/app/layout.tsx
  • kits/sql-query-generator/apps/app/page.tsx
  • kits/sql-query-generator/apps/lib/lamatic-client.ts
  • kits/sql-query-generator/apps/next.config.mjs
  • kits/sql-query-generator/apps/package.json
  • kits/sql-query-generator/apps/postcss.config.mjs
  • kits/sql-query-generator/apps/tsconfig.json
  • kits/sql-query-generator/constitutions/default.md
  • kits/sql-query-generator/flows/sql-query-generator.ts
  • kits/sql-query-generator/lamatic.config.ts
  • kits/sql-query-generator/model-configs/sql-query-generator_model.ts
  • kits/sql-query-generator/prompts/sql-query-generator_system.md
  • kits/sql-query-generator/prompts/sql-query-generator_user.md

Comment on lines +3 to +4
## Overview
This agent converts natural language questions into optimized, read-only SQL queries. Users provide their database schema (as CREATE TABLE statements) and ask questions in plain English. The agent returns a well-structured SQL SELECT query along with an explanation, the tables used, any assumptions made, and a confidence score.
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial | 💤 Low value

Agent, your documentation formatting needs a tactical adjustment.

The heading "## Overview" (line 3) should have a blank line after it according to markdown best practices (MD022). This improves readability across different renderers.

Note: If agent.md is a templated file like constitutions/default.md, this fix should be applied at the template/source level so all future kits inherit the correct format.

📄 Proposed fix for heading spacing
 ## Overview
+
 This agent converts natural language questions into optimized, read-only SQL queries. Users provide their database schema (as CREATE TABLE statements) and ask questions in plain English. The agent returns a well-structured SQL SELECT query along with an explanation, the tables used, any assumptions made, and a confidence score.

Based on learnings: "In kits/*/constitutions/default.md, the default.md constitution file is a templated/auto-generated file that ships as part of every new kit. It may have markdownlint MD022 (blanks-around-headings) warnings by default. When flagging such warnings in these files, note that the fix should be applied at the template/source level so all future kits inherit the corrected format."

📝 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
## Overview
This agent converts natural language questions into optimized, read-only SQL queries. Users provide their database schema (as CREATE TABLE statements) and ask questions in plain English. The agent returns a well-structured SQL SELECT query along with an explanation, the tables used, any assumptions made, and a confidence score.
## Overview
This agent converts natural language questions into optimized, read-only SQL queries. Users provide their database schema (as CREATE TABLE statements) and ask questions in plain English. The agent returns a well-structured SQL SELECT query along with an explanation, the tables used, any assumptions made, and a confidence score.
🧰 Tools
🪛 markdownlint-cli2 (0.22.1)

[warning] 3-3: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@kits/sql-query-generator/agent.md` around lines 3 - 4, The "## Overview"
heading in agent.md needs a blank line after it to satisfy MD022; insert a
single empty line immediately following the "## Overview" heading so the heading
is separated from the paragraph that follows, and if this file is generated from
a template (e.g., the constitutions/default.md template used by kits/*), apply
the same change in that template (update the "## Overview" heading in
constitutions/default.md) so future kits inherit the correct spacing.

Comment on lines +6 to +19
## Architecture
The agent uses a single Lamatic Flow with three nodes:
1. **API Request** — receives the database schema and question via GraphQL
2. **Generate Text (LLM)** — processes the inputs using a system prompt tuned for SQL generation
3. **API Response** — returns the generated SQL as a JSON string

## Key Design Decisions
- **Read-only queries only** — the agent is explicitly instructed to never generate INSERT, UPDATE, DELETE, DROP, or ALTER statements, making it safe for production use
- **Structured JSON output** — the response includes sql, explanation, tables_used, assumptions, and confidence fields for easy frontend parsing
- **Cross-database compatibility** — queries target standard SQL that works across PostgreSQL, MySQL, and SQLite
- **Explicit JOINs** — the agent prefers explicit JOIN syntax over implicit joins for readability

## Flows
1. `sql-query-generator` — the single flow that handles schema parsing, SQL generation, and response formatting
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial | 💤 Low value

Field report: multiple heading spacing issues detected.

Agent, your document has four headings that need blank lines after them (lines 6, 12, 18) for proper markdown formatting (MD022). This is a consistent pattern throughout the file.

📄 Proposed fix for all heading spacing issues
 ## Architecture
+
 The agent uses a single Lamatic Flow with three nodes:
 1. **API Request** — receives the database schema and question via GraphQL
 2. **Generate Text (LLM)** — processes the inputs using a system prompt tuned for SQL generation
 3. **API Response** — returns the generated SQL as a JSON string

 ## Key Design Decisions
+
 - **Read-only queries only** — the agent is explicitly instructed to never generate INSERT, UPDATE, DELETE, DROP, or ALTER statements, making it safe for production use
 - **Structured JSON output** — the response includes sql, explanation, tables_used, assumptions, and confidence fields for easy frontend parsing
 - **Cross-database compatibility** — queries target standard SQL that works across PostgreSQL, MySQL, and SQLite
 - **Explicit JOINs** — the agent prefers explicit JOIN syntax over implicit joins for readability

 ## Flows
+
 1. `sql-query-generator` — the single flow that handles schema parsing, SQL generation, and response formatting

Based on learnings: "In kits/*/constitutions/default.md, the default.md constitution file is a templated/auto-generated file that ships as part of every new kit. It may have markdownlint MD022 (blanks-around-headings) warnings by default. When flagging such warnings in these files, note that the fix should be applied at the template/source level so all future kits inherit the corrected format."

📝 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
## Architecture
The agent uses a single Lamatic Flow with three nodes:
1. **API Request** — receives the database schema and question via GraphQL
2. **Generate Text (LLM)** — processes the inputs using a system prompt tuned for SQL generation
3. **API Response** — returns the generated SQL as a JSON string
## Key Design Decisions
- **Read-only queries only** — the agent is explicitly instructed to never generate INSERT, UPDATE, DELETE, DROP, or ALTER statements, making it safe for production use
- **Structured JSON output** — the response includes sql, explanation, tables_used, assumptions, and confidence fields for easy frontend parsing
- **Cross-database compatibility** — queries target standard SQL that works across PostgreSQL, MySQL, and SQLite
- **Explicit JOINs** — the agent prefers explicit JOIN syntax over implicit joins for readability
## Flows
1. `sql-query-generator` — the single flow that handles schema parsing, SQL generation, and response formatting
## Architecture
The agent uses a single Lamatic Flow with three nodes:
1. **API Request** — receives the database schema and question via GraphQL
2. **Generate Text (LLM)** — processes the inputs using a system prompt tuned for SQL generation
3. **API Response** — returns the generated SQL as a JSON string
## Key Design Decisions
- **Read-only queries only** — the agent is explicitly instructed to never generate INSERT, UPDATE, DELETE, DROP, or ALTER statements, making it safe for production use
- **Structured JSON output** — the response includes sql, explanation, tables_used, assumptions, and confidence fields for easy frontend parsing
- **Cross-database compatibility** — queries target standard SQL that works across PostgreSQL, MySQL, and SQLite
- **Explicit JOINs** — the agent prefers explicit JOIN syntax over implicit joins for readability
## Flows
1. `sql-query-generator` — the single flow that handles schema parsing, SQL generation, and response formatting
🧰 Tools
🪛 markdownlint-cli2 (0.22.1)

[warning] 6-6: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


[warning] 12-12: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


[warning] 18-18: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@kits/sql-query-generator/agent.md` around lines 6 - 19, Add a blank line
after each Markdown heading in this document (e.g., after "Architecture", "Key
Design Decisions", and "Flows") to satisfy MD022; update the file's headings so
there is one empty line between each heading and the following paragraph/list.
Also fix the source template (kits/*/constitutions/default.md) that generates
these kit README/constitution files so future kits are created with correct
blank lines after headings.

Comment on lines +1 to +4
SQL_QUERY_GENERATOR_FLOW_ID = "YOUR_FLOW_ID"
LAMATIC_API_URL = "YOUR_API_ENDPOINT"
LAMATIC_PROJECT_ID = "YOUR_PROJECT_ID"
LAMATIC_API_KEY = "YOUR_API_KEY"
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Agent, tighten up your .env format—remove those extraneous spaces.

Standard .env protocol requires no spaces around the equals sign. Your current format (KEY = VALUE) works but deviates from convention—should be KEY=VALUE.

🔧 Proposed fix to align with standard format
-SQL_QUERY_GENERATOR_FLOW_ID = "YOUR_FLOW_ID"
-LAMATIC_API_URL = "YOUR_API_ENDPOINT"
-LAMATIC_PROJECT_ID = "YOUR_PROJECT_ID"
-LAMATIC_API_KEY = "YOUR_API_KEY"
+SQL_QUERY_GENERATOR_FLOW_ID="YOUR_FLOW_ID"
+LAMATIC_API_URL="YOUR_API_ENDPOINT"
+LAMATIC_PROJECT_ID="YOUR_PROJECT_ID"
+LAMATIC_API_KEY="YOUR_API_KEY"
📝 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
SQL_QUERY_GENERATOR_FLOW_ID = "YOUR_FLOW_ID"
LAMATIC_API_URL = "YOUR_API_ENDPOINT"
LAMATIC_PROJECT_ID = "YOUR_PROJECT_ID"
LAMATIC_API_KEY = "YOUR_API_KEY"
SQL_QUERY_GENERATOR_FLOW_ID="YOUR_FLOW_ID"
LAMATIC_API_URL="YOUR_API_ENDPOINT"
LAMATIC_PROJECT_ID="YOUR_PROJECT_ID"
LAMATIC_API_KEY="YOUR_API_KEY"
🧰 Tools
🪛 dotenv-linter (4.0.0)

[warning] 1-1: [SpaceCharacter] The line has spaces around equal sign

(SpaceCharacter)


[warning] 2-2: [SpaceCharacter] The line has spaces around equal sign

(SpaceCharacter)


[warning] 2-2: [UnorderedKey] The LAMATIC_API_URL key should go before the SQL_QUERY_GENERATOR_FLOW_ID key

(UnorderedKey)


[warning] 3-3: [SpaceCharacter] The line has spaces around equal sign

(SpaceCharacter)


[warning] 3-3: [UnorderedKey] The LAMATIC_PROJECT_ID key should go before the SQL_QUERY_GENERATOR_FLOW_ID key

(UnorderedKey)


[warning] 4-4: [SpaceCharacter] The line has spaces around equal sign

(SpaceCharacter)


[warning] 4-4: [UnorderedKey] The LAMATIC_API_KEY key should go before the LAMATIC_API_URL key

(UnorderedKey)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@kits/sql-query-generator/apps/.env.example` around lines 1 - 4, Update the
.env example to remove spaces around the equals sign so entries follow KEY=VALUE
convention; specifically change lines for SQL_QUERY_GENERATOR_FLOW_ID,
LAMATIC_API_URL, LAMATIC_PROJECT_ID, and LAMATIC_API_KEY to use
SQL_QUERY_GENERATOR_FLOW_ID="YOUR_FLOW_ID", LAMATIC_API_URL="YOUR_API_ENDPOINT",
LAMATIC_PROJECT_ID="YOUR_PROJECT_ID", and LAMATIC_API_KEY="YOUR_API_KEY" (no
spaces around =).

Comment on lines +19 to +31
function parseResponse(raw: string): SQLGeneratorResult {
let cleaned = raw.trim();
if (cleaned.startsWith("```json")) {
cleaned = cleaned.slice(7);
} else if (cleaned.startsWith("```")) {
cleaned = cleaned.slice(3);
}
if (cleaned.endsWith("```")) {
cleaned = cleaned.slice(0, -3);
}
cleaned = cleaned.trim();
return JSON.parse(cleaned);
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial | ⚡ Quick win

The package is trusted but never inspected, Agent. parseResponse casts JSON.parse(cleaned) straight to SQLGeneratorResult with no runtime shape check. If the model emits valid JSON of the wrong shape (missing confidence, tables_used not an array, etc.), the malformed object reaches the UI where confidenceColor(result.confidence) and the assumptions/tables rendering have no guards — risking a runtime fault. The JSON.parse throw is already caught, so only structural validation is missing.

🛡️ Suggested defensive validation
 function parseResponse(raw: string): SQLGeneratorResult {
   let cleaned = raw.trim();
   if (cleaned.startsWith("```json")) {
     cleaned = cleaned.slice(7);
   } else if (cleaned.startsWith("```")) {
     cleaned = cleaned.slice(3);
   }
   if (cleaned.endsWith("```")) {
     cleaned = cleaned.slice(0, -3);
   }
   cleaned = cleaned.trim();
-  return JSON.parse(cleaned);
+  const parsed = JSON.parse(cleaned);
+  const validConfidence = ["high", "medium", "low"];
+  return {
+    sql: typeof parsed.sql === "string" ? parsed.sql : null,
+    explanation: typeof parsed.explanation === "string" ? parsed.explanation : "",
+    tables_used: Array.isArray(parsed.tables_used) ? parsed.tables_used : [],
+    assumptions: typeof parsed.assumptions === "string" ? parsed.assumptions : null,
+    confidence: validConfidence.includes(parsed.confidence) ? parsed.confidence : "low",
+  };
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@kits/sql-query-generator/apps/actions/orchestrate.ts` around lines 19 - 31,
parseResponse currently returns JSON.parse(cleaned) cast to SQLGeneratorResult
without runtime shape checks; add defensive validation after parsing in
parseResponse to ensure the returned object conforms to SQLGeneratorResult:
verify parsed.sql and parsed.explanation are strings (or set safe defaults),
ensure parsed.tables_used is an array (or []), ensure parsed.assumptions is a
string (or null/empty), and validate parsed.confidence against allowed values
["high","medium","low"] (default to "low" if invalid); construct and return a
sanitized object matching SQLGeneratorResult rather than returning the raw
parsed value so downstream calls like confidenceColor(result.confidence) and
table/assumption rendering cannot crash.

Comment on lines +6 to +12
interface QueryResult {
sql: string | null;
explanation: string;
tables_used: string[];
assumptions: string | null;
confidence: "high" | "medium" | "low";
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Agent briefing: Type duplication detected in the field.

The QueryResult interface is an exact duplicate of SQLGeneratorResult from actions/orchestrate.ts. This creates a maintenance risk—if the server response shape evolves, both definitions must be synchronized.

Mission directive: Export SQLGeneratorResult from orchestrate.ts and import it here.

As per coding guidelines: TypeScript usage should eliminate redundancy.

🔧 Proposed fix to eliminate duplication

In actions/orchestrate.ts, export the type:

-interface SQLGeneratorResult {
+export interface SQLGeneratorResult {
   sql: string | null;
   explanation: string;
   tables_used: string[];
   assumptions: string | null;
   confidence: "high" | "medium" | "low";
 }

Then in this file:

 "use client";
 
 import { useState } from "react";
-import { generateQuery } from "`@/actions/orchestrate`";
-
-interface QueryResult {
-  sql: string | null;
-  explanation: string;
-  tables_used: string[];
-  assumptions: string | null;
-  confidence: "high" | "medium" | "low";
-}
+import { generateQuery, type SQLGeneratorResult } from "`@/actions/orchestrate`";

And update the state typing:

-  const [result, setResult] = useState<QueryResult | null>(null);
+  const [result, setResult] = useState<SQLGeneratorResult | null>(null);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@kits/sql-query-generator/apps/app/page.tsx` around lines 6 - 12, QueryResult
is a duplicate of SQLGeneratorResult; remove the local QueryResult type and
instead export SQLGeneratorResult from actions/orchestrate.ts (ensure it's
exported as a named export) and import that type into this file, then update any
usages/state declarations that referenced QueryResult to use SQLGeneratorResult
(references: QueryResult, SQLGeneratorResult, actions/orchestrate.ts, and any
state variables in page.tsx that were typed with QueryResult).

Comment on lines +102 to +117
<textarea
value={schema}
onChange={(e) => setSchema(e.target.value)}
placeholder="Paste your CREATE TABLE statements here..."
className="w-full h-44 p-3 border border-gray-300 rounded-lg font-mono text-sm resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
/>

<label className="block text-sm font-medium text-gray-700 mt-5 mb-2">
Your Question
</label>
<textarea
value={question}
onChange={(e) => setQuestion(e.target.value)}
placeholder='e.g. "Find all users who placed more than 3 orders last month"'
className="w-full h-20 p-3 border border-gray-300 rounded-lg text-sm resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
/>
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial | 💤 Low value

Intel update: Accessibility protocol can be strengthened.

The textareas lack explicit id/htmlFor associations and aria-label attributes. While visual labels are present, screen reader users would benefit from proper semantic linkage.

Optional enhancement: Add id to textareas and htmlFor to labels.

♿ Proposed accessibility improvements
           <label
+            htmlFor="schema-input"
             className="block text-sm font-medium text-gray-700"
           >
             Database Schema
           </label>
           ...
           <textarea
+            id="schema-input"
+            aria-label="Database schema input"
             value={schema}
             onChange={(e) => setSchema(e.target.value)}
             placeholder="Paste your CREATE TABLE statements here..."
             className="w-full h-44 p-3 border border-gray-300 rounded-lg font-mono text-sm resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
           />

           <label
+            htmlFor="question-input"
             className="block text-sm font-medium text-gray-700 mt-5 mb-2"
           >
             Your Question
           </label>
           <textarea
+            id="question-input"
+            aria-label="Natural language question input"
             value={question}
             onChange={(e) => setQuestion(e.target.value)}
             placeholder='e.g. "Find all users who placed more than 3 orders last month"'
             className="w-full h-20 p-3 border border-gray-300 rounded-lg text-sm resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
           />
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@kits/sql-query-generator/apps/app/page.tsx` around lines 102 - 117, The two
textarea controls bound to value={schema} and value={question} lack semantic
linkage to their visual labels; add unique id attributes (e.g.,
"schema-textarea" and "question-textarea") to those textarea elements, update
the corresponding <label> elements to include htmlFor set to those ids, and also
add either aria-label or aria-labelledby on each textarea for screen readers (or
use aria-labelledby pointing to the label text) so the schema and question
inputs (the elements using setSchema and setQuestion) are properly announced.

Comment on lines +160 to +167
<button
onClick={() => {
if (result.sql) navigator.clipboard.writeText(result.sql);
}}
className="absolute top-2 right-2 px-2 py-1 bg-gray-700 text-gray-300 text-xs rounded hover:bg-gray-600 transition-colors"
>
Copy
</button>
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial | ⚡ Quick win

Equipment requisition: Copy operation requires visual indicator.

The copy button lacks an icon (violates "Use lucide-react for icons throughout kits" guideline) and accessibility attributes. Adding a Copy icon and aria-label would improve both visual clarity and screen reader support.

As per coding guidelines: kits/**/*.{ts,tsx} should use lucide-react for icons.

📋 Proposed enhancement with icon and accessibility
 import { useState } from "react";
 import { generateQuery, type SQLGeneratorResult } from "`@/actions/orchestrate`";
-import { FileCode, Sparkles } from "lucide-react";
+import { FileCode, Sparkles, Copy } from "lucide-react";
                 <button
                   onClick={() => {
                     if (result.sql) navigator.clipboard.writeText(result.sql);
                   }}
+                  aria-label="Copy SQL to clipboard"
                   className="absolute top-2 right-2 px-2 py-1 bg-gray-700 text-gray-300 text-xs rounded hover:bg-gray-600 transition-colors"
                 >
+                  <Copy className="inline-block w-3 h-3 mr-1" />
                   Copy
                 </button>
📝 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
<button
onClick={() => {
if (result.sql) navigator.clipboard.writeText(result.sql);
}}
className="absolute top-2 right-2 px-2 py-1 bg-gray-700 text-gray-300 text-xs rounded hover:bg-gray-600 transition-colors"
>
Copy
</button>
import { useState } from "react";
import { generateQuery, type SQLGeneratorResult } from "`@/actions/orchestrate`";
import { FileCode, Sparkles, Copy } from "lucide-react";
// ... other code ...
<button
onClick={() => {
if (result.sql) navigator.clipboard.writeText(result.sql);
}}
aria-label="Copy SQL to clipboard"
className="absolute top-2 right-2 px-2 py-1 bg-gray-700 text-gray-300 text-xs rounded hover:bg-gray-600 transition-colors"
>
<Copy className="inline-block w-3 h-3 mr-1" />
Copy
</button>
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@kits/sql-query-generator/apps/app/page.tsx` around lines 160 - 167, Update
the Copy button to use the lucide-react Copy icon and add accessibility
attributes: import Copy from 'lucide-react' at the top of page.tsx, replace the
button content so the icon is rendered (e.g., <Copy .../>) alongside or instead
of the "Copy" text, and add an aria-label like aria-label="Copy SQL to
clipboard" (optionally title="Copy SQL") to the <button> element; keep the
existing onClick handler (navigator.clipboard.writeText(result.sql)) and
existing classes but adjust icon sizing via className on the Copy component for
visual parity.

"start": "next start"
},
"dependencies": {
"lamatic": "latest",
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Agent, your package dependency is compromised—pin that version immediately.

The "lamatic": "latest" dependency violates protocol. Using "latest" means each installation pulls a different version, breaking reproducibility and risking mission failure when breaking changes slip through. Your orders are clear: pin to an explicit version (e.g., "lamatic": "1.2.3").

🔒 Proposed fix to secure the dependency
-    "lamatic": "latest",
+    "lamatic": "1.0.0",

Note: Replace 1.0.0 with the actual current version from your lock file or npm registry.

As per coding guidelines: "Each kit must have its own package.json with pinned dependency versions; do not rely on workspace-level hoisting or a root package.json"

📝 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
"lamatic": "latest",
"lamatic": "1.0.0",
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@kits/sql-query-generator/apps/package.json` at line 17, The dependency
"lamatic": "latest" in package.json is unpinned and must be fixed; replace the
"latest" specifier with an explicit, immutable version (e.g., the version from
this app's lockfile or the current npm registry) so the entry reads "lamatic":
"<exact-version>"; update package.json accordingly and run npm/yarn install to
refresh the lockfile so the kit has a pinned, reproducible dependency.

### 3. Configure environment

```bash
cp .env.example .env
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Mission briefing, agent: use .env.local for Next.js development secrets.

Your deployment package correctly references .env.example as the template, but the local copy command should target .env.local instead of .env. Next.js prioritizes .env.local for developer-specific secrets and most kits' .gitignore files exclude it by default (along with .env). This prevents accidental commits of live credentials.

🔒 Recommended fix for secure local development
-cp .env.example .env
+cp .env.example .env.local

As per coding guidelines: "The .gitignore file must exclude .env and .env.local to prevent accidental secret commits."

📝 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
cp .env.example .env
cp .env.example .env.local
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@kits/sql-query-generator/README.md` at line 41, Replace the README's local
env copy step so developers create a Next.js safe local file: change the
instruction that runs "cp .env.example .env" to copy into ".env.local" instead
(update the line that currently reads cp .env.example .env to use .env.local);
also verify the repository .gitignore excludes both .env and .env.local to avoid
committing secrets.

Comment on lines +46 to +51
```
SQL_QUERY_GENERATOR_FLOW_ID = "your-flow-id"
LAMATIC_API_URL = "https://your-org.lamatic.dev"
LAMATIC_PROJECT_ID = "your-project-id"
LAMATIC_API_KEY = "sk-your-api-key"
```
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Mission briefing: code fence needs a language identifier.

The environment variable example block (lines 46-51) is missing a language specifier. Intelligence analysts recommend adding env or bash to improve syntax highlighting and comply with markdown standards.

📋 Proposed fix for code fence language
-```
+```env
 SQL_QUERY_GENERATOR_FLOW_ID = "your-flow-id"
 LAMATIC_API_URL = "https://your-org.lamatic.dev"
 LAMATIC_PROJECT_ID = "your-project-id"
 LAMATIC_API_KEY = "sk-your-api-key"

</details>

<!-- suggestion_start -->

<details>
<summary>📝 Committable suggestion</summary>

> ‼️ **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.

```suggestion

🧰 Tools
🪛 markdownlint-cli2 (0.22.1)

[warning] 46-46: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@kits/sql-query-generator/README.md` around lines 46 - 51, Add a language
identifier to the markdown code fence that shows the environment variables (the
block containing SQL_QUERY_GENERATOR_FLOW_ID, LAMATIC_API_URL,
LAMATIC_PROJECT_ID, LAMATIC_API_KEY) so editors render proper syntax
highlighting; change the opening triple backticks to include a language like env
or bash (e.g., ```env) and keep the variable lines unchanged.

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.

2 participants