| 1 |
# Harlequin for Agents |
| 2 |
|
| 3 |
**A product plan for making Harlequin the best SQL client for coding agents.** |
| 4 |
|
| 5 |
Status: draft for discussion. Product and user stories only — implementation details are |
| 6 |
deliberately sketched, not specified. |
| 7 |
|
| 8 |
Scope: the `harlequin` package (this repo) and the `harlequin-web` site |
| 9 |
(<https://harlequin.sh>). |
| 10 |
|
| 11 |
--- |
| 12 |
|
| 13 |
## 1. The opportunity |
| 14 |
|
| 15 |
Today an agent asked to "look at my warehouse" reaches for whatever CLI is nearest: |
| 16 |
`psql`, `duckdb`, `bq`, `databricks sql`, `mysql`, `trino`. Each has different flags, |
| 17 |
different output formats, different auth, different error semantics, and different |
| 18 |
ideas about what "give me the schema" means. The agent burns tokens rediscovering all |
| 19 |
of that on every task, and it hallucinates flags for the ones it has seen least. |
| 20 |
|
| 21 |
Harlequin already has the thing that fixes this, and nobody else does: |
| 22 |
|
| 23 |
- **One uniform adapter interface across ~15 databases** — DuckDB, SQLite, Postgres, |
| 24 |
MySQL, BigQuery, Trino, Databricks, ODBC, ADBC, Cassandra, NebulaGraph, RisingWave, |
| 25 |
Wherobots, Exasol. |
| 26 |
- **A normalized catalog abstraction** (`Catalog` / `CatalogItem`) that already answers |
| 27 |
"what tables exist and what are their column types" without dialect-specific |
| 28 |
`information_schema` queries. |
| 29 |
- **Profiles in a config file** that already encode "how to connect to my warehouse," |
| 30 |
discovered automatically from the cwd and home directory. |
| 31 |
- **sqlfmt** as an existing dependency. |
| 32 |
- **A TUI on the other end of the same config**, which no other CLI has. |
| 33 |
|
| 34 |
The pitch writes itself: **`hsql -P prod -c "select 1"` works the same way against every |
| 35 |
database your team uses.** One CLI contract, one set of flags, one output format |
| 36 |
vocabulary, one exit-code scheme — and when the agent needs a human, the human opens |
| 37 |
Harlequin against the same profile and sees the same catalog. |
| 38 |
|
| 39 |
That last point is the real differentiator. Every other SQL client can be made |
| 40 |
agent-friendly. Only Harlequin can make the *handoff* good. |
| 41 |
|
| 42 |
## 2. Who we are designing for |
| 43 |
|
| 44 |
Three personas, all of which are "an agent," but with materially different needs. |
| 45 |
|
| 46 |
### P1 — Agent as operator |
| 47 |
|
| 48 |
Runs queries headlessly on a human's behalf, usually in a loop, usually inside a coding |
| 49 |
agent's Bash tool. Cares about: deterministic output, honest truncation, exit codes, |
| 50 |
token-efficient results, not accidentally dropping a table. |
| 51 |
|
| 52 |
### P2 — Agent as pair |
| 53 |
|
| 54 |
Works alongside a human who has Harlequin open. Drafts a query the human will run; |
| 55 |
reads what the human already ran. Cares about: handoff in both directions. |
| 56 |
|
| 57 |
### P3 — Agent as support engineer |
| 58 |
|
| 59 |
Helps a human install, configure, and troubleshoot Harlequin — "why won't it connect to |
| 60 |
Snowflake," "add a prod profile to my config," "what does this error mean." Cares about: |
| 61 |
machine-readable docs, a formal config spec, a self-describing CLI, good diagnostics. |
| 62 |
|
| 63 |
Most existing "AI-friendly CLI" work only serves P1. Serving P2 and P3 is where |
| 64 |
Harlequin can be uniquely good. |
| 65 |
|
| 66 |
## 3. Design principles |
| 67 |
|
| 68 |
These are the calls I'd want made up front, because they resolve most of the small |
| 69 |
decisions downstream. |
| 70 |
|
| 71 |
1. **One engine, two front doors.** `harlequin` (TUI) and `hsql` (headless) share |
| 72 |
adapters, config discovery, profiles, limit semantics, and one execution core. |
| 73 |
Neither reimplements the other. See §4. |
| 74 |
|
| 75 |
2. **stdout is data; stderr is narration.** Results go to stdout and nothing else does. |
| 76 |
Truncation notices, warnings, errors, and `--stats` go to stderr — and nothing that |
| 77 |
stdout already carries: the row count is the result's own footer, and a timing is a |
| 78 |
field of `--stats`. This is already the intent in `exception.py` — make it a hard, |
| 79 |
tested contract. |
| 80 |
|
| 81 |
3. **Exit codes are an API.** Documented, stable, and distinct enough that an agent can |
| 82 |
branch on them without parsing text. |
| 83 |
|
| 84 |
4. **Determinism over cleverness: identical output whether stdout is a TTY, a pipe, or |
| 85 |
a pty.** Agent harnesses vary in which they give you. A client that formats |
| 86 |
differently under a pipe is a bug factory. No TTY-sniffing for format selection. |
| 87 |
(Color is the one exception, and it follows `NO_COLOR` / `--color`.) |
| 88 |
|
| 89 |
5. **Token efficiency is a feature.** Results cost the agent money. Defaults should be |
| 90 |
small, and truncation must always be announced — never silent. |
| 91 |
|
| 92 |
6. **Be boring and psql-shaped.** An agent's prior is `psql`, secondarily `duckdb`. |
| 93 |
Every flag we can borrow, we borrow. Novel spellings cost tokens and cause retries. |
| 94 |
|
| 95 |
7. **Never make the agent guess.** Everything Harlequin knows about itself — options |
| 96 |
(including plugin-contributed ones), profiles, formats, adapters, capabilities, |
| 97 |
catalog — should be dumpable as JSON on demand. This is the one place we should be |
| 98 |
*more* capable than psql, because our option surface is dynamic and plugin-driven, so |
| 99 |
no amount of pretraining can teach an agent what's actually installed. |
| 100 |
|
| 101 |
8. **Safety is a product feature, not a warning in the docs.** `--read-only`, |
| 102 |
`--timeout`, and `--dry-run` are what let a human hand an agent a warehouse |
| 103 |
credential without flinching. |
| 104 |
|
| 105 |
9. **No LLM inside Harlequin.** No API keys, no model config, no vendor coupling. We |
| 106 |
make Harlequin excellent for the agent already sitting next to the user. (See §10 for |
| 107 |
how this answers issue #952.) |
| 108 |
|
| 109 |
--- |
| 110 |
|
| 111 |
## 4. Shape of the CLI: two commands, one engine |
| 112 |
|
| 113 |
**Decision: headless mode ships as a separate command, `hsql`, not as flags on |
| 114 |
`harlequin`.** |
| 115 |
|
| 116 |
The tempting reason — it frees the flag namespace — is the weakest one. The real reasons |
| 117 |
are these. |
| 118 |
|
| 119 |
**Two audiences want two stability contracts.** The TUI's promise is "delight a human, |
| 120 |
evolve freely." The headless promise is "output format and exit codes are an API, |
| 121 |
frozen." Inside one command those pull against each other on every release, and a TUI |
| 122 |
change can silently break a machine contract. A separate command makes the boundary |
| 123 |
structural rather than something a reviewer has to remember. |
| 124 |
|
| 125 |
**Cold start stops being a discipline problem.** With one entry point, "never import |
| 126 |
Textual on the headless path" is a rule any contributor can regress silently. With a |
| 127 |
separate module graph it becomes an import-linter test in CI — *the `hsql` module graph |
| 128 |
must not contain `textual`* — which is the difference between hitting the 300ms target |
| 129 |
and hoping to. |
| 130 |
|
| 131 |
**It opens a lean install later.** `pip install hsql` with no Textual, no pyperclip, is |
| 132 |
plausible for CI images and agent sandboxes, and hard to reach from a single entry point. |
| 133 |
|
| 134 |
### What actually ships |
| 135 |
|
| 136 |
**The same package, with a second console script:** |
| 137 |
`hsql = "harlequin.hsql:main"` alongside the existing `harlequin` script. |
| 138 |
|
| 139 |
That is the key de-risking move. **The command split is cheap and near-reversible; the |
| 140 |
package split is the expensive part, and it can wait indefinitely** — possibly forever. |
| 141 |
We get the boundary and the enforceable import graph now, and decide about a separate |
| 142 |
distribution only if the lean-install demand materializes. |
| 143 |
|
| 144 |
`harlequin` itself gains **nothing**: no `-c`, no growth in an already-large `--help`, |
| 145 |
no behavior change. The one addition is a custom unknown-option handler, so |
| 146 |
`harlequin -c "select 1"` fails with *"`-c` isn't a harlequin option — did you mean |
| 147 |
`hsql -c`? See harlequin.sh/docs/headless."* |
| 148 |
|
| 149 |
Everything in Workstream B lands as `hsql` subcommands: `hsql catalog`, |
| 150 |
`hsql describe`, `hsql fmt`, `hsql spec`, `hsql info`, `hsql config`, `hsql history`, |
| 151 |
`hsql mcp`, `hsql open`. Bare `hsql` with no arguments prints help; it never launches |
| 152 |
the TUI. |
| 153 |
|
| 154 |
> **Amended in M2's plan: these are mode options, not subcommands.** `hsql --catalog`, |
| 155 |
> `hsql --info`, `hsql --spec`, `hsql --config show`. It matches `harlequin --config`, so |
| 156 |
> one shape covers both commands — and it sidesteps the objection this section raises |
| 157 |
> against subcommands, which applies here too: `hsql` takes `CONN_STR` positionally, so |
| 158 |
> `hsql catalog` and a database file named `catalog` would have needed a disambiguation |
| 159 |
> rule, docs for the rule, and a test for the rule. No verb, no rule. |
| 160 |
|
| 161 |
### Consequences |
| 162 |
|
| 163 |
- **The `-f` collision disappears, and with it the plan's only breaking change.** |
| 164 |
`harlequin -f` stays `--show-files` forever; `hsql -f` is `--file`, as psql users |
| 165 |
expect. Nothing here needs to wait for 3.0 — the whole plan becomes additive and can |
| 166 |
ship in 2.x minors. |
| 167 |
- `hsql` gets clean access to `-c`, `-f`, `-o`, `-A`, and friends, so psql muscle memory |
| 168 |
works without compromise. |
| 169 |
- `hsql --help` omits every TUI-only option (`--theme`, `--keymap-name`, `--show-files`, |
| 170 |
`--show-s3`, `--locale`, `--config`, `--keys`), which is a real token saving for an |
| 171 |
agent reading it. It also omits the adapter connection-option matrix: `hsql --help` |
| 172 |
lists the *names* of installed adapters and points at `hsql --help -a <adapter>` for |
| 173 |
one adapter's options. That keeps the first thing an agent reads small and stable, and |
| 174 |
keeps `--help` true for every adapter rather than showing whichever one is the |
| 175 |
default. |
| 176 |
- The handoff gets a natural verb: `hsql open query.sql` reads much better than |
| 177 |
`harlequin --new-buffer query.sql`. |
| 178 |
|
| 179 |
### Alternatives rejected |
| 180 |
|
| 181 |
- **Flags on `harlequin`.** Requires the 3.0 `-f` break, grows an already-large help |
| 182 |
surface, and leaves cold start and the stability boundary as matters of discipline. |
| 183 |
- **Subcommands on `harlequin` with a bare-invocation TUI fallback** |
| 184 |
(`harlequin query -c ...`). Needs a custom Click `Group` that falls back to the TUI |
| 185 |
when the first argument isn't a known subcommand, and it is genuinely ambiguous: a |
| 186 |
DuckDB file named `catalog` or `config` in the cwd resolves as a subcommand. Low |
| 187 |
probability, but exactly the confusing failure we don't want an agent hitting. |
| 188 |
|
| 189 |
### On the name |
| 190 |
|
| 191 |
`hsql` is free on PyPI as of this writing — M0 in §11 secures it before anything else |
| 192 |
starts. HSQLDB ships `sqltool` and `java -jar`, not a binary named `hsql`, so there's no |
| 193 |
PATH collision — the cost is search-results mindshare with |
| 194 |
HyperSQL, which is real but mild and fading. `hq` is taken. `harlequin-cli` is free but |
| 195 |
too long for something an agent types a hundred times in a task; short names are cheap |
| 196 |
in tokens and cheap in working memory. |
| 197 |
|
| 198 |
I'd take `hsql`. It's obviously "harlequin sql," and it sharpens the positioning rather |
| 199 |
than diluting it: |
| 200 |
|
| 201 |
> **Harlequin** — the SQL IDE for your terminal. |
| 202 |
> **hsql** — the same engine, headless, for scripts and agents. |
| 203 |
> Fifteen databases, one adapter ecosystem. |
| 204 |
|
| 205 |
That's a better story than "one tool with a flag." |
| 206 |
|
| 207 |
--- |
| 208 |
|
| 209 |
## 5. Workstream A — `hsql`, headless execution |
| 210 |
|
| 211 |
Closes [#524](https://github.com/tconbeer/harlequin/issues/524). This is the |
| 212 |
foundation; everything else in this plan assumes it. |
| 213 |
|
| 214 |
### Proposed surface |
| 215 |
|
| 216 |
``` |
| 217 |
hsql [OPTIONS] [CONN_STR]... Execute SQL and exit |
| 218 |
hsql <SUBCOMMAND> [OPTIONS] catalog, describe, fmt, spec, info, |
| 219 |
config, history, open, mcp |
| 220 |
|
| 221 |
-c, --command TEXT Execute SQL. Repeatable. |
| 222 |
-f, --file PATH Execute SQL from a file (or `-` for stdin). Repeatable. |
| 223 |
-o, --output PATH Write results to PATH instead of stdout. |
| 224 |
--format NAME Output format (see below). Default: table. |
| 225 |
--csv/--json/--jsonl/--markdown/--vertical Format shorthands. |
| 226 |
-t, --tuples-only Rows only: no header, no footer. As in psql. |
| 227 |
-A, --no-align Unaligned output. As in psql. |
| 228 |
--no-header Omit the header row (keep other chrome). |
| 229 |
--null-string STR Render NULL as STR. Default: empty for csv, "NULL" for table. |
| 230 |
-P, --profile NAME Same profiles as the TUI. |
| 231 |
--limit N Max rows fetched per result set. Default: 500. -1 = no limit. |
| 232 |
--result all|last|N Which result set(s) to emit. Default: all. |
| 233 |
--on-error stop|continue Default: stop. |
| 234 |
--stats Write a one-line JSON summary to stderr. |
| 235 |
--color auto|always|never Default: never. |
| 236 |
--timeout SECONDS Cancel the query and exit non-zero. |
| 237 |
--read-only Refuse to run if the adapter can't enforce read-only. |
| 238 |
--dry-run Parse/validate (and EXPLAIN where supported) without executing. |
| 239 |
--single-transaction Wrap the whole script; roll back on any error. |
| 240 |
``` |
| 241 |
|
| 242 |
Config discovery, profiles, and precedence are identical to the TUI: CLI > env > |
| 243 |
`--config-path` > cwd config > user config dir > home > defaults. That's the whole |
| 244 |
point — `hsql -P prod -c ...` means the agent never handles a credential. |
| 245 |
|
| 246 |
### Formats |
| 247 |
|
| 248 |
| Format | Use | |
| 249 |
| --- | --- | |
| 250 |
| `table` (default) | Aligned text. Human-legible, deterministic. | |
| 251 |
| `markdown` / `md` | Pipe table. The most reliable format for an LLM to read back. | |
| 252 |
| `csv`, `tsv` | Pipelines, spreadsheets. | |
| 253 |
| `json` | Array of row objects. Matches `duckdb -json`. | |
| 254 |
| `jsonl` / `ndjson` | One object per line. Streaming, large results. | |
| 255 |
| `vertical` | psql `\x`. One column per line — best for inspecting a single wide row. | |
| 256 |
| `parquet`, `arrow`, `orc` | Bulk handoff. Already implemented in `export.py`. | |
| 257 |
| `none` | Discard rows; report status only. For DDL/DML/ETL. | |
| 258 |
|
| 259 |
> **Amended in implementation.** There is no `-F`: that is psql's |
| 260 |
> `--field-separator`, and a flag that sets a delimiter in one command and picks a |
| 261 |
> format in the other is a mistake waiting for a script — the same reasoning that |
| 262 |
> keeps `-l` off `--limit`. The format is chosen by `--format` spelled out, or by |
| 263 |
> the `--csv`/`--json`/`--jsonl`/`--markdown`/`--vertical` shorthands, which cover |
| 264 |
> the choices anyone types often enough to want a short flag for. |
| 265 |
|
| 266 |
### Behaviors that matter more than the flag list |
| 267 |
|
| 268 |
**Truncation is always announced.** If `--limit` bites, stderr gets |
| 269 |
`note: results truncated at --limit 500; pass --limit -1 for all rows`, and text formats |
| 270 |
append a visible `… 500 of >500 rows` footer. |
| 271 |
|
| 272 |
Note that `--limit` here is a *hard* limit — it caps what leaves the database, via the |
| 273 |
adapter's `set_limit()`. The TUI's `--limit` is a soft display cap: it fetches everything |
| 274 |
and caps what loads into the viewer, which is why the TUI can report an exact |
| 275 |
`Showing 100,000 of 3,412,887`. `hsql` deliberately doesn't buy that number, so it says |
| 276 |
`>500`; only `--limit -1` yields an exact count. The TUI's default of 100,000 is |
| 277 |
right for a TUI and a catastrophe for an agent; `hsql` defaults to 500. |
| 278 |
|
| 279 |
> **Amended by [#1026](https://github.com/tconbeer/harlequin/issues/1026).** One key |
| 280 |
> naming both of those limits was the bug, not the design: the TUI's display cap is now |
| 281 |
> `viewer_max_rows`, `limit` is the hard fetch limit in both commands, and unlimited is |
| 282 |
> spelled `-1` rather than `0`, so that `--limit 0` can fetch a header and no rows (and |
| 283 |
> there is no `-l`, which is psql's `--list`). The text |
| 284 |
> layouts additionally cap what they *print* (`--display-rows`, 40 rows or 10 records), |
| 285 |
> since fetching 500 rows and printing 500 rows are separate questions. |
| 286 |
|
| 287 |
Detecting truncation at all requires fetching `limit + 1` rows and emitting `limit` — |
| 288 |
`set_limit(n)` followed by `fetchall()` returns at most n rows and cannot say whether an |
| 289 |
n+1th existed. Worth stating here rather than leaving to implementation, because it's the |
| 290 |
kind of detail that gets optimized away and quietly breaks this promise. |
| 291 |
|
| 292 |
The stderr notice fires **even under `-t`**. `-t` suppresses stdout chrome, not |
| 293 |
warnings; a flag that silently defeats truncation reporting would undo principle 5. |
| 294 |
|
| 295 |
**Row counts and timing go to stderr**, so `hsql -c "select 1" --csv > out.csv` produces |
| 296 |
a clean file while the agent still sees `1 row in 0.02s`. |
| 297 |
|
| 298 |
**`--stats` emits one line of JSON to stderr** for any output format: |
| 299 |
|
| 300 |
```json |
| 301 |
{"status":"ok","statements":1,"rows":500,"truncated":true,"limit":500, |
| 302 |
"elapsed_ms":412,"columns":[{"name":"id","type":"BIGINT"}]} |
| 303 |
``` |
| 304 |
|
| 305 |
This is how an agent gets structured metadata without polluting stdout, and it works |
| 306 |
identically whether stdout is CSV or Parquet. |
| 307 |
|
| 308 |
**Errors are plain.** No Rich panels, no ANSI, no box drawing: |
| 309 |
`hsql: error: relation "usres" does not exist` on stderr. The panel is a TUI affordance. |
| 310 |
|
| 311 |
> **Amended in M2's plan**, on two of the safety flags above. |
| 312 |
> |
| 313 |
> **`--timeout` has to attribute the cancellation itself.** A cancelled DuckDB query comes |
| 314 |
> back as an empty result set with no error — `fetchall()` swallows the interrupt and |
| 315 |
> returns `None`, which is also what an empty result looks like — so a timeout that trusts |
| 316 |
> the adapter prints "no rows" and exits 0. `hsql` knows it fired the deadline, discards |
| 317 |
> that result, and exits 4. It also refuses up front on an adapter that can't cancel, |
| 318 |
> since there is otherwise no way to stop the work. |
| 319 |
> |
| 320 |
> **`--single-transaction` is cut too.** Adapters name their transaction modes freely — |
| 321 |
> SQLite and Postgres offer "Auto"/"Manual", DuckDB overrides nothing and reports none, and |
| 322 |
> a third-party adapter may name its modes anything and default to whatever its driver |
| 323 |
> does — so core cannot ask for "the manual one" through that interface without first |
| 324 |
> reworking what a transaction mode is. Story A6's guarantee comes from `begin` and |
| 325 |
> `commit` in the caller's own script until then. |
| 326 |
> |
| 327 |
> **`--dry-run` is cut**, from M2 and possibly for good. Only DuckDB implements |
| 328 |
> `validate_sql` at all, and there it is a parse check rather than an existence check: |
| 329 |
> `select * from no_such_table` validates clean, because the adapter treats every |
| 330 |
> non-parser error as valid so that DDL passes. Making it honest would mean a `PREPARE` |
| 331 |
> pass in the DuckDB adapter plus a refusal path on every other adapter — a lot of |
| 332 |
> machinery for a flag that would be truthful on one backend. |
| 333 |
|
| 334 |
**Exit codes:** |
| 335 |
|
| 336 |
| Code | Meaning | |
| 337 |
| --- | --- | |
| 338 |
| 0 | Success | |
| 339 |
| 1 | Query error (the database rejected the SQL) | |
| 340 |
| 2 | Usage / config error (bad flag, bad profile, bad TOML) | |
| 341 |
| 3 | Connection error (couldn't reach or authenticate to the database) | |
| 342 |
| 4 | Timeout / cancelled | |
| 343 |
| 130 | SIGINT | |
| 344 |
|
| 345 |
**Cold start is a feature.** An agent may run twenty queries in a task. Target: |
| 346 |
**`hsql -c "select 1"` against DuckDB in under 300ms**, tracked as a benchmark in CI and |
| 347 |
protected by the import-linter rule from §4. |
| 348 |
|
| 349 |
**Large results stream — in M5, not M1.** Streaming has to start at the cursor: |
| 350 |
`HarlequinCursor.fetchall()` materializes the whole result before any writer exists, so |
| 351 |
no amount of care in the format layer helps. Deferred wholesale to M5 along with |
| 352 |
[#875](https://github.com/tconbeer/harlequin/issues/875), rather than half-designed |
| 353 |
now. |
| 354 |
|
| 355 |
### User stories |
| 356 |
|
| 357 |
- **A1.** As an agent, I run `hsql -P prod -c "select count(*) from orders"` and get a |
| 358 |
small, aligned result on stdout and exit code 0, so I can report a number to the human |
| 359 |
without parsing a TUI. |
| 360 |
- **A2.** As an agent, I run the same command against Postgres, BigQuery, and DuckDB and |
| 361 |
the flags, output shape, and exit codes are identical, so I don't relearn a CLI per |
| 362 |
database. |
| 363 |
- **A3.** As an agent, when my SQL is wrong I get a one-line error on stderr and exit |
| 364 |
code 1, and nothing on stdout, so I can distinguish "the query failed" from "the query |
| 365 |
returned zero rows." |
| 366 |
- **A4.** As an agent, when a result is larger than the limit I am told so explicitly, so |
| 367 |
I never report a truncated aggregate as a complete one. |
| 368 |
- **A5.** As an agent, I pass `--json` and pipe to `jq` without stripping banners, |
| 369 |
timings, or a "(500 rows)" footer. |
| 370 |
- **A6.** As an agent, I run a multi-statement script with `-f setup.sql |
| 371 |
--single-transaction` and either all of it applies or none of it does. |
| 372 |
- **A7.** As a human, I set `read_only = true` in my agent profile so the agent |
| 373 |
physically cannot write to prod, and I can point at that line in the config when |
| 374 |
someone asks whether it's safe. |
| 375 |
- **A8.** As a human, I use `hsql` in a Makefile or CI job because it's the same engine |
| 376 |
and the same profile I already use interactively. |
| 377 |
|
| 378 |
### On `-t`, and the `-tAc` idiom |
| 379 |
|
| 380 |
`-t` is `--theme` in `harlequin` and "tuples only" in psql. Since `hsql` has no themes, |
| 381 |
`-t` is free, and it takes the **psql meaning**. |
| 382 |
|
| 383 |
The reason isn't `-t` in isolation — it's that `psql -tAc "select count(*)"` is a single |
| 384 |
well-worn idiom, the standard way to capture a scalar in a shell script. Supporting `-t` |
| 385 |
and `-A` separately but not together would be pointless; refusing `-t` would break the |
| 386 |
cluster and make first contact with a scripting audience an error message. Borrowing the |
| 387 |
flag is principle 6 doing its job. |
| 388 |
|
| 389 |
The residual risk is small and worth naming: someone with `harlequin -t nord` habits |
| 390 |
types `hsql -t nord -c ...`, `-t` parses as a boolean, and `nord` is read as a |
| 391 |
connection string. The resulting "could not open database 'nord'" is diagnosable, and we |
| 392 |
can special-case the hint when an unparseable conn_str matches a known theme name. |
| 393 |
|
| 394 |
`hsql -tAc "select count(*) from orders"` returning a bare number and nothing else |
| 395 |
should be an explicitly tested case, and the first example in the scripting docs. |
| 396 |
|
| 397 |
A short "differences from psql" table in the docs should still cover `-P` (profile here, |
| 398 |
pset there) and anything else that diverges. |
| 399 |
|
| 400 |
--- |
| 401 |
|
| 402 |
## 6. Workstream B — Self-description and introspection |
| 403 |
|
| 404 |
If Workstream A is what lets an agent *run* a query, this is what lets it write a |
| 405 |
correct one on the first try. All of it lands as `hsql` subcommands. |
| 406 |
|
| 407 |
### `hsql catalog` — the catalog is a filesystem, not a document |
| 408 |
|
| 409 |
The highest-leverage feature in this plan after `-c`. Harlequin already normalizes the |
| 410 |
catalog across every adapter; today that value is locked inside the TUI. |
| 411 |
|
| 412 |
**The binding constraint is fetch cost, not token cost.** `get_catalog()` issues one |
| 413 |
query and returns databases only; every level below it is a separate `fetch_children()` |
| 414 |
round trip, with columns as the leaf. Listing one schema's columns is `1 + 1 + 1 + T` |
| 415 |
queries. A "dump the tree, then filter" interface is an N+1 walk that gets slower the |
| 416 |
more useful it would be — and #1007 already moved the TUI off eager loading for exactly |
| 417 |
this reason. Filtering in the client protects the agent's context and does nothing for |
| 418 |
the database. |
| 419 |
|
| 420 |
So the model is a filesystem: **`ls`, `stat`, `find`** — not dump-and-grep. That bounds |
| 421 |
cost structurally, because you only pay for the level you asked for, and it rides on the |
| 422 |
navigation loop agents are most practiced at. |
| 423 |
|
| 424 |
``` |
| 425 |
hsql catalog [PATH] [--depth N] [--max-nodes N] [--format compact|json|md|tree] |
| 426 |
hsql describe <PATH> |
| 427 |
hsql find <TERM> [--in tables|columns|all] |
| 428 |
``` |
| 429 |
|
| 430 |
- **One level below the match, by default.** `hsql catalog` → databases; |
| 431 |
`hsql catalog mydb` → schemas; `hsql catalog mydb.analytics` → relations; |
| 432 |
`hsql catalog mydb.analytics.orders` → columns. Exactly one `fetch_children()` call. |
| 433 |
`--depth N` opts into recursion; there is no unbounded default. |
| 434 |
|
| 435 |
Counting depth **from the match** rather than from the root is what makes this safe |
| 436 |
rather than merely conservative: at every level, depth 1 is a single round trip, so |
| 437 |
there is no path on which the default degrades into a walk. Depth ≥2 from a schema is |
| 438 |
the first N+1, and it's opt-in. |
| 439 |
|
| 440 |
- **Patterns are paths with an optional trailing glob.** A trailing wildcard filters one |
| 441 |
resolved parent's children and stays a single round trip, so `analytics.*` is just |
| 442 |
sugar for `analytics`, and `analytics.ord*` narrows it. An *interior* wildcard |
| 443 |
(`*.orders`, `mydb.*.orders`) can't be evaluated without fetching every candidate |
| 444 |
level, so it belongs to `find` below — never something a `catalog` call does quietly. |
| 445 |
- **Report child counts** wherever the adapter can get them cheaply. `400 relations` next |
| 446 |
to a schema is what lets an agent decide *not* to recurse. Cost should be predictable |
| 447 |
before the call, not just measurable after it. |
| 448 |
- **A node budget.** `--max-nodes` (default ~2000) stops a recursive walk and says so, |
| 449 |
naming the path to narrow. Same rule as row truncation: never silent. |
| 450 |
- **`--stats` reports round trips**, so the expensive shape of a query is visible. |
| 451 |
- **Emit `query_name`, not just the label.** Adapters already compute the correctly |
| 452 |
quoted identifier for every item. Handing it over means the agent never guesses whether |
| 453 |
this backend wants `"Orders"` or `` `orders` ``. It costs nothing and no other client |
| 454 |
does it. |
| 455 |
- **`--format compact`** stays for the leaf and shallow-recursion cases: |
| 456 |
`analytics.orders(id BIGINT, customer_id BIGINT, total DECIMAL(18,2))`. Roughly an |
| 457 |
order of magnitude cheaper than pretty JSON and perfectly readable by a model. |
| 458 |
- **`describe`** returns one object in full — columns, types, comments, row counts where |
| 459 |
the adapter can supply them. One round trip. |
| 460 |
|
| 461 |
> **Amended in M2's plan**, on four things this section assumes the catalog contract can |
| 462 |
> already do. |
| 463 |
> |
| 464 |
> **A listing is one round trip per path segment, plus one** — four for |
| 465 |
> `--catalog --path mydb.analytics.orders`, not one. An item can only be reached through |
| 466 |
> its ancestors, so the resolve in front of the listing is itself a walk. The listing stays |
| 467 |
> single-level and cheap; the resolve is what a network database charges for. |
| 468 |
> |
| 469 |
> **`--depth N` is one number over levels with wildly different costs, so M2 ships no |
| 470 |
> recursion at all.** Depth 2 from the root fetches each database's schema names — one |
| 471 |
> round trip per database, and databases are few. Depth 2 from a *schema* is one round trip |
| 472 |
> per relation: measured, 400 relations is **403 round trips and 2.3 seconds against a |
| 473 |
> local DuckDB file**, on the call an agent would most want to make. Recursion comes back |
| 474 |
> with `fetch_descendants()`, which is what would make it a single query rather than a |
| 475 |
> walk with a budget bolted on. |
| 476 |
> |
| 477 |
> **Child counts have no cheap case.** A count is only knowable by fetching the children, |
| 478 |
> so "report child counts wherever the adapter can get them cheaply" cannot be implemented |
| 479 |
> as written. What a listing can report is what it fetched, which it already does. |
| 480 |
> |
| 481 |
> **`describe` is `catalog` on a relation, so there is no separate verb.** One level below |
| 482 |
> a relation *is* its columns, with their names, real types and quoted identifiers. All a |
| 483 |
> second mode could add is detail the contract does not carry (comments) or that costs a |
| 484 |
> table scan (row counts). |
| 485 |
> |
| 486 |
> **`--format compact` is cut, and the type it wanted is added.** `CatalogItem.type_label` |
| 487 |
> is a 1–3 character label for a tree column (`##`, `s`, `ts`), so the type an agent needs |
| 488 |
> is not in the contract at all — M2 adds an optional `type_name`, which the in-tree |
| 489 |
> adapters already fetch and discard, falling back to the short label where an adapter |
| 490 |
> never populates it. The *format* goes: `parent(child TYPE, …)` only reads for a relation |
| 491 |
> and its columns, and what a level is belongs to the adapter, so a database's schemas |
| 492 |
> would render as a signature they are not. `-tA --format csv` over the same rows is as |
| 493 |
> cheap and is true at every level. |
| 494 |
|
| 495 |
### `hsql find` — the real gap |
| 496 |
|
| 497 |
What an agent most often needs isn't "list this schema," it's *"where does `orders` |
| 498 |
live"* or *"which tables have a `customer_id`."* That cannot be a walk. |
| 499 |
|
| 500 |
This wants an **optional adapter capability** (`implements_catalog_search`): one |
| 501 |
`information_schema`-style query where the adapter can serve it, and an explicit "not |
| 502 |
supported by this adapter" where it can't, surfaced through the capability flags in |
| 503 |
`hsql info`. High value, but it should not block the rest of the workstream. |
| 504 |
|
| 505 |
### An adapter-API question this raises |
| 506 |
|
| 507 |
`fetch_children` is per-item, which is exactly right for a viewport-driven TUI and forces |
| 508 |
N+1 for bulk access. An adapter that could pull an entire schema's columns in a single |
| 509 |
`information_schema` query has no way to say so. |
| 510 |
|
| 511 |
Worth considering an optional **`fetch_descendants(depth)`** on `InteractiveCatalogItem`, |
| 512 |
with a default implementation that simply walks `fetch_children`. Adapters that can do |
| 513 |
better override it; everything keeps working for those that don't. This is a |
| 514 |
Harlequin-core API decision, not an `hsql` one, and it would improve the TUI's |
| 515 |
expand-all path too. |
| 516 |
|
| 517 |
**Stories:** |
| 518 |
|
| 519 |
- **B1.** As an agent, I run `hsql -P prod catalog` and then `hsql -P prod catalog mydb` |
| 520 |
to orient myself, paying one query per step and knowing what each step cost. |
| 521 |
- **B2.** As an agent, I see `analytics — 400 relations` and scope my next call instead of |
| 522 |
recursing into a walk that would take a minute and blow my context. |
| 523 |
- **B3.** As an agent, I run `hsql -P prod catalog mydb.analytics.orders --format compact` |
| 524 |
and write a correct join on the first attempt, pasting the adapter's own quoted |
| 525 |
identifiers rather than guessing at them. |
| 526 |
- **B4.** As an agent handed an unfamiliar warehouse, I run `hsql find orders` and get a |
| 527 |
path instead of walking three levels to look for one. |
| 528 |
|
| 529 |
### `hsql spec --json` |
| 530 |
|
| 531 |
Dump the full, *installed* CLI surface — including options contributed by whichever |
| 532 |
adapter plugins are present — as JSON. Harlequin already builds these dynamically from |
| 533 |
`AbstractOption`, so the data exists; it just isn't reachable. |
| 534 |
|
| 535 |
This is unusually valuable here precisely because the option surface is plugin-driven. |
| 536 |
No model's pretraining can know that this machine has `harlequin-databricks` installed |
| 537 |
with its particular options. Self-description turns a guessing game into a lookup. |
| 538 |
|
| 539 |
- **B4.** As an agent, I run `hsql spec --json` once at the start of a task and never |
| 540 |
hallucinate a flag for the rest of it. |
| 541 |
|
| 542 |
### `hsql info --json` |
| 543 |
|
| 544 |
The debug-info screen, headless: versions, installed adapters, discovered config files in |
| 545 |
precedence order, the active profile, and **capability flags per adapter** |
| 546 |
(`implements_cancel`, `implements_copy`, `implements_read_only`, |
| 547 |
`implements_validate_sql`, `supports_transactions`). Credentials and connection strings |
| 548 |
redacted. |
| 549 |
|
| 550 |
Capability flags matter: they let an agent know *not* to try `--dry-run` on an adapter |
| 551 |
that can't validate, instead of trying and failing. |
| 552 |
|
| 553 |
> **Amended in M2's plan.** The flags have to be *declared* on the adapter class, not |
| 554 |
> detected on the connection. Reflection can't answer the question: |
| 555 |
> `HarlequinSqliteConnection` defines `validate_sql` and raises `NotImplementedError` from |
| 556 |
> it, so an override check reports SQLite as validating SQL. Nothing is broken by that |
| 557 |
> today — the app catches the error at the call site — but a class variable is the pattern |
| 558 |
> that can be read *before* the call, and the only one `hsql --info` can read while the |
| 559 |
> database is unreachable, which is when a diagnostic is worth most. So `--info` imports |
| 560 |
> adapters and opens no connection. |
| 561 |
|
| 562 |
- **B5.** As an agent debugging a human's setup, I run `hsql info --json` and can tell |
| 563 |
them exactly which config file is winning and why. |
| 564 |
- **B6.** As an agent, I check capability flags before offering the human a feature their |
| 565 |
adapter doesn't support. |
| 566 |
|
| 567 |
### `hsql fmt` |
| 568 |
|
| 569 |
Expose sqlfmt, which is already a dependency. `hsql fmt query.sql`, |
| 570 |
`hsql fmt -c "select 1"`, `--check` for CI. Agents write inconsistent SQL; this |
| 571 |
normalizes it before it lands in a human's repo. Cheap, and a genuinely nice human |
| 572 |
feature too. |
| 573 |
|
| 574 |
> **Cut in M2's plan.** An agent that wants formatted SQL can run `sqlfmt`, which is what |
| 575 |
> this would have wrapped. It is also the only headless mode that would have forced a |
| 576 |
> 196ms sqlfmt import into a package whose import graph is otherwise an enforced contract — |
| 577 |
> paid by the mode alone, but a deferral to maintain forever for a wrapper nobody asked |
| 578 |
> for. |
| 579 |
|
| 580 |
### `hsql history` |
| 581 |
|
| 582 |
Query history is already cached per connection — but as a pickle. Expose it |
| 583 |
(`hsql history --json -n 20`) and additionally write an append-only JSONL log, so both |
| 584 |
agents and humans can read it with ordinary tools. |
| 585 |
|
| 586 |
- **B7.** As an agent joining a task mid-stream, I read the human's recent query history |
| 587 |
and continue their line of investigation instead of starting over. |
| 588 |
|
| 589 |
--- |
| 590 |
|
| 591 |
## 7. Workstream C — The config file as a formal contract |
| 592 |
|
| 593 |
Agents write config files. Today they'd be guessing at TOML structure from prose docs, |
| 594 |
and a wrong guess produces a confusing runtime error. The config is shared between |
| 595 |
`harlequin` and `hsql`, so this serves both. |
| 596 |
|
| 597 |
### Deliverables |
| 598 |
|
| 599 |
1. **A published JSON Schema** for `.harlequin.toml`, at |
| 600 |
`https://harlequin.sh/schemas/config/v1.json` and shipped in the package. Enables the |
| 601 |
`#:schema` comment for taplo / Even Better TOML — editor validation for humans, and a |
| 602 |
verifiable target for agents. |
| 603 |
- Wrinkle: adapter options are dynamic. Solution: publish a base schema for the |
| 604 |
site, and have `hsql config schema --json` generate a locally-accurate one that |
| 605 |
includes the installed adapters' options. |
| 606 |
2. **`hsql config validate [--json]`** — structured diagnostics with file paths and line |
| 607 |
numbers, so an agent can fix its own mistake without a human in the loop. The existing |
| 608 |
`_raise_on_bad_schema` messages are already good; they just need a machine channel. |
| 609 |
3. **`hsql config show [--json]`** — the effective merged config, with provenance per key |
| 610 |
(`limit = 500 # from ~/.harlequin.toml`). This is the single best troubleshooting |
| 611 |
artifact we could produce. |
| 612 |
4. **`hsql config init --non-interactive`** — the TUI wizard (`harlequin --config`) is |
| 613 |
questionary-only, so agents can't use it. A non-interactive path that edits TOML |
| 614 |
through tomlkit (preserving the human's comments and formatting) means an agent can |
| 615 |
safely modify a config it didn't write. The interactive wizard stays exactly where it |
| 616 |
is; each command gets the affordance right for its audience. |
| 617 |
5. **Environment variable interpolation** (`${DB_PASSWORD}`) in config values — closes |
| 618 |
[#898](https://github.com/tconbeer/harlequin/issues/898), and it's a prerequisite for |
| 619 |
agents and CI ever touching a config that involves secrets. |
| 620 |
6. **A formal spec page on the site**: discovery order, merge semantics, precedence, |
| 621 |
every key with its type and default, and the reserved/invalid names. |
| 622 |
|
| 623 |
> **Amended in M2's plan**, on two things this workstream would otherwise document as they |
| 624 |
> stand. |
| 625 |
> |
| 626 |
> **The merge is per top-level key, not per profile, and the result is a start-up |
| 627 |
> failure.** `_merge_config_files()` is a `dict.update()` per file, so a cwd config file |
| 628 |
> that defines any profile replaces the home file's whole `profiles` table — while leaving |
| 629 |
> its `default_profile` in place, since that is a different top-level key. Both commands |
| 630 |
> then refuse to start: *"Config files set the default_profile to personal, but do not |
| 631 |
> define a profile with that name."* Reproduced on this checkout, and against the |
| 632 |
> pre-refactor `config.py` as well, so it is long-standing rather than something the |
| 633 |
> `tomllib` change introduced. M2 makes the merge per-key and treats it as a bug fix; the |
| 634 |
> spec page should describe that rather than what exists today. |
| 635 |
> |
| 636 |
> **Validation runs on the merged document, so no error can name a file.** `load_config()` |
| 637 |
> merges every discovered file and then validates the result, which means a diagnostic can |
| 638 |
> only ever point at a key in a structure nobody wrote. M2 validates each file as it is |
| 639 |
> read and merges only valid ones, which is what makes deliverable 2's file-and-line |
| 640 |
> diagnostics possible. It also adds `hsql --config list-profiles`, since the first |
| 641 |
> question a human asks is what they can pass to `-P`, and a missing name is how the merge |
| 642 |
> bug above becomes visible. |
| 643 |
> |
| 644 |
> **`${VAR}` interpolation has to be a read-path transform.** `harlequin --config` reads |
| 645 |
> the config and writes it back, so resolving values too early bakes a plaintext password |
| 646 |
> into the user's file on their next wizard run. The syntax is `${VAR}` and |
| 647 |
> `${VAR:-default}` — a bare `{` never triggers it, so nothing anyone has in a password |
| 648 |
> today needs escaping — and an unset variable with no default is a config error naming |
| 649 |
> the variable and its file, never an empty string. |
| 650 |
|
| 651 |
### Secrets: #667, #898, and redaction are one feature |
| 652 |
|
| 653 |
[#667](https://github.com/tconbeer/harlequin/issues/667) asks for a password prompt, and |
| 654 |
the maintainer's read at the time was that it wants **a new type of adapter option**. |
| 655 |
That's the right shape, and it does far more than serve the prompt: it turns redaction |
| 656 |
from a discipline into a property of the declaration. |
| 657 |
|
| 658 |
The decisive argument is the plugin ecosystem. Core cannot enumerate every adapter's |
| 659 |
secret — `--service-account-key`, `--token`, `--tls-key`, whatever the next adapter |
| 660 |
invents. But each adapter can declare its own, once, and then every consumer gets it |
| 661 |
free: `hsql info --json`, `config show`, `spec --json`, error output, the debug-info |
| 662 |
screen, and the config wizard's masked input. |
| 663 |
|
| 664 |
Combine that with `${VAR}` interpolation (#898) and the secrets story closes: |
| 665 |
|
| 666 |
- **`PasswordOption`** (or `secret=True` on `AbstractOption`) — declares an option as |
| 667 |
sensitive. Drives `hide_input` at the prompt, a masked widget in the TUI, and |
| 668 |
redaction everywhere else. |
| 669 |
- **Never prompt in headless mode.** A prompt that blocks on stdin is the *worst* |
| 670 |
failure mode for an agent: no output, no exit code, the whole turn burned until |
| 671 |
something times out. `hsql` must fail fast with a message pointing at the profile or the |
| 672 |
env var. |
| 673 |
|
| 674 |
> **Amended in M2's plan: no `--password-stdin` either.** Between profiles, `${VAR}` |
| 675 |
> interpolation and the variables every driver already reads, it fills no gap worth a |
| 676 |
> flag — and the gap it does fill, it fills by consuming the stream `-f -` wants. |
| 677 |
- **`spec --json` marks secret options.** This is what teaches an agent *not* to |
| 678 |
construct `hsql --password hunter2`, which would leak through `ps` and shell history |
| 679 |
to every other user on the box. The skill should say it too, but the machine-readable |
| 680 |
flag is what makes it checkable. |
| 681 |
- **Scrub known secret values from outbound strings** as a backstop. Declarative |
| 682 |
redaction covers values we own; a driver exception that echoes a DSN does not go |
| 683 |
through our option layer. |
| 684 |
- **Connection strings need their own handling.** `conn_str` is a positional argument, so |
| 685 |
no option type covers `postgres://user:pw@host/db`. It needs DSN-aware redaction of its |
| 686 |
own — and [#354](https://github.com/tconbeer/harlequin/issues/354) is evidence that |
| 687 |
people really do put passwords there. |
| 688 |
- **History is the one surface this can't fix.** `create user x password 'y'` is a secret |
| 689 |
inside a query. Worth saying plainly in the docs that history is local-only and may |
| 690 |
contain secrets by construction. |
| 691 |
|
| 692 |
### Stories |
| 693 |
|
| 694 |
- **C0.** As a human, I hand my agent a profile name, and no secret ever appears in an |
| 695 |
argument list, a transcript, or `ps` output. |
| 696 |
- **C1.** As an agent, I add a `prod` profile to a human's existing config without |
| 697 |
clobbering their comments or reformatting the file. |
| 698 |
- **C2.** As an agent, I validate the config I just wrote and get a line number when I |
| 699 |
get it wrong. |
| 700 |
- **C3.** As a human, my editor red-squiggles a typo'd key before I ever run Harlequin. |
| 701 |
- **C4.** As an agent, I write a config that references `${SNOWFLAKE_PASSWORD}` and never |
| 702 |
see the secret itself. |
| 703 |
|
| 704 |
--- |
| 705 |
|
| 706 |
## 8. Workstream D — Docs that machines can read (harlequin.sh) |
| 707 |
|
| 708 |
The docs are already markdown files on disk (`src/docs/**/*.md`) and there's already an |
| 709 |
`/api/docs` index route. Most of this is plumbing we half-have. |
| 710 |
|
| 711 |
### D1. `llms.txt` and `llms-full.txt` |
| 712 |
|
| 713 |
Highest ROI item on the site. `llms.txt` at the root: an index of every docs page with a |
| 714 |
one-line description and a link. `llms-full.txt`: the whole documentation set |
| 715 |
concatenated as clean markdown. Both prerendered at build time. An agent fetches one URL |
| 716 |
and knows everything. |
| 717 |
|
| 718 |
### D2. Raw markdown per page |
| 719 |
|
| 720 |
`https://harlequin.sh/docs/getting-started/running.md` returns `text/markdown`. |
| 721 |
Implemented as a catch-all `+server.ts` reading the source via `import.meta.glob(..., |
| 722 |
{ query: '?raw' })`. |
| 723 |
|
| 724 |
The real work is sanitization: the sources carry mdsvex `<script>` blocks and Svelte |
| 725 |
component tags (`<Tip>`, `<Figure>`, `<Key>`). The raw route must strip the script |
| 726 |
blocks and downgrade components to plain markdown equivalents (`<Tip>` → a blockquote, |
| 727 |
`<Figure>` → an image with the caption as alt text, `<Key>` → backticks). Worth |
| 728 |
budgeting real time for; a raw route that emits Svelte tags is worse than none. |
| 729 |
|
| 730 |
### D3. Docs API v1 |
| 731 |
|
| 732 |
Extend the existing endpoint into something documented and stable: |
| 733 |
|
| 734 |
- `GET /api/docs` → index (exists today) |
| 735 |
- `GET /api/docs/{topic}/{page}` → `{ title, topic, slug, markdown, updated_at }` |
| 736 |
- `GET /api/docs/search?q=` → keyword search over a prebuilt index (the corpus is small; |
| 737 |
no vector store needed) |
| 738 |
- CORS `*`, cached with the ISR config already in use. |
| 739 |
|
| 740 |
### D4. Copy / view as markdown |
| 741 |
|
| 742 |
A "Copy page as Markdown" button and a "View as Markdown" link in the docs layout. The |
| 743 |
copy variant should prepend the canonical URL and title as a header so pasted context |
| 744 |
carries its provenance. Small, cheap, and increasingly expected. |
| 745 |
|
| 746 |
### D5. A "Headless & Agents" docs topic |
| 747 |
|
| 748 |
A first-class topic in the sidebar, not a footnote. Pages: |
| 749 |
|
| 750 |
- The `hsql` CLI — overview and tutorial |
| 751 |
- Output Formats — the table from §5, with examples |
| 752 |
- Exit Codes and Error Handling |
| 753 |
- Catalog and Introspection |
| 754 |
- Safety: read-only, timeouts, dry runs |
| 755 |
- Differences from `psql` |
| 756 |
- Config File Spec (links to Workstream C) |
| 757 |
- Using Harlequin with Claude Code and other agents — the skill |
| 758 |
- The MCP server |
| 759 |
|
| 760 |
The topic is named for the capability rather than the binary, so a human who doesn't yet |
| 761 |
know `hsql` exists can still find it. |
| 762 |
|
| 763 |
### D6. Homepage positioning |
| 764 |
|
| 765 |
The two-command story from §4 needs a home on the landing page — a short section that |
| 766 |
says Harlequin is the IDE, `hsql` is the same engine headless, and both speak fifteen |
| 767 |
databases. This is the page a human sends to their agent, which makes it the entry point |
| 768 |
for P3. |
| 769 |
|
| 770 |
### D7. `AGENTS.md` in the repos |
| 771 |
|
| 772 |
For agents working *on* Harlequin: repo layout, how adapters plug in, how to run tests |
| 773 |
(`make check`), the snapshot-test workflow, and the changelog convention. Add it to this |
| 774 |
repo and to `harlequin-adapter-template` so new adapters inherit it. |
| 775 |
|
| 776 |
### Stories |
| 777 |
|
| 778 |
- **D1s.** As an agent helping a human install Harlequin on Windows, I fetch |
| 779 |
`llms-full.txt` and answer from current docs instead of stale pretraining. |
| 780 |
- **D2s.** As an agent, I fetch one page as markdown and spend a tenth of the tokens I'd |
| 781 |
spend on the rendered HTML. |
| 782 |
- **D3s.** As a human, I click "Copy as Markdown" and paste an accurate page into my |
| 783 |
agent's context. |
| 784 |
|
| 785 |
--- |
| 786 |
|
| 787 |
## 9. Workstream E — Integrations: skill first, MCP last |
| 788 |
|
| 789 |
### The recommendation, and why |
| 790 |
|
| 791 |
**Ship a skill first. Make MCP a thin wrapper over the same execution core, not a |
| 792 |
parallel implementation.** |
| 793 |
|
| 794 |
A good CLI plus a skill — one markdown file that teaches `hsql` — works in *any* agent |
| 795 |
harness that can run a shell command: Claude Code, Codex, Cursor, aider, a bash script, |
| 796 |
CI. It costs one file to maintain, adds zero tokens to requests that don't use it, and |
| 797 |
keeps a single tested code path. |
| 798 |
|
| 799 |
MCP earns its keep in exactly two places, and they're real: |
| 800 |
|
| 801 |
1. **Harnesses without shell access** — Claude Desktop, chat clients, some IDE |
| 802 |
integrations. The CLI is invisible to them. |
| 803 |
2. **Connection reuse and session state.** For Postgres, BigQuery, Trino, and Databricks, |
| 804 |
connection setup dominates a short query. A persistent server also preserves temp |
| 805 |
tables, session settings, and open transactions across calls, which a fresh process |
| 806 |
per query cannot. |
| 807 |
|
| 808 |
So: both, in that order, sharing one core. |
| 809 |
|
| 810 |
### E1. The Harlequin skill |
| 811 |
|
| 812 |
`SKILL.md` in this repo, published on the site, and installable. Contents: |
| 813 |
|
| 814 |
- Discover the setup first: `hsql info --json`, `hsql spec --json` |
| 815 |
- Use profiles, never raw credentials |
| 816 |
- Orient with `catalog --depth 2`, then scope with a pattern |
| 817 |
- Run with `-c`; pick a format on purpose; respect the limit; check for truncation |
| 818 |
- Branch on exit codes |
| 819 |
- Prefer `--read-only` unless the human asked for a write |
| 820 |
- **When to stop and hand off to the human's TUI** — this is the part nobody else will |
| 821 |
write, and it's what makes the skill feel like Harlequin's rather than generic |
| 822 |
|
| 823 |
### E2. `hsql mcp` |
| 824 |
|
| 825 |
`hsql mcp --profile prod` starts a stdio MCP server. Deliberately small tool surface — |
| 826 |
every tool is tokens in every request: |
| 827 |
|
| 828 |
- `run_query(sql, format?, limit?)` |
| 829 |
- `list_catalog(pattern?, depth?)` |
| 830 |
- `describe_object(name)` |
| 831 |
- `explain_query(sql)` |
| 832 |
- `format_sql(sql)` |
| 833 |
|
| 834 |
Plus MCP *resources* for the catalog and for the docs (`llms-full.txt`), which is the |
| 835 |
idiomatic way to expose reference material without spending tool-schema tokens. |
| 836 |
|
| 837 |
Read-only by default; writes require an explicit `--allow-writes`. The MCP dependencies |
| 838 |
ship as an optional extra so the base install stays lean. |
| 839 |
|
| 840 |
**Sequenced last, deliberately** (M6). Everything above it — the execution core, the |
| 841 |
catalog navigation, the capability flags, the skill — is what an MCP server would be a |
| 842 |
wrapper *around*. Building it before those settle means designing tool schemas against a |
| 843 |
moving target and then maintaining the mistakes. Shipping it last also means we'll know |
| 844 |
from real skill usage which five tools are actually worth their tokens, rather than |
| 845 |
guessing. |
| 846 |
|
| 847 |
### Stories |
| 848 |
|
| 849 |
- **E1s.** As an agent in Claude Code, I install the Harlequin skill and immediately use |
| 850 |
the right flags, formats, and limits without trial and error. |
| 851 |
- **E2s.** As a human in Claude Desktop with no shell, I add the Harlequin MCP server and |
| 852 |
ask questions about my Postgres database. |
| 853 |
- **E3s.** As an agent running twenty queries against BigQuery, I reuse one connection |
| 854 |
instead of paying setup cost twenty times. |
| 855 |
|
| 856 |
--- |
| 857 |
|
| 858 |
## 10. Workstream F — Human ↔ agent handoff |
| 859 |
|
| 860 |
This is the part only Harlequin can build, and I'd resist the temptation to sequence it |
| 861 |
last just because it's the least conventional. |
| 862 |
|
| 863 |
- **`hsql open query.sql`** launches the TUI with the query loaded in a new buffer, |
| 864 |
**not executed**. The agent drafts; the human reviews, edits, and runs. Buffers already |
| 865 |
persist through `editor_cache.py`, so the machinery is close at hand. Having a verb for |
| 866 |
this on the agent-facing command is exactly the ergonomic win the two-command split |
| 867 |
buys us. |
| 868 |
- **"Copy CLI command" action in the TUI** — writes `hsql -P prod -c '<current buffer>' |
| 869 |
--csv` to the clipboard, so a human can hand their agent something exactly |
| 870 |
reproducible. |
| 871 |
- **Readable history** (Workstream B) closes the loop the other way. |
| 872 |
|
| 873 |
### On issue #952 — natural language to SQL |
| 874 |
|
| 875 |
I don't think Harlequin should embed an LLM. No API keys, no model selection, no |
| 876 |
provider coupling, no support burden for someone else's rate limits. |
| 877 |
|
| 878 |
But there's a middle path that fits Harlequin's plugin ethos and answers the actual |
| 879 |
request: **a configurable external-command hook.** Let the user define, in their config, |
| 880 |
a command that receives the current buffer (and optionally the catalog) on stdin and |
| 881 |
whose stdout is inserted into the editor. Then `Ctrl+G` runs *whatever the user |
| 882 |
already trusts* — `claude -p`, `llm`, a local model, a company-internal endpoint. Same |
| 883 |
shape as the existing external-editor request ([#767](https://github.com/tconbeer/harlequin/issues/767), |
| 884 |
[#769](https://github.com/tconbeer/harlequin/issues/769)), and it inherits their |
| 885 |
credentials rather than asking for new ones. |
| 886 |
|
| 887 |
### Stories |
| 888 |
|
| 889 |
- **F1.** As an agent, I draft a migration and `hsql open` it in the human's TUI for |
| 890 |
review rather than executing it myself. |
| 891 |
- **F2.** As a human, I explore interactively, then copy a reproducible `hsql` command for |
| 892 |
my agent to parameterize and run in CI. |
| 893 |
- **F3.** As a human, I press one key in the TUI and my own AI tool rewrites my query — |
| 894 |
using my own credentials, not Harlequin's. |
| 895 |
|
| 896 |
--- |
| 897 |
|
| 898 |
## 11. Roadmap |
| 899 |
|
| 900 |
Because the CLI is a separate command, **every milestone here is purely additive to |
| 901 |
`harlequin`** and can ship in 2.x minors. Nothing waits for a major version. |
| 902 |
|
| 903 |
| Milestone | Theme | Contents | |
| 904 |
| --- | --- | --- | |
| 905 |
| **M0** | Secure the name | Publish `hsql` to PyPI as a metapackage depending on `harlequin`, so `pip install hsql` works today and the name can't be taken while the rest of this ships. | |
| 906 |
| **M1** | `hsql` | Second console script; extract the shared execution core; import-linter rule and cold-start benchmark in CI. `-c`, `-f`, stdin, `-o`, `--format` + shorthands, default `--limit 500`, truncation notices, `--stats`, exit codes, `--on-error`, `--color`/`NO_COLOR`, plain errors. Unknown-option hint on `harlequin`. Docs: the "Headless & Agents" topic, seeded. **Closes #524.** | |
| 907 |
| **M2** | Self-description & safety | `catalog` (one level below the match, child counts, node budget), `describe`, `info --json`, `spec --json`, `fmt`, `config validate/show/schema/init`, capability flags, secret option type + declarative redaction (**#667**), env interpolation (**#898**), `--read-only`, `--timeout`, `--dry-run`. Published JSON Schema. Stretch: `find` + `implements_catalog_search`, optional `fetch_descendants`. | |
| 908 |
| **M3** | Docs for machines | `llms.txt`, `llms-full.txt`, raw `.md` routes, Docs API v1, copy-as-markdown, homepage positioning, `AGENTS.md`. | |
| 909 |
| **M4** | Skill & handoff | Skill, `hsql open`, JSONL history, "Copy CLI command", external-command hook. | |
| 910 |
| **M5** | Scale | Streaming output, `--offset`/pagination, memory work for large results (**#875**). | |
| 911 |
| **M6** | MCP | `hsql mcp` over the M1 execution core: `run_query`, `list_catalog`, `describe_object`, `explain_query`, `format_sql`, plus catalog and docs resources. Read-only by default. | |
| 912 |
|
| 913 |
**On M1.** Implementation is planned in detail in |
| 914 |
[the M1 technical plan](./m1-hsql-technical-plan.md): the module architecture, the |
| 915 |
refactors that have to land first, and an eight-PR sequence across two releases. A few |
| 916 |
figures and defaults in this document were corrected against measurements taken while |
| 917 |
writing it; §8 there lists them. PRs 1–6 shipped and PR 7, the docs topic, is in flight; |
| 918 |
PR 8, the agent eval suite, was not built. |
| 919 |
|
| 920 |
**On M2.** Likewise in [the M2 technical plan](./m2-hsql-technical-plan.md), across three |
| 921 |
releases rather than one: **config and self-description first**, since they fix bugs that |
| 922 |
exist today and need no adapter change at all; then the catalog, with search implemented for |
| 923 |
both in-tree adapters rather than left as a stretch; then the safety flags, which need |
| 924 |
additive members on the adapter contract and therefore an ecosystem rollout. The amendments |
| 925 |
marked above are the corrections that came out of measuring it. This table's M2 row is |
| 926 |
otherwise all subtraction: the introspection surface is mode options rather than |
| 927 |
subcommands, and `describe`, `fmt`, `--dry-run`, `--single-transaction`, `--password-stdin`, |
| 928 |
recursive `--depth`, the node budget, child counts and the `compact` format are all cut — |
| 929 |
each for a reason given in §7 of that plan. |
| 930 |
|
| 931 |
**On M0.** Name availability is the only thing in this plan that someone else can take |
| 932 |
while we deliberate, which is why it's a milestone rather than a task. It's also cheap |
| 933 |
enough to do this week. |
| 934 |
|
| 935 |
A few things worth getting right the first time: |
| 936 |
|
| 937 |
- **Metapackage, not a second copy of the artifact.** `hsql` should be a small |
| 938 |
distribution whose only dependency is `harlequin`. Republishing the same built wheel |
| 939 |
under a second name would put duplicate modules on disk and conflict outright if a user |
| 940 |
installed both. |
| 941 |
- **Version it independently and float the dependency** — `hsql 0.1.0` requiring |
| 942 |
`harlequin>=2.x` — so it doesn't need a release every time Harlequin cuts one. (Also |
| 943 |
reversed once M1 shipped: it now takes Harlequin's version and pins it. See the status |
| 944 |
note below.) |
| 945 |
- **No placeholder console script.** It's tempting to ship an `hsql` command that prints |
| 946 |
"coming soon," but from M1 the `harlequin` distribution itself provides that entry |
| 947 |
point, and two installed distributions claiming the same script name is a mess to |
| 948 |
unwind. `pip install hsql` giving you Harlequin, plus a README that says what's coming, |
| 949 |
is honest enough. (M1 shipped, and the metapackage does declare the script now — see |
| 950 |
the status note below. The half of this that held up is "no *placeholder*": it points |
| 951 |
at Harlequin's entry point rather than standing in for it.) |
| 952 |
- Reserve the same name anywhere else Harlequin is published or packaged while we're at |
| 953 |
it. |
| 954 |
|
| 955 |
This is a genuine, working package rather than a squat, which also keeps it on the right |
| 956 |
side of PyPI's naming policy. |
| 957 |
|
| 958 |
*Status: the metapackage lives in `packaging/hsql/`, and M1 changed two of the decisions |
| 959 |
above.* |
| 960 |
|
| 961 |
*It declares `hsql = "harlequin.hsql:main"` — the same entry point Harlequin's own script |
| 962 |
uses, so the two console scripts are byte-identical and co-installing them is a no-op. |
| 963 |
Without it, `uvx hsql` still ran, but uv warned that the executable came from a |
| 964 |
dependency and suggested `uvx --from harlequin hsql`, on the one command line this |
| 965 |
package exists to make short.* |
| 966 |
|
| 967 |
*And it ships with Harlequin rather than on its own cadence: `publish.yml` builds and |
| 968 |
uploads both from one release, and the metapackage carries Harlequin's version number and |
| 969 |
pins that release exactly — `release.yml` sets all three numbers with `uv version` and |
| 970 |
`uv add`, and `test_packaging.py` fails the release PR if they ever disagree. So `hsql |
| 971 |
2.9.0` is `harlequin 2.9.0`, whichever name a caller installs by. The independent cadence |
| 972 |
was the right call while this package was a reserved name and nothing else; once it |
| 973 |
points at an entry point that only some releases have, a floating floor is a promise the |
| 974 |
metapackage cannot keep.* |
| 975 |
|
| 976 |
`--read-only` sits in M2 rather than M1 only because it requires an adapter-interface |
| 977 |
addition and therefore an ecosystem rollout; if that lands early, pull it forward. It's |
| 978 |
the flag that makes everything else socially acceptable. |
| 979 |
|
| 980 |
### If only three things get built |
| 981 |
|
| 982 |
1. **`hsql`** with `-c` / `-f` / `-o` / `--format`, a strict stdout/stderr split, |
| 983 |
documented exit codes, and honest truncation. |
| 984 |
2. **`hsql catalog --format compact`**. |
| 985 |
3. **`llms.txt` + raw markdown docs + the "Headless & Agents" topic + the skill.** |
| 986 |
|
| 987 |
That trio takes an agent from "reinvents psql badly" to "writes a correct query against |
| 988 |
any of fifteen databases on the first try." |
| 989 |
|
| 990 |
--- |
| 991 |
|
| 992 |
## 12. Risks and open questions |
| 993 |
|
| 994 |
- **Two front doors can drift.** The whole bet rests on one shared execution core. If |
| 995 |
`hsql` grows its own query logic, or the TUI keeps a parallel path, we've built two |
| 996 |
products. Mitigation: extract the core in M1 and refactor the TUI onto it in the same |
| 997 |
milestone, not later. |
| 998 |
- **Discoverability of `hsql`.** Nobody guesses it exists; `harlequin -c` is guessable. |
| 999 |
Mitigated by the unknown-option hint, the docs topic named for the capability rather |
| 1000 |
than the binary, homepage positioning, and the skill. Worth watching — if support |
| 1001 |
questions suggest people can't find it, revisit. |
| 1002 |
- **Name mindshare.** `hsql` competes with HyperSQL in search results. No PATH or PyPI |
| 1003 |
collision, but SEO for "hsql" will take work; docs should always spell it "hsql, the |
| 1004 |
Harlequin CLI" on first use. |
| 1005 |
- **Adapter ecosystem lift.** `--read-only`, `validate_sql`, catalog search, and any bulk |
| 1006 |
`fetch_descendants` are optional adapter methods. `hsql` must degrade gracefully and |
| 1007 |
*say which adapter lacks what* — hence capability flags. Third-party adapters will lag; |
| 1008 |
plan for a long tail. |
| 1009 |
- **Catalog fetch cost is the sharpest edge in the plan.** The default is safe by |
| 1010 |
construction (§6), but `--depth 2` on a wide schema is an N+1 walk on most adapters, |
| 1011 |
and it's also the single most useful catalog call an agent can make. Child counts, the |
| 1012 |
node budget, and `--stats` are what keep that honest until adapters can serve it in |
| 1013 |
one query. |
| 1014 |
- **Cold start.** Measured rather than feared, and worse than this section assumed: a |
| 1015 |
bare `harlequin --version` takes 1.3s today. Lazy entry-point resolution is a |
| 1016 |
requirement of M1, not a contingency — `load_adapter_plugins()` imports every installed |
| 1017 |
adapter on every invocation, worth 160ms with four installed and unbounded as the |
| 1018 |
ecosystem grows. An import-linter rule in this repo would also never have caught the |
| 1019 |
largest single cause, which is upstream: `harlequin.adapter` pays 265ms for |
| 1020 |
`textual-fastdatatable`, whose backend needs no Textual but whose package `__init__` |
| 1021 |
imports the DataTable widget. See the M1 technical plan. |
| 1022 |
- **Memory.** Materializing an Arrow table for a large export is the same failure as |
| 1023 |
#875, and it is not fixed in M1. See the streaming note in §5. |
| 1024 |
- **Secrets.** `info --json`, `config show`, error messages, and history are all leak |
| 1025 |
surfaces, and agents paste output into transcripts. Mitigated structurally by the |
| 1026 |
secret option type in §7 (**#667**) rather than by remembering to redact at each site — |
| 1027 |
but note that connection strings and query history sit outside that mechanism and need |
| 1028 |
their own handling. |
| 1029 |
- **Two help surfaces to keep coherent.** `harlequin --help` and `hsql --help` share the |
| 1030 |
adapter option matrix and must not disagree. Generate both from the same option |
| 1031 |
definitions. |
| 1032 |
- **Docs drift.** `spec --json` output and the site's config spec must be generated from |
| 1033 |
the same source, or they'll disagree within two releases. |
| 1034 |
- **MCP maintenance.** Only worth it as a thin wrapper. If it starts growing its own |
| 1035 |
query logic, that's the signal we got the layering wrong. |
| 1036 |
|
| 1037 |
## 13. How we'd know it worked |
| 1038 |
|
| 1039 |
- `hsql -c "select 1"` against DuckDB completes in **< 300ms**, tracked in CI. |
| 1040 |
- The `hsql` module graph contains **no `textual` import**, enforced in CI. |
| 1041 |
- **An agent eval suite in CI**: a handful of realistic tasks ("find the top 10 customers |
| 1042 |
by revenue") run against fixture databases with a small model, scored on wrong-flag |
| 1043 |
retries and task completion. This is the metric that actually matters, and it's the one |
| 1044 |
that would keep the CLI honest as it grows. I'd build it in M1 with three tasks and |
| 1045 |
expand it. |
| 1046 |
- An agent given only `hsql --help` completes a query task with **zero** wrong-flag |
| 1047 |
retries. |
| 1048 |
- `llms.txt` is served, and every docs page is fetchable as clean markdown. |
| 1049 |
- #524, #667, and #898 closed; #952 answered without embedding an LLM. |
| 1050 |
- Qualitatively: someone writes "just use hsql, it works the same everywhere" in a thread |
| 1051 |
about getting an agent to talk to a database. |