Debian Codegraph @

docs/plans/m4-hsql-technical-plan.md

raw
1 # M4 Technical Plan — the handoff, and the two hooks
2
3 Implementation plan for milestone M4 of [Harlequin for agents](./harlequin-for-agents.md),
4 following [M1](./m1-hsql-technical-plan.md), [M2](./m2-hsql-technical-plan.md) and
5 [M3](./m3-hsql-technical-plan.md). M1 built the command, M2 taught it to describe itself, M3
6 wrote the docs and the skill an agent reads before it runs. This one is Workstream F: what
7 happens when the agent and the human need to hand work to each other.
8
9 **M4's scope, from the roadmap:** the skill, `hsql open`, JSONL history, "Copy CLI command",
10 and the external-command hook. **The skill (E1) shipped in M3** — it is in the wheel, prints
11 from `hsql --skill`, and installs as a plugin — so what is left is the four handoff features.
12 Two of those turn out to be three: the external-command hook covers two requests that share
13 almost nothing, and this plan splits them (§6.1). And "JSONL history" turns out to name a
14 storage format that the History screen's missing search rules out (§6.4).
15
16 **The issues M4 closes.** [#1102](https://github.com/tconbeer/harlequin/issues/1102), external
17 editor support, was opened while this plan was being written and carries a reference
18 implementation from Posting. [#952](https://github.com/tconbeer/harlequin/issues/952),
19 natural language to SQL, is closed `not planned` — "I won't be adding this to Harlequin" — and
20 the command hook is the answer that stays true to that: Harlequin runs the tool the user
21 already trusts, with the user's own credentials, and embeds no model (§8).
22 [#850](https://github.com/tconbeer/harlequin/issues/850), the History screen's UI, and
23 [#429](https://github.com/tconbeer/harlequin/issues/429), search in that screen, ride along
24 with the release that changes what it reads — and #429 is what decides how the history is
25 stored at all (§3.2, §3.4).
26
27 **Three releases, and the editor and the hooks go first** (Ted's call). Nothing in this
28 milestone depends on anything else in it, so the order is a product decision: A is the editor
29 and the hooks, B is query history and search, C is the handoff (§4).
30
31 **Bottom line up front.** Three claims, each measured below.
32
33 1. **The handoff between the two commands is a process boundary, and everything cheap about
34 it is on the far side of one.** `hsql --open` cannot put a buffer in front of a human
35 in-process: `harlequin.editor_cache` imports Textual — 341 modules, +164ms over a bare
36 interpreter, against a whole `hsql --version` of 118ms — and it is rewritten *whole* at
37 `action_quit`, so a second writer would race a running IDE for the file that holds every
38 open buffer (§1.1). `--open` execs a documented flag on the other command instead, and the
39 argv it builds is the same module the TUI's "Copy CLI command" reads backwards (§3.1, §3.5).
40 2. **The query history both commands should share cannot be either of the things that hold it
41 today, and search is what settles what replaces them.** The IDE's history is a pickle
42 inside the catalog cache, written once, at quit — so a crash, a `kill`, or a container that
43 goes away loses the session — and it lives in `harlequin.history`, which imports rich,
44 which is on the headless FORBIDDEN list and costs +46ms on a 118ms command (§1.2, §1.3).
45 The store both commands can write is a SQLite database, not the JSONL file the roadmap
46 names: with [#429](https://github.com/tconbeer/harlequin/issues/429) in scope, searching
47 100,000 records costs **396ms** as a file scan and **35ms** as a `like`, and 400ms per
48 keystroke is not a filter anyone can type into. `sqlite3` is stdlib, imports *cheaper* than
49 `json` (+4.0ms against +7.6ms), and costs 0.020ms a row to write (§3.2).
50 3. **The external editor and the AI hook are two features, and the terminal is why.** One
51 needs the terminal and must suspend the app; the other must not have it and must not block
52 the app. They differ in thread, in exchange medium, in failure mode, in what cancels them,
53 and in whether the user's query leaves the machine (§6.1). And a shell command that came
54 from a config file is not the same as one that came from `$EDITOR`: config files merge from
55 the current working directory, so a repository you cloned can define one (§1.7). The
56 environment is the user; a file is not.
57
58 ---
59
60 ## 1. Where things are today
61
62 Measured on this checkout — 2.12.2, the release the M2 safety work closed — with Python
63 3.10.15 on Linux, textual 8.2.8, textual-textarea 0.18.1. Timings are the minimum of five
64 subprocess runs; a bare `python -c "import sys"` is 12.7ms on this machine and is subtracted
65 where an import cost is given.
66
67 ### 1.1 Nothing outside the IDE can put a query in front of a human
68
69 `harlequin` takes `CONN_STR` positionally and has no file argument. `-f` is not free: it is
70 `--show-files`, the directory the Data Catalog shows in a file tree. The only way to get a
71 `.sql` file into a buffer today is `code_editor.load` — the editor's Open Query action, a path
72 input inside a running app.
73
74 The product plan's note that "buffers already persist through `editor_cache.py`, so the
75 machinery is close at hand" is the one part of §10 that measurement contradicts, in both
76 directions that matter:
77
78 ```
79 import harlequin.editor_cache 175.1ms (+164.4ms) 341 modules textual: yes
80 import harlequin.history 59.0ms ( +45.9ms) 142 modules textual: no, rich: yes
81 import harlequin.catalog_cache (rich: yes, via harlequin.history)
82 ```
83
84 `editor_cache.BufferState` holds a `textual.widgets.text_area.Selection`, so reading or
85 writing that cache imports the TUI. And the cache is not an append-only store: `action_quit`
86 writes `Cache(focus_index, buffers)` — every open buffer, all at once (`app.py:963`). A second
87 process appending a draft to it would be writing the file a running IDE is about to overwrite
88 from memory.
89
90 So the handoff cannot be "hsql writes the buffer cache." It has to be an argument to the other
91 command.
92
93 ### 1.2 History is a pickle, written once, at quit
94
95 `History` is a `deque(maxlen=500)` of `QueryExecution` records, per connection hash, stored
96 inside `CatalogCache.history` and pickled to the user cache dir. It is loaded on
97 `CatalogCacheLoaded` and written in exactly one place: `action_quit` (`app.py:965-977`),
98 alongside the editor cache. Every `append_to_history()` between start-up and quit lives only
99 in memory.
100
101 Three consequences, all of which M4 has to deal with:
102
103 - **A session that does not exit cleanly has no history.** A crash, a `kill`, a closed
104 terminal, a container reclaimed under a remote session: the queries are gone.
105 - **`hsql` writes nothing.** An agent can run forty queries against the human's database and
106 leave no trace the human's History screen will ever show. This is Workstream B's "closes the
107 loop the other way", and it is currently closed in neither direction.
108 - **A pickle is not a thing "both agents and humans can read with ordinary tools"** — the
109 product plan's own criterion. Reading it requires importing `harlequin.history` to unpickle
110 the dataclass, which imports rich.
111
112 It also cannot be searched. The History screen is an `OptionList` of at most 500 records with
113 no filter input, so "what was that query I ran last week" is answered by scrolling —
114 [#429](https://github.com/tconbeer/harlequin/issues/429), open since January 2024. Search is
115 the requirement that decides the storage (§3.2), which is why it belongs in this milestone
116 rather than after it.
117
118 And the screen that shows it has other problems, filed as
119 [#850](https://github.com/tconbeer/harlequin/issues/850). `HistoryScreen` subclasses `Screen`,
120 not `ModalScreen` — and `ModalScreen` is the one whose "bindings take precedence over the
121 App's", so every app-level key is live behind a screen whose job is to pick one query. Its
122 preview pane is a `TextEditor` with `read_only=True`, which stops edits but not focus: Tab or a
123 click puts a cursor in a query the user cannot change. Ted's reading of the issue is that the
124 interactivity of the preview is the problem, not the missing key list.
125
126 ### 1.3 `harlequin.history` is a rendering, and headless code may not import it
127
128 `QueryExecution.__rich__` builds a `Group` of a `Columns` and a `Text`: the History screen's
129 row, in the dataclass that holds the record. `tests/unit_tests/test_import_hygiene.py` lists
130 `rich` in `FORBIDDEN` for every headless import, for the reason the module docstring gives —
131 nothing headless renders — and it is the guard that caught rich arriving sideways through
132 `textual_fastdatatable` before 0.17.1 deferred it.
133
134 Measured, that guard is not ceremony: `harlequin.history` costs +46ms, which is 39% of a whole
135 `hsql --version` invocation:
136
137 ```
138 hsql --version 114-119ms
139 harlequin --version 621-636ms
140 ```
141
142 `harlequin.catalog_cache` imports `harlequin.history`, so it carries rich too — which means
143 `get_connection_hash()`, the function that decides *which* history a session gets, is also
144 unreachable from `hsql` today. Whatever writes the shared log has to live below both.
145
146 ### 1.4 Nothing in the app knows what command line started it
147
148 "Copy CLI command" has to render an `hsql` invocation that reproduces what the human is
149 looking at. The app cannot: `Harlequin.__init__` receives an *instantiated* adapter, plus
150 `profile_name`, `connection_hash`, and the TUI's own settings. `conn_str` is consumed in
151 `cli.py` and handed to the adapter's constructor; no attribute on `HarlequinAdapter` carries
152 it — adapters store it themselves, and the contract does not require them to. `--config-path`,
153 `-a`, `--read-only` and any adapter options typed on the command line are gone by the time the
154 app exists.
155
156 The app also never calls `redact.hide_secrets_in()`. `hsql` does, on every run; the IDE does
157 not, so `redact_text()` in an IDE process masks nothing, because `_HIDDEN` is empty. Anything
158 M4 adds that prints or copies a value — a clipboard string, a log line — needs that call to
159 have happened.
160
161 ### 1.5 Actions are a fixed registry, and an unknown name crashes the app on mount
162
163 `HARLEQUIN_ACTIONS` maps ~90 action names to `(target widget class, action method)`.
164 Keymaps — plugin or config — map keys to those names, and `action_bind_keymaps()` /
165 `bind_keys()` look each one up with `HARLEQUIN_ACTIONS[binding.action]`. `keymap.py` carries
166 the TODO: `# TODO: ADD VALIDATION when creating bindings from config`.
167
168 Measured, with a keymap whose only binding names `code_editor.formt`:
169
170 ```
171 KeyError: 'code_editor.formt'
172 in action_bind_keymaps, during on_mount
173 ```
174
175 The app dies in mount with a traceback, on a typo in a config file, and `harlequin --keys` —
176 the tool for fixing keymaps — is a second Textual app that reads the same registry. M4 makes
177 action names come partly from config (one per configured command), which turns this from a
178 papercut into the failure mode of a new feature.
179
180 ### 1.6 Nothing runs a subprocess, `suspend()` exists, and tests cannot reach it
181
182 There is no `subprocess`, `os.system` or `$EDITOR` anywhere in `src/`. Textual's
183 `App.suspend()` is a synchronous context manager that publishes a suspend signal, drops out of
184 application mode, redirects `stdout`/`stderr` back to the real ones for the duration, and
185 resumes with `refresh(layout=True)`. Two things about it shape §3.6:
186
187 - It is **main-thread only**, by construction: it redirects the process's streams and drives
188 the driver. Nothing in a `@work(thread=True)` worker may call it.
189 - It is **unavailable in tests.** `can_suspend` is True on the Linux and Windows drivers and
190 False on the base driver, which the headless driver inherits. Measured inside `run_test()`:
191
192 ```
193 DRIVER: HeadlessDriver can_suspend: False
194 RAISED: SuspendNotSupported App.suspend is not supported in this environment.
195 ```
196
197 So the external-editor path needs a seam a test can patch, and the `SuspendNotSupported`
198 branch is itself a user-visible behavior to test rather than an assertion that never fires.
199
200 ### 1.7 Config files merge from the working directory, so a config file is not the user
201
202 `load_config()` reads, in priority order, an explicit `--config-path`, then `./.harlequin.toml`
203 and `./pyproject.toml`, then the user config dir, then home — and merges them, nearest file
204 wins, per profile and per keymap. A repository you clone can therefore supply a profile, a
205 keymap, and (today) a duckdb `init_path`, which runs SQL at connection time.
206
207 That is already a real trust surface, and it is bounded: arbitrary SQL against a database the
208 user chose to open. A `[commands]` table would make it arbitrary code as the user, from a file
209 they may never have read — and, as Ted put it, a git-synced dotfiles repo makes the same true
210 of a file in the user's *own* config dir. `$EDITOR`, by contrast, is the user's own shell
211 session. That asymmetry is the whole design of §3.8.
212
213 ### 1.8 What the skill can say about handing off, and what it cannot
214
215 M3 shipped the skill with section 9, "Know when to hand off," and it currently reads: stop,
216 and tell the human to run `harlequin -P <profile>`. That is the best available advice for an
217 agent holding a draft migration, and it loses the draft: the human gets an empty editor and
218 the agent's SQL is in a transcript somewhere above. §3.1 is what lets that paragraph say
219 `hsql --open -f draft.sql -P prod` instead, and M3's §7 already names it as the paragraph M4
220 rewrites.
221
222 ---
223
224 ## 2. The obstacles, stated plainly
225
226 1. **The two commands cannot share a process.** One is a TUI that owns the terminal; the other
227 must not import Textual. Every handoff feature in M4 is therefore an argv, a file, or a
228 log — never an import.
229 2. **The store that both commands write has to be below rich.** Not `harlequin.history`, not
230 `catalog_cache`, and not a pickle of a dataclass whose `__repr__` is a Rich renderable.
231 3. **The shared store has more than one writer and now has to be searched.** Concurrency
232 alone an append-only file survives; search over all of it — not a bounded tail — is what it
233 cannot serve at an interactive latency.
234 4. **The app does not remember how it was started**, and half of what it would need to
235 remember is secret.
236 5. **Running someone else's program from inside a Textual app has two incompatible shapes,**
237 and picking one shape for both produces a config whose validity table is mostly errors.
238 6. **A config file can now ask Harlequin to execute a shell command,** and config files arrive
239 from directories the user did not audit.
240 7. **A user-defined action name has to exist before a keymap can bind it,** and today an
241 action name that does not exist is a crash rather than a message.
242
243 ---
244
245 ## 3. Target architecture
246
247 Six deliverables, three new modules and one new mode, all of the new modules below rich:
248
249 ```
250 harlequin/
251 invocation.py # what a command line said; renders back to either command's argv
252 query_log.py # the query history: one SQLite store, written by both commands
253 external.py # running someone else's program: the two shapes, and the trust gate
254 hsql/modes/history.py # the store, as a result set, like every other mode
255 ```
256
257 `invocation.py` and `query_log.py` are importable by `hsql` (stdlib plus `platformdirs` and
258 `harlequin.redact`), and `modes/history.py` is imported by the callback only when the mode is
259 chosen, as every mode is. `external.py` is the IDE's, and imports Textual only under
260 `TYPE_CHECKING`; the app owns the widgets, this module owns the process.
261
262 ### 3.1 `hsql --open`, and the flag on the other side
263
264 **A mode option, not a subcommand.** M2 settled that (`hsql catalog` versus a DuckDB file
265 named `catalog`); `--open` needs no new rule, and reuses the SQL sources the command already
266 has. All three of these work, because `-c`, `-f` and stdin are already one layer:
267
268 ```bash
269 hsql --open -f migration.sql -P prod # the file, in the human's IDE
270 hsql --open -c "select * from orders …" -P prod
271 claude -p "write the backfill" | hsql --open -P prod
272 ```
273
274 **The other side is a documented flag, not a private channel.** `harlequin --open PATH`
275 (repeatable) loads each file into a new buffer, activates the last, and **executes nothing**.
276 It is worth having on its own: `harlequin --open report.sql` is what a human wants too, and
277 `-f` was never available for it (§1.1).
278
279 **What crosses the boundary.** `--open` does not connect to a database — it is a handoff, not
280 a run — so what it forwards is the connection *description*: `-P`, `--config-path`, `-a` when
281 it was typed, `--read-only`, and `CONN_STR`. Adapter options typed on the command line are
282 rendered back from their declarations (`AbstractOption`, M2's `to_dict()`), with one refusal:
283 **an option declared `secret=True` is not forwarded.** hsql exits in a second; the IDE it
284 launches lives for hours, and `ps` shows an argv for as long as the process holds it. The
285 error names the fix, which is the fix the skill already teaches:
286
287 ```
288 hsql: --password cannot be forwarded to the IDE. Put it in a profile and pass -P.
289 ```
290
291 **Launching.** `[sys.executable, "-m", "harlequin", *argv]`, never a PATH lookup:
292 `harlequin.__main__` exists, `python -m harlequin --version` works today, and the interpreter
293 running `hsql` is by definition the one that has Harlequin installed. On POSIX, `os.execv`
294 replaces the process — no second interpreter resident under the IDE, and signals and exit
295 status belong to the app that owns the screen. On Windows, `os.execv` returns control to the
296 shell while the child still runs, so there it is `subprocess.run()` and the child's return
297 code.
298
299 **The terminal has to be handed over too**, and this is the part that is easy to get wrong.
300 After `cat q.sql | hsql --open`, fd 0 is an exhausted pipe; the IDE would start and read no
301 keys. So `--open` reattaches 0/1/2 from the controlling terminal (`/dev/tty`, `CONIN$`/
302 `CONOUT$` on Windows) whenever they are not a TTY, and refuses with a usage error when there
303 is no controlling terminal to reattach to — a CI job that pipes into `--open` gets a sentence,
304 not a hung process.
305
306 **The scratch file.** `-c` and stdin have no path, so `--open` writes one:
307 `<user_state_dir>/harlequin/open/YYYYmmdd-HHMMSS-<pid>.sql`, pruned of anything older than
308 seven days on each invocation. State, not cache: an unsaved draft is not disposable. A query
309 that came from `-f` is passed by its own path — the IDE copies text into a buffer and never
310 writes back, so the human's file is not touched either way.
311
312 ### 3.2 `harlequin.query_log` — one store, two writers, and why it is SQLite
313
314 One database, at `<user_state_dir>/harlequin/history.db`, one row per statement:
315
316 ```sql
317 create table queries (
318 id integer primary key, -- insertion order, which is also newest-last
319 run_at text not null, -- UTC, ISO-8601
320 program text not null, -- 'hsql' or 'harlequin'
321 connection text, -- the id the caches key on
322 profile text,
323 adapter text,
324 sql text not null,
325 status text not null, -- 'ok' | 'error' | 'canceled'
326 rows integer,
327 truncated integer,
328 elapsed_ms real,
329 error text
330 );
331 create index queries_connection_at on queries (connection, id desc);
332 ```
333
334 **Search is what decides the format** — §1.2 and
335 [#429](https://github.com/tconbeer/harlequin/issues/429). A tail read is bounded by
336 construction — the newest 500 — so an append-only file serves it well. Search is the
337 opposite: its whole value is that it reaches queries you ran weeks ago, which means reading
338 everything. Measured over 100,000 records (52 MB of JSONL, 45 MB of
339 SQLite, both warm in page cache):
340
341 | | JSON Lines | SQLite |
342 | --- | --- | --- |
343 | newest 500 for one connection | 8.2ms (hand-written reverse scan) | 16.7ms (`order by id desc limit 500`) |
344 | **search all of it, newest 500 matches** | **396.4ms** (full scan + parse) | **34.9ms** (`sql like ?`) |
345 | one record written | 0.006ms (`os.write`, `O_APPEND`) | 0.020ms (WAL, `synchronous=normal`) |
346 | import cost | +7.6ms (`json`) | +4.0ms (`sqlite3`) |
347
348 The tail row is a wash and the write row is 14µs on a query that cannot take less than a
349 millisecond. The search row is the milestone: 400ms per keystroke is not a filter anyone can
350 type into, and it is 400ms only because the file was in cache. `sqlite3` is *cheaper* to
351 import than `json`, is stdlib, and is already the module `harlequin_sqlite` drives.
352
353 **Pragmas are part of the design, not tuning.** `journal_mode=wal` and `synchronous=normal`
354 are what make a write 0.020ms; the defaults measure 0.678ms, a 34× difference that would show
355 up on a script of a thousand statements. `busy_timeout=5000` is what makes concurrent writers
356 a non-event: 8 processes × 200 inserts produced 1,600 rows, 0 errors, in 0.15s wall. WAL needs
357 shared memory, which a network home directory does not have, so a failure to enter WAL falls
358 back to the default journal — still 0.678ms, still correct.
359
360 **A schema change is an `alter table`, not a new file.** `pragma user_version` plus an ordered
361 list of migrations, which is the thing the pickle caches cannot do: `CACHE_VERSION` throws the
362 old data away, and history is the one store where that is a loss rather than a re-fetch.
363
364 Everything else about the record is unchanged by the format:
365
366 - **`sql` goes through `redact.redact_text()`** before it is written. A query can carry a
367 credential — `attach 'postgres://user:pw@host'`, `create user … password '…'` — and the
368 product plan's §12 lists query history as a leak surface that sits outside the declaration
369 mechanism. It sits outside the *declaration*, not outside `redact`: `redact_text()` masks
370 every value this process was told to hide. Which means the IDE has to start calling
371 `hide_secrets_in()` (§1.4) — one line in `cli.py`, and the debug screen gets more honest for
372 free.
373 - **`connection` is the same id the caches key on**, so the History screen can show this
374 database's queries and `--history` can filter to them. `get_connection_hash()` moves out of
375 `catalog_cache` into `query_log` (it is a hash of a dict; it never needed rich), and
376 `catalog_cache` imports it from there.
377 - **`status`** is `ok`, `error` or `canceled` — the third because M2 established that a
378 cancelled cursor is indistinguishable from an empty result unless the caller attributes it.
379
380 **Failure never fails a query.** A store that cannot be opened, migrated or written disables
381 logging for the process — `sqlite3.Error` in one place, not at each call site. `hsql` says so
382 once on stderr through `diagnostics` (never stdout — §"stdout belongs to query output"), the
383 IDE notifies once. **Retention** replaces file rotation and is a `delete` rather than a
384 `rename`: once per process, rows beyond the newest 100,000 go, so nothing is ever lost from
385 the end that the beginning did not push out.
386
387 **Opt-out** is `--no-write-history`, a flag on both commands and so a profile key of the same
388 name (Ted's call). Spelled as a refusal because only one of the two values changes behavior,
389 and because `--history` is the mode below: a key called `history` and a mode called `--history`
390 would have been one word meaning two things. Nothing else reports the store's path: `--info`
391 describes the installation, not the user's data, and the mode below is how a caller reads the
392 rows without needing to know where they are.
393
394 **JSON Lines does not go away; it stops being the storage.** `hsql --history --jsonl` emits
395 exactly the record above, one object per line, because the mode is a result set and every
396 format already works on it (§3.3) — so the "readable with ordinary tools" property the product
397 plan asked for now works on Windows and needs no `jq`. And the store is a SQLite file, so the
398 other ordinary tool is Harlequin: `harlequin -a sqlite ~/.local/state/harlequin/history.db`
399 opens your own query history in the IDE, with a catalog and a results viewer around it.
400
401 ### 3.3 `hsql --history` and `--history-search`, the modes that read the store
402
403 Two mode options, shaped like the two M2 built — `--catalog` lists, `--catalog-search` finds —
404 and they cost almost nothing to build, because the whole output layer is already written and
405 **these two are not listings at all: they are queries.** `--catalog` has to synthesize a result
406 set, since what it is reporting on is a walk over catalog objects, and that is what
407 `query.rows_to_result()` exists for. `--history` is running SQL against a SQLite database, so
408 its rows go where a cursor's rows go: `create_backend(rows, column_names=COLUMNS)`, the same
409 call `query.fetch()` makes for every query and the same one `harlequin_sqlite` makes with its
410 own `fetchall()`. What comes back is the `ResultSet` the query path builds, so `--format
411 json`, `--jsonl`, `--csv`, `-x`, `-o PATH`, `--stats` and the layout flags all work on it the
412 day it lands, and none of them is a line of new code.
413
414 Through stdlib `sqlite3`, not through the SQLite adapter: `-P prod` names the adapter whose
415 `connection_id` filters the store, and loading a second adapter plug-in to read a file this
416 module already owns would be a strange way to answer a question about `postgres`.
417
418 ```bash
419 hsql --history --limit 20 # the last 20, as a table
420 hsql --history -P prod --json # this profile's, for an agent
421 hsql --history-search "line_items" # every query that mentions it, newest first
422 hsql --history -x --limit 1 # the last one, vertically
423 ```
424
425 - **The only database they open is the store.** They are the only modes that read a profile
426 and build an adapter without ever connecting with it: the adapter is constructed solely to
427 ask it for `connection_id`, which is what filters the store to one database. A history mode
428 that woke a warehouse to list queries would be its own kind of joke.
429 - **Scope follows the invocation.** `-P`, `-a` or a `CONN_STR` narrows to that connection;
430 with none of them, the mode reports every connection, because "I typed `hsql --history` and
431 got someone else's idea of the default database" is the surprising answer. The `profile` and
432 `adapter` columns are what tell them apart.
433 - **Newest first**, which is what every shell means by history, and what makes `--limit` mean
434 "the most recent N" rather than "the oldest N". `--limit` is honored here rather than refused
435 as it is under `--catalog`: the store has a row count, so a hard limit on it is exact.
436 Default 500 — the size of the deque the History screen has always kept — and `-1` for all.
437 - **Columns:** `run_at`, `program`, `profile`, `adapter`, `status`, `rows`, `elapsed_ms`,
438 `sql`.
439 - **`sql` is folded to one line, in every format.** Two invariants force it and one fact
440 makes it harmless: `layout.py` pads by terminal cells and has no concept of a cell that
441 spans rows, and `--format table` and `--format csv` agree cell for cell, pinned by the
442 golden-format snapshots (M1 §5) — so a column that is verbatim in JSON and folded in a
443 table is not on offer. Folding loses formatting, not meaning: `" ".join(sql.split())` is
444 still the query, and still runnable.
445 - **`--history-search TERM` is its own mode**, exactly as `--catalog-search` is its own mode
446 beside `--catalog`: same store, same columns, same `--limit`, one added `sql like '%TERM%'`.
447 M2 cut `--find` and settled on `--catalog-search`, so a caller who learned that spelling
448 guesses this one, and `_one_mode()` already refuses two modes in one invocation. It is
449 [#429](https://github.com/tconbeer/harlequin/issues/429)'s headless half, it is one clause
450 rather than a reader, and it is the flag that would have been unaffordable over a file
451 (§3.2). Unlike `--catalog-search` it declares nothing and refuses nobody: no adapter
452 capability is involved, because nothing is asked of the database.
453 - **The read is one indexed query**, `where connection = ? [and sql like ?] order by id desc
454 limit ?`. `hsql --history --limit 20` costs the same on a 100,000-row store as on a 20-row
455 one, and the reverse-scan reader an append-only file would have needed — with its truncated
456 last line, its malformed record, and its "how far back do I read for 500 matches" — does not
457 have to exist.
458 - **The columns keep their types, and that costs a duckdb import.** `create_backend()` infers
459 from the tuples: `rows` arrives `int64`, `elapsed_ms` `double`, the rest strings. So
460 `--json` emits `"rows":42,"elapsed_ms":12.5` rather than `"rows":"42"`, which is the
461 difference between a record an agent can sum and one it has to re-parse. The price is that
462 `text_columns()` no longer short-circuits on an all-string table, so the text layouts cast
463 through duckdb: **+112ms** to import it (pyarrow alone is 61.6ms; pyarrow and duckdb
464 together, 173.7ms) and 1.4ms to cast 20 rows, 1.8ms to cast 500. Worth it (Ted's call), and
465 the rendering does not change either way — duckdb prints `12.5` where `str()` would have.
466
467 These are the modes the skill teaches for B7 — an agent joining a task mid-stream reads what
468 the human has been running, or searches it for the table it cares about, in the format it
469 wants, on Windows as well as anywhere else, with no `jq` and no path to know.
470
471 ### 3.4 The History screen reads the store, and gains a filter
472
473 `History` stops being a pickled deque and becomes a query: `History.recent(connection=…,
474 n=500, search=None)`, the same `order by id desc limit ?` the two modes run. `QueryExecution` keeps
475 its `__rich__`; it just gets its rows from the store rather than from `CatalogCache`.
476
477 Three things follow, and they are the point of the milestone:
478
479 - **A crashed session keeps its history**, because the row was written when the query ran.
480 - **`hsql`'s queries appear in the human's History screen**, which is B7 — "as an agent
481 joining a task mid-stream, I read the human's recent query history" — working in both
482 directions from one store.
483 - `CatalogCache.history` is removed and `CACHE_VERSION` goes to 3. A **one-time migration**
484 runs when the old cache is present and the store holds nothing for that connection: the
485 pickled records are inserted with their own timestamps and `program = 'harlequin'`. Fifteen
486 lines, and it is also the test that proves the writer accepts historical timestamps.
487
488 **The filter is #429, and it is an `Input` over the same query.** Typing narrows the list to
489 rows whose `sql` matches, over the whole store rather than the 500 the screen holds — which is
490 the point, since the query you are hunting for is usually not in the last 500. The query runs
491 on a worker thread, debounced the way the editor debounces its symbol scan, and 35ms over
492 100,000 rows (§3.2) is what makes that feel like typing rather than waiting. Escape clears the
493 filter; Enter still inserts the highlighted query into a new buffer, as it does today.
494
495 The screen is reworked in the same release (#850, §1.2): a `ModalScreen`, so the app's
496 bindings stop reaching through it; a preview that is a highlighted, **non-focusable** surface
497 rather than a read-only editor with a cursor in it; and the screen's own bindings shown the way
498 every other screen shows them — which the filter makes more pressing rather than less, since a
499 screen with a text input in it is a screen where every stray binding is a surprise. Textual
500 8.2.8 has no `textual.highlights`, so the preview stays a `TextEditor` that cannot take focus
501 rather than becoming a `Static` — a swap to make when the version that offers it is pinned, not
502 before.
503
504 ### 3.5 "Copy CLI command", and the module both directions share
505
506 `harlequin.invocation` holds what a command line said:
507
508 ```python
509 @dataclass(frozen=True)
510 class Invocation:
511 adapter: str | None # only when it was typed
512 conn_str: tuple[str, ...]
513 profile: str | None
514 config_path: Path | None
515 read_only: bool
516 adapter_options: Mapping[str, Any] # typed, not defaulted, not from the profile
517
518 def to_hsql_argv(self, sql: str, *, limit: int | None) -> list[str]: ...
519 def to_harlequin_argv(self, open_paths: Sequence[Path]) -> list[str]: ...
520 ```
521
522 Both commands build one — `harlequin/cli.py` from its own `explicitly_set` set, `hsql/cli.py`
523 from its own — and each renders the *other* command's argv. §3.1's handoff is
524 `to_harlequin_argv()`; the TUI action is `to_hsql_argv()`. One module, two pure functions, no
525 subprocess and no widgets in the test.
526
527 The action, `copy_cli_command`, renders the queries that **would run** —
528 `_get_selected_queries()`, the same call `Ctrl+Enter` makes, so the copied command is what the
529 human is looking at — and the Run Query Bar's limit when the box is checked:
530
531 ```
532 hsql -P prod -c 'select * from orders where day = current_date' --limit 500
533 ```
534
535 Quoting is `shlex.quote` on POSIX and `subprocess.list2cmdline` on Windows. It goes through
536 `_copy_to_clipboard()`, so it also goes out over OSC 52 and works across ssh. **No format
537 flag**: `table` is the default and is what the human is looking at; an agent handed the string
538 adds `--csv` because the skill tells it to (§6.9). A secret in a typed adapter option is
539 masked rather than copied, with a notification saying so — the same rule as §3.1, for the same
540 reason, since a clipboard outlives the app too.
541
542 Shipped **unbound**: every obvious key is taken, and `harlequin --keys` plus the docs are how
543 a user picks one. The action is in the registry, so it is bindable and listed the day it
544 lands.
545
546 ### 3.6 The external editor (#1102)
547
548 The small one, and it can ship first because it needs nothing else in this milestone.
549
550 ```
551 capture the buffer -> temp file -> suspend the app -> run the editor ->
552 read the file back -> one undoable edit -> delete the temp file
553 ```
554
555 - **Resolution order: config `editor`, then `$VISUAL`, then `$EDITOR`, then refuse.** No
556 built-in fallback to `vi` or `notepad`: launching an editor the user never named is the one
557 outcome nobody asked for. The refusal names both spellings.
558 - **`$EDITOR` and `$VISUAL` need no confirmation.** The environment is the user's own shell
559 session (Ted's call, and the reason). A config-defined `editor` is a config-defined shell
560 command and goes through §3.8 like any other.
561 - **The exchange is a file, because editors do not read stdin.** A
562 `NamedTemporaryFile(suffix=".sql")` written from the active buffer, handed to the editor as
563 its last argument — the `git rebase -i` shape that #767 identified and that Posting
564 implements.
565 - **`with app.suspend():`, on the main thread.** Wrapped so `SuspendNotSupported` and `OSError`
566 become an error modal rather than a traceback, and behind
567 `harlequin.external.run_in_terminal(app, argv)` — one seam, because §1.6 measured that no
568 test can enter the real thing.
569 - **A non-zero exit discards the edit**, with a notification naming the status. That is the
570 `git commit`/`:cq` convention, and it is the only escape hatch a user has once the editor is
571 open.
572 - The result is applied by assigning `CodeEditor.text`, which in textual-textarea 0.18.1
573 checkpoints undo history and calls `replace()` over the whole document — so the round trip
574 is one `Ctrl+Z` away, and the buffer's selection and scroll are the editor's to restore.
575
576 The action is `code_editor.edit_externally`, on `CodeEditor`, and #1102's third checkbox —
577 "post-external-editor action", e.g. format or run on return — is **not** in M4 (§7): the
578 buffer is back in the editor and the existing keys already do those things.
579
580 ### 3.7 The command hook (#952)
581
582 The other shape: a **filter**, not a takeover.
583
584 ```toml
585 [commands.ai]
586 command = "claude -p 'Rewrite this SQL. Output SQL only, no code fences.'"
587 description = "Rewrite with Claude" # what --keys and the footer call it
588 stdin = "buffer" # buffer | selection | none
589 output = "replace" # replace | insert | new-buffer | none
590 timeout = 120
591 ```
592
593 - **It runs on a worker thread** — `@work(thread=True, exclusive=True, group="external_commands",
594 exit_on_error=False)` — so the app stays alive, the catalog keeps loading, and a query the
595 user already started keeps running. Nothing in it touches a widget: it posts
596 `ExternalCommandFinished(name, stdout, stderr, code)` and an `@on` handler applies the
597 result, exactly as the query workers do.
598 - **stdin in, stdout out.** The buffer (or the selection) goes in; stdout replaces the buffer
599 as one undoable edit, or is inserted at the cursor, or opens a new buffer. **Empty stdout is
600 never applied**: a model that returned nothing must not blank a human's query. Non-zero exit
601 → error modal carrying stderr, buffer untouched. stderr on a successful run → a
602 notification, because plenty of tools log there.
603 - **The context is a profile name, not a payload.** The child is handed `HARLEQUIN_PROFILE`,
604 `HARLEQUIN_ADAPTER` and `HARLEQUIN_CONN_STR` in its environment, and that is the whole of
605 the "and optionally the catalog" the product plan wanted: a hook that needs the schema runs
606 `hsql -P "$HARLEQUIN_PROFILE" --catalog` or `--catalog-search`, which is the command M2 built
607 and M3 documented, against the same profile, with the same redaction. Marshalling a catalog
608 onto stdin would be a second, worse copy of a thing this project already ships — and it
609 would pay for a walk the user may not need.
610 - **`timeout` bounds it** (default 120s): `terminate()`, two seconds of grace, `kill()`. While
611 a hook is running the Cancel Query binding stops it too — to a user, "stop" is one idea, and
612 a second cancel key for a second kind of work is a worse answer than one key that stops
613 whatever is running.
614 - **No `shell = true`.** A pipeline goes in a script and the script goes in `command`; a shell
615 string would mean two quoting rules (POSIX and `cmd.exe`) for a feature whose whole value is
616 running something the user already has. `command` takes a list, or a string that `shlex`
617 splits.
618 - **`hsql` runs no hooks, ever.** A headless command that executes shell commands out of a
619 config file it found in `$CWD` is a supply-chain hazard in CI. `hsql` reads the table for
620 `--config validate` and ignores it otherwise.
621
622 ### 3.8 Trust: what a config file may make Harlequin execute
623
624 Two rules, and neither is a preference the config file can set for itself.
625
626 **Rule 1 — provenance.** `[commands]` and a top-level `editor` are honored only from a config
627 file the user named or keeps: an explicit `--config-path`, the user config dir, or home. A
628 definition found in `./.harlequin.toml` or `./pyproject.toml` is **ignored**, with one
629 notification naming the file and the key. Merging already tracks which file supplied each key
630 (`Provenance`, M2 §3.6), so this is a check at the point of use, not a second pass.
631
632 **Rule 2 — consent, per definition.** Before a command runs for the first time, a modal shows
633 the exact argv, the config file it came from, and three choices — Run once / Always allow /
634 Cancel — with **Cancel focused**. "Always allow" appends a record to
635 `<user_state_dir>/harlequin/trusted_commands.json`:
636
637 ```json
638 {"name":"ai","source":"/home/ted/.config/harlequin/config.toml",
639 "command":"claude -p 'Rewrite this SQL…'","fingerprint":"sha256:…","trusted_at":"2026-09-02T…"}
640 ```
641
642 The fingerprint covers the name, the resolved argv and the source path, so **editing the
643 command re-prompts**. The store is in state, not in config, deliberately: a synced config file
644 that could carry its own approval would defeat the gate it is supposed to pass. The plaintext
645 command sits beside the hash so the file can be audited by the person it protects, and revoking
646 is deleting a line.
647
648 **What is not gated:** `$EDITOR`/`$VISUAL` (§3.6), and `hsql --open` launching `harlequin`
649 (a known entry point in the same interpreter, not a user string).
650
651 **What is never automatic:** a hook runs only from a key the user pressed. No hook on start-up,
652 on connect, on error, or on quit — that is how a config-defined command becomes a startup
653 payload, and there is no version of it M4 wants.
654
655 ### 3.9 Actions can come from config, so the registry becomes a function
656
657 `HARLEQUIN_ACTIONS` stays as the static base; `build_actions(command_names)` returns it plus
658 one `command.<name>` entry per configured hook, targeting `CodeEditor` with
659 `run_command('<name>')` and the hook's `description`. `app.py`, `keys_app.py` and the keymap
660 loader all take the built registry — `keys_app` already loads config to find keymaps, so it
661 can list a user's own commands in the binding editor beside the built-in actions.
662
663 And the crash in §1.5 gets fixed on the way, because it is now reachable by typo *and* by a
664 command that was renamed: an unknown action name is **skipped with one notification naming the
665 keymap and the action**, not a `KeyError` in mount. A keymap with one bad line should cost the
666 user that line, not the application.
667
668 ---
669
670 ## 4. Sequencing
671
672 Three releases, and **the editor and the hooks go first** (Ted's call). Nothing in this
673 milestone depends on anything else in it — that is what makes the order a choice rather than a
674 constraint — so the order is by what users are waiting for and by how much design risk each
675 group carries. [#1102](https://github.com/tconbeer/harlequin/issues/1102) is open, has a
676 reference implementation, and needs nothing else here; the trust model under it is the most
677 consequential decision in M4 and benefits from being in the world early rather than shipping
678 last with two other features on top of it. The query history follows, because it changes a
679 stored format and a screen, because it is what makes an agent's queries visible to a human at
680 all, and because search ([#429](https://github.com/tconbeer/harlequin/issues/429)) is what
681 decides the format it changes to. The handoff is last: it is the largest new public surface —
682 two flags across two commands — and it lands better after the history, since a draft handed to
683 a human and the queries they run against it are then one story rather than two.
684
685 Each release maps to a run of §3: A is §3.6–§3.9, B is §3.2–§3.4, C is §3.1 and §3.5.
686
687 Numbering assumes M3's remaining work releases as 2.13.
688
689 ### Release A — the editor and the hooks (2.13)
690
691 **PR 1 — The external editor.** `$EDITOR`/`$VISUAL` only, `harlequin.external.run_in_terminal()`,
692 the suspend wrapper and its unsupported-environment path, temp-file exchange, non-zero-exit
693 discard, and the `code_editor.edit_externally` action. No config key and no trust store yet, so
694 it is reviewable on its own. Closes
695 [#1102](https://github.com/tconbeer/harlequin/issues/1102) for the request as filed.
696
697 **PR 2 — The trust gate.** Provenance rule, consent modal, trust store, and the config
698 `editor` key as its first consumer. The gate ships with something small enough to review it
699 against, and a release before anything larger runs through it.
700
701 **PR 3 — `[commands]` in config, and actions from config.** The `Config` member, the schema
702 regeneration (`scripts/write_config_schema.py`, and the pinned artifact), `build_actions()`,
703 the keymap-validation fix from §1.5, and `--config validate`'s coverage of the new table.
704 Nothing executes yet; the keys bind to an action that reports "not implemented" in exactly one
705 commit, or PR 3 and PR 4 land together if that reads badly in review.
706
707 **PR 4 — Running a hook.** The worker, stdin/stdout, the four `output` modes, the empty-output
708 rule, timeout and cancel, error surfacing. Answers
709 [#952](https://github.com/tconbeer/harlequin/issues/952).
710
711 **PR 5 — Docs** (`harlequin-web`): "External editor" and "Bring your own AI" pages, the trust
712 model stated plainly, and a worked `claude -p` config with the prompt that keeps code fences
713 out of the buffer.
714
715 ### Release B — query history, and search (2.14)
716
717 **PR 6 — `harlequin.query_log`.** The schema, the pragmas, `user_version` and its migration
718 step, the writer, retention, `get_connection_hash()`'s move out of `catalog_cache`,
719 `--no-write-history`, and both commands writing. The IDE starts calling `hide_secrets_in()`
720 here — the store is the first thing it persists that could carry a value from a profile
721 (§1.4). Guards: `hsql`'s import set still contains no rich, and `hsql --version` is still
722 ~120ms.
723
724 **PR 7 — `hsql --history` and `--history-search`.** Both modes, the connection filter, the
725 folded `sql` column, `--limit` as "the most recent N", and the search clause. Nothing new in
726 the output layer — the listing goes through the emitters `--catalog` already uses. Adds both
727 modes to the skill. Closes B7's headless half and #429's.
728
729 **PR 8 — The History screen reads the store.** `History.recent()`, `CatalogCache.history`
730 removed, `CACHE_VERSION` to 3, and the one-time migration. This is the PR where an agent's
731 queries first show up in a human's History screen, and where the human's show up under
732 `--history`.
733
734 **PR 9 — The History screen, reconsidered.** The filter input over the whole store, plus
735 modal, a non-focusable preview, and the screen's own bindings shown as every other screen
736 shows them (§1.2, §3.4). Search and the rework land together because they are the same
737 screen and the same reading of it: the pane is for choosing a query, not for editing one.
738 Closes [#429](https://github.com/tconbeer/harlequin/issues/429) and
739 [#850](https://github.com/tconbeer/harlequin/issues/850).
740
741 **PR 10 — Docs** (`harlequin-web`): the query history — where it lives, what it holds, how to
742 search it from either front end, and that it is a SQLite file the reader can open in Harlequin
743 itself — and `--history` in "Headless & Agents".
744
745 ### Release C — the handoff (2.15)
746
747 **PR 11 — `harlequin.invocation`, and `harlequin --open`.** The dataclass, both argv renderers,
748 and the IDE flag that loads files into buffers without executing them. `cli.py` builds an
749 `Invocation` and hands it to the app. Closes the half of F1 the IDE owns, and is useful on its
750 own (`harlequin --open report.sql`).
751
752 **PR 12 — `hsql --open`.** The mode option, the secret refusal, the scratch file and its
753 pruning, the exec/subprocess split, and the `/dev/tty` reattach. Rewrites the skill's section
754 9 (`hsql --skill` ships from the wheel, so this is the same PR). Closes F1.
755
756 **PR 13 — Copy CLI command.** The action, the quoting, the masking, the registry entry. Closes
757 F2.
758
759 **PR 14 — Docs** (`harlequin-web`): the handoff section in "Headless & Agents", and `--open` on
760 both command pages.
761
762 **Ordering rationale.** Within a release, unchanged from M1 and M2: a contract or a gate lands
763 with the first consumer that needs it, and nothing declares a thing nothing reads. Across
764 releases, the three groups are independent, so the order is a product decision rather than a
765 technical one — which also means it can change again without rewriting §3.
766
767 ---
768
769 ## 5. Testing
770
771 **Unit, and most of the milestone is unit-testable.**
772
773 - `Invocation.to_hsql_argv()` / `to_harlequin_argv()`: profile vs conn_str, typed vs defaulted
774 options, the secret refusal, and quoting on both platforms (parametrized over
775 `shlex.quote`/`list2cmdline` rather than skipped on one).
776 - `query_log`: row round trip; the schema migration, from `user_version = 0` forward and on a
777 store already at the current version; retention trimming to the newest N; `redact_text()`
778 applied to `sql`; an unwritable directory and an unreadable store each disabling logging
779 without raising; and the WAL fallback, exercised by a store where `journal_mode=wal` does
780 not stick.
781 - The **concurrent write** measurement becomes a real test — 4 processes × 100 inserts,
782 asserting every row lands and no `sqlite3.Error` escapes — marked so it can be deselected on
783 a slow runner.
784 - The pickle migration, including timestamps that predate the store, and a second run that
785 does not double-insert.
786 - `--history`: the connection filter with two connections interleaved; `--limit` taking from
787 the newest end; `--history-search` matching mid-string, and its case behavior pinned where
788 SQLite's `like` would otherwise surprise us; the folded `sql` column matching between
789 `--format table` and `--format csv`, asserted the way the golden-format snapshots assert it
790 rather than against a copy of the folding rule; `--json` emitting `rows` and `elapsed_ms`
791 unquoted, and null for a statement that has neither; and an empty store printing a header
792 and no rows rather than nothing.
793 - A guard that `--history` opens no connection: the mode runs against a profile whose adapter
794 would raise on `connect()`, and still prints rows.
795 - Trust: fingerprint stability across a whitespace change (it should change — the argv is what
796 runs), and the provenance rule (a `[commands]` table in `./pyproject.toml` is ignored; the
797 same table under `--config-path` is not).
798 - `build_actions()`: a command name that collides with a built-in action, and a keymap naming
799 an action nothing defines.
800
801 **Functional (pilot + snapshot).**
802
803 - `harlequin --open a.sql b.sql`: two new buffers, the second active, **nothing executed** —
804 assert on the absence of a `QuerySubmitted`, not only on the snapshot.
805 - The copy action: assert the string, through the editor's clipboard rather than the system's.
806 - The hook worker against a **hermetic child** — `[sys.executable, "-c", …]`, never an external
807 binary — covering success, empty stdout, non-zero exit with stderr, and a timeout that kills
808 a child that ignores `terminate()`.
809 - The consent modal: cancel leaves the buffer alone and runs nothing; "always allow" writes one
810 record and the second invocation does not prompt.
811 - The History screen after #850 and #429: an app-level binding pressed on the screen does
812 nothing, Tab does not land focus in the preview, and typing in the filter narrows the list
813 to rows the 500-record window would not have held — all asserted on behavior, not on the
814 snapshot, since the snapshot changes for reasons none of them cares about.
815 - The editor round trip with `run_in_terminal` patched, plus the `SuspendNotSupported` path
816 asserted as a notification — §1.6 measured that the real suspend cannot be reached in
817 `run_test()`, so the seam is the test surface.
818
819 **Import hygiene.** `harlequin.invocation` and `harlequin.query_log` join `HEADLESS_IMPORTS`.
820 A run that logs must not import rich: that is the assertion that keeps §1.3's finding from
821 coming back as a 46ms regression on every `hsql -c`.
822
823 **Not tested, and said out loud:** no test runs a real editor or a real model; nothing asserts
824 on `/dev/tty` reattachment (CI has no controlling terminal) — the decision function is tested,
825 the two `dup2` calls are not.
826
827 ---
828
829 ## 6. Decisions
830
831 ### 6.1 The external editor and the AI hook are two features
832
833 The product plan folds them together — "same shape as the existing external-editor request" —
834 and the shape is where they differ:
835
836 | | External editor | Command hook |
837 | --- | --- | --- |
838 | The terminal | needs it; the app suspends | must not have it; the app stays live |
839 | Thread | main, blocking (suspend redirects the process's streams) | worker |
840 | Exchange | a temp file, edited in place | stdin → stdout |
841 | Duration | as long as the human takes | seconds, and needs a bound |
842 | Cancel | quitting the editor | a timeout, and a key |
843 | Failure | non-zero exit means "discard" | non-zero exit is an error to show |
844 | Config | one key; `$EDITOR` is usually all of it | a named command with a prompt, per task |
845 | Trust | the environment is the user | a file is not |
846 | Privacy | the query stays on the machine | the query may leave it |
847
848 What they share is four lines: build an argv, start a process, read a result, apply it as one
849 undoable edit. Unifying them means a single config table with an `interactive` switch, a
850 `{file}` placeholder whose presence silently changes the exchange, and a validity table where
851 most combinations are refused — a worse config than two tables, to save four lines. They also
852 close two different issues, for two different users, and the editor ships first because it
853 needs no trust store at all — `$EDITOR` is the user's own environment (§6.8).
854
855 ### 6.2 `hsql --open`, not `hsql open`
856
857 M2's rule, unchanged: `CONN_STR` is positional, so a subcommand named `open` would need a rule
858 to distinguish it from a DuckDB file named `open`. `--open` needs none, and it composes with
859 `-c`, `-f` and stdin, which a subcommand taking its own path argument would have duplicated.
860
861 ### 6.3 The handoff execs; it does not import, and it does not write the buffer cache
862
863 Measured in §1.1: the cache is Textual (+164ms and 341 modules) and is rewritten whole at
864 quit, so a second writer races the IDE. An in-process import of `harlequin.cli` would break
865 the one contract `hsql` is defined by. `python -m harlequin` in the same interpreter is the
866 only option that is both correct and cheap, and it is cheap only relative to what it launches
867 — a 620ms `harlequin --version` is the floor for anything that opens the IDE.
868
869 ### 6.4 One SQLite store, not JSONL, and not one file per connection
870
871 The roadmap says "JSONL history," and this plan said so too until #429 came into scope. The
872 reversal is in §3.2 and rests on one number: searching 100,000 records is 396ms as a file scan
873 and 35ms as a `like`. Everything else was close enough to be a preference — writes 14µs apart,
874 `sqlite3` importing cheaper than `json`, files within 15% in size, tail reads a wash — and
875 search is not close.
876
877 Three second-order effects, all in the same direction. **The reader stops existing**: no
878 reverse-scan-by-chunks, no truncated last line, no "read further back until 500 match" — one
879 indexed query instead, and a whole class of §5 tests with it. **A schema change becomes an
880 `alter table`**, where the pickle caches bump a version and discard, which is the wrong
881 behavior for the one store whose contents cannot be re-fetched. And **the file is a database
882 Harlequin can open**: `harlequin -a sqlite ~/.local/state/harlequin/history.db` is a better
883 answer to "readable with ordinary tools" than `jq` was, on every platform.
884
885 What is given up is `tail -f`, and `hsql --history --jsonl` gives back the format if not the
886 follow. Still one store rather than one per connection, for the reason it always was: an agent
887 asking what has been run against a warehouse should not have to know a connection hash to find
888 a file, and ordering across databases is a `order by`, not a merge.
889
890 ### 6.5 `--history` is a mode, and the store's path is not in `--info`
891
892 When the store was a JSONL file, the tempting cut was to ship it and let `tail` and `jq` be
893 the reader. It is a mode (Ted's call), and three things say so — the first two of which
894 outlived the format, and the third of which is why a SQLite store needs one even more.
895
896 **A mode is nearly free, because a listing is a result set.** M2 §3.3 built that road for
897 `--catalog`: hand the emitters a `ResultSet` and every format, every layout flag and `-o`
898 follow. `--history` is a reader plus a table; it is not a second output stack.
899
900 **The pipeline is not portable and not self-describing.** It needed `jq`, a path, a filter by
901 connection, and a shell that has `tail` — which Windows does not. "Read the human's recent
902 queries" is a thing the skill should be able to teach in one line that works everywhere. With
903 a SQLite store the pipeline would need `sqlite3` and a schema besides, so the mode carries
904 more weight now, not less.
905
906 **And `--info` is the wrong place for the path.** `--info` reports on the installation —
907 versions, platform, config files, adapter capabilities. A pointer into the user's own query
908 history is a different kind of fact, and putting it there invites a reader to go parse the file
909 by hand when a mode can hand them rows. The path stays in the docs, where a person who wants to
910 back the file up or delete it will look.
911
912 ### 6.6 The hook's context is a profile name, not a catalog
913
914 Harlequin already ships the best catalog-for-agents interface it has (`--catalog`,
915 `--catalog-search`, `--info`), documented in M3 and taught by the skill. A hook that gets
916 `HARLEQUIN_PROFILE` can call it; a hook that gets 40 KB of marshalled catalog on stdin pays
917 for a walk it may not need and gets a second, worse format for the same data.
918
919 ### 6.7 The trust store is not the config file
920
921 If "always allow" wrote back into the config, a synced config could ship its own approval and
922 the gate would protect nothing. State dir, fingerprinted by argv and source, plaintext beside
923 the hash so the person it protects can audit it.
924
925 ### 6.8 `$EDITOR` is trusted; a config file is not
926
927 Ted's call, and the line generalizes: the environment is the user's own session, and a config
928 file is a document that arrives from a directory (`$CWD`) or a sync (dotfiles) that the user
929 may not have read. That is also why the provenance rule (§3.8) is separate from the consent
930 prompt — one keeps a stranger's file from ever asking, the other keeps the user's own file
931 honest.
932
933 ### 6.9 The copied command carries no `--csv`
934
935 The product plan's example is `hsql -P prod -c '…' --csv`. The human copying it is looking at
936 a table, and the agent receiving it knows from the skill to pick a format on purpose (§5 of
937 `SKILL.md`). A format flag in the copied string is a guess about the recipient; the profile,
938 the connection and the SQL are not.
939
940 ---
941
942 ## 7. Explicitly not in M4
943
944 - **`hsql mcp`** — M6, unchanged.
945 - **Streaming, `--offset`, and the memory work in #875** — M5.
946 - **A post-editor action** (#1102's third checkbox: format or run on return). The buffer is
947 back in the editor and `code_editor.format` and `code_editor.run_query` are already bound.
948 - **Hooks anywhere but the Query Editor.** A hook over a *result set* — "explain this table" —
949 is a real idea and a different feature: it needs a serialization of the result, a size
950 policy, and an answer for where the output goes.
951 - **Code-fence stripping on hook output.** The prompt is the config author's, and the docs give
952 one that works. A heuristic here would be Harlequin guessing at model output.
953 - **`shell = true`, and placeholders beyond none.** §3.7.
954 - **Action-name validation in `hsql --config validate`.** It would be genuinely useful — an
955 agent editing a keymap would learn about a typo without starting a TUI — but the registry
956 lives in `harlequin.actions`, which imports `harlequin.components` and therefore Textual.
957 Doing it properly means splitting the *names* into a leaf module and leaving the widget
958 targets behind, which is a refactor to make on purpose, with the second consumer in hand.
959 - **A `--open` that starts a query running.** It would collapse the review step F1 exists for.
960 - **`--history --since 2h`.** Obvious the moment the mode exists, and one more `where` clause
961 once the store is a database — but `--limit` and newest-first cover the case this milestone
962 is for. Worth doing next, not now.
963 - **FTS5 over the history.** `like` is 35ms over 100,000 rows (§3.2), an FTS table is a second
964 thing to keep in step with the first, tokenizing SQL is a poor fit for a tokenizer built for
965 prose, and FTS5 is a compile-time option that is *usually* present. Revisit at a million
966 rows, with a measurement rather than an instinct.
967 - **Anything else in the history store.** The catalog and buffer caches are still pickles, and
968 the database that now exists is an obvious home for them. It is also a separate change, with
969 a separate migration and a separate failure mode, and this milestone has enough of both.
970 - **Per-hook cancel keys, hook chaining, and hooks that write config.** Each is a feature
971 request that will read as obvious once one hook works, and none of them is M4's.
972
973 ---
974
975 ## 8. Corrections to the product plan
976
977 Recorded here; applied to `harlequin-for-agents.md` in the same PR as this document.
978
979 - **§11's M4 row still lists the skill**, which shipped in M3 (`hsql --skill`, the packaged
980 `SKILL.md`, and the marketplace entry). The row is `hsql --open`, the query log, "Copy CLI
981 command", the external editor, and command hooks.
982 - **§10's `hsql open query.sql` is a subcommand, and M2 settled on mode options.** The spelling
983 is `hsql --open`, reading its SQL from `-c`, `-f` or stdin like every other run (§6.2).
984 - **§10's "buffers already persist through `editor_cache.py`, so the machinery is close at
985 hand" is measurably wrong in the direction that matters.** That cache imports Textual and is
986 rewritten whole at quit; it is the one mechanism the handoff cannot use (§1.1).
987 - **§10 treats the external editor and the AI hook as one feature.** They differ in the
988 terminal, the thread, the exchange, the failure mode and the trust model, and #1102 now
989 exists as its own issue with its own reference implementation (§6.1).
990 - **§10 does not mention consent, and a config-defined shell command needs it.** Config files
991 merge from `$CWD`, so a cloned repository can define one; a synced dotfiles repo can do the
992 same in the user's own config dir. §3.8 is the missing paragraph.
993 - **The roadmap's "JSONL history" names a format that search rules out.** M4 stores query
994 history in SQLite and *emits* JSON Lines: `hsql --history --jsonl` is the record the roadmap
995 described, and the store behind it is what makes #429 affordable (§3.2, §6.4).
996 - **§6's `hsql history --json -n 20` is the right feature under two wrong assumptions.** The
997 spelling is `hsql --history --json --limit 20` — a mode option, and `--limit` rather than a
998 new `-n`, because both commands already mean "the rows that leave the store" by it. And what
999 it reads is not the pickle §6 proposes to "expose": that one is written once, at quit, behind
1000 a module headless code may not import (§1.2, §1.3). The log is the store; the mode is the
1001 reader (§3.3).
1002 - **§12's risk list says query history "sits outside that mechanism" and needs its own
1003 handling.** It needs one line of handling: `redact_text()` on the way into the log, plus the
1004 `hide_secrets_in()` call the IDE has never made (§1.4, §3.2).
1005 - **§9's skill section 9 is rewritten by this milestone**, as M3 §7 predicted: the handoff
1006 advice becomes `hsql --open -f draft.sql -P prod` rather than "tell them to run `harlequin`".
1007 - **#952 is closed as `not planned`**, with "I won't be adding this to Harlequin. But shortly I
1008 am releasing `hsql`." §10's "#952 answered without embedding an LLM" is still the right
1009 answer; the changelog entry should reference #952 for the hook and #1102 for the editor,
1010 and #952 can be reopened or left closed with a comment pointing at the hook.
1011 - **§13's success criteria should gain one line**: a query run by `hsql` appears in the human's
1012 History screen, and a draft written by an agent opens in the human's editor without being
1013 run. That is what Workstream F is for, and neither is measurable today.