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 a profile key, `history = false`, read by both commands. Nothing else reports
388 the store's path: `--info` describes the installation, not the user's data, and the mode below
389 is how a caller reads the rows without needing to know where they are.
390
391 **JSON Lines does not go away; it stops being the storage.** `hsql --history --jsonl` emits
392 exactly the record above, one object per line, because the mode is a result set and every
393 format already works on it (§3.3) — so the "readable with ordinary tools" property the product
394 plan asked for now works on Windows and needs no `jq`. And the store is a SQLite file, so the
395 other ordinary tool is Harlequin: `harlequin -a sqlite ~/.local/state/harlequin/history.db`
396 opens your own query history in the IDE, with a catalog and a results viewer around it.
397
398 ### 3.3 `hsql --history` and `--history-search`, the modes that read the store
399
400 Two mode options, shaped like the two M2 built — `--catalog` lists, `--catalog-search` finds —
401 and they cost almost nothing to build, because the whole output layer is already written and
402 **these two are not listings at all: they are queries.** `--catalog` has to synthesize a result
403 set, since what it is reporting on is a walk over catalog objects, and that is what
404 `query.rows_to_result()` exists for. `--history` is running SQL against a SQLite database, so
405 its rows go where a cursor's rows go: `create_backend(rows, column_names=COLUMNS)`, the same
406 call `query.fetch()` makes for every query and the same one `harlequin_sqlite` makes with its
407 own `fetchall()`. What comes back is the `ResultSet` the query path builds, so `--format
408 json`, `--jsonl`, `--csv`, `-x`, `-o PATH`, `--stats` and the layout flags all work on it the
409 day it lands, and none of them is a line of new code.
410
411 Through stdlib `sqlite3`, not through the SQLite adapter: `-P prod` names the adapter whose
412 `connection_id` filters the store, and loading a second adapter plug-in to read a file this
413 module already owns would be a strange way to answer a question about `postgres`.
414
415 ```bash
416 hsql --history --limit 20 # the last 20, as a table
417 hsql --history -P prod --json # this profile's, for an agent
418 hsql --history-search "line_items" # every query that mentions it, newest first
419 hsql --history -x --limit 1 # the last one, vertically
420 ```
421
422 - **The only database they open is the store.** They are the only modes that read a profile
423 and build an adapter without ever connecting with it: the adapter is constructed solely to
424 ask it for `connection_id`, which is what filters the store to one database. A history mode
425 that woke a warehouse to list queries would be its own kind of joke.
426 - **Scope follows the invocation.** `-P`, `-a` or a `CONN_STR` narrows to that connection;
427 with none of them, the mode reports every connection, because "I typed `hsql --history` and
428 got someone else's idea of the default database" is the surprising answer. The `profile` and
429 `adapter` columns are what tell them apart.
430 - **Newest first**, which is what every shell means by history, and what makes `--limit` mean
431 "the most recent N" rather than "the oldest N". `--limit` is honored here rather than refused
432 as it is under `--catalog`: the store has a row count, so a hard limit on it is exact.
433 Default 500 — the size of the deque the History screen has always kept — and `-1` for all.
434 - **Columns:** `run_at`, `program`, `profile`, `adapter`, `status`, `rows`, `elapsed_ms`,
435 `sql`.
436 - **`sql` is folded to one line, in every format.** Two invariants force it and one fact
437 makes it harmless: `layout.py` pads by terminal cells and has no concept of a cell that
438 spans rows, and `--format table` and `--format csv` agree cell for cell, pinned by the
439 golden-format snapshots (M1 §5) — so a column that is verbatim in JSON and folded in a
440 table is not on offer. Folding loses formatting, not meaning: `" ".join(sql.split())` is
441 still the query, and still runnable.
442 - **`--history-search TERM` is its own mode**, exactly as `--catalog-search` is its own mode
443 beside `--catalog`: same store, same columns, same `--limit`, one added `sql like '%TERM%'`.
444 M2 cut `--find` and settled on `--catalog-search`, so a caller who learned that spelling
445 guesses this one, and `_one_mode()` already refuses two modes in one invocation. It is
446 [#429](https://github.com/tconbeer/harlequin/issues/429)'s headless half, it is one clause
447 rather than a reader, and it is the flag that would have been unaffordable over a file
448 (§3.2). Unlike `--catalog-search` it declares nothing and refuses nobody: no adapter
449 capability is involved, because nothing is asked of the database.
450 - **The read is one indexed query**, `where connection = ? [and sql like ?] order by id desc
451 limit ?`. `hsql --history --limit 20` costs the same on a 100,000-row store as on a 20-row
452 one, and the reverse-scan reader an append-only file would have needed — with its truncated
453 last line, its malformed record, and its "how far back do I read for 500 matches" — does not
454 have to exist.
455 - **The columns keep their types, and that costs a duckdb import.** `create_backend()` infers
456 from the tuples: `rows` arrives `int64`, `elapsed_ms` `double`, the rest strings. So
457 `--json` emits `"rows":42,"elapsed_ms":12.5` rather than `"rows":"42"`, which is the
458 difference between a record an agent can sum and one it has to re-parse. The price is that
459 `text_columns()` no longer short-circuits on an all-string table, so the text layouts cast
460 through duckdb: **+112ms** to import it (pyarrow alone is 61.6ms; pyarrow and duckdb
461 together, 173.7ms) and 1.4ms to cast 20 rows, 1.8ms to cast 500. Worth it (Ted's call), and
462 the rendering does not change either way — duckdb prints `12.5` where `str()` would have.
463
464 These are the modes the skill teaches for B7 — an agent joining a task mid-stream reads what
465 the human has been running, or searches it for the table it cares about, in the format it
466 wants, on Windows as well as anywhere else, with no `jq` and no path to know.
467
468 ### 3.4 The History screen reads the store, and gains a filter
469
470 `History` stops being a pickled deque and becomes a query: `History.recent(connection=…,
471 n=500, search=None)`, the same `order by id desc limit ?` the two modes run. `QueryExecution` keeps
472 its `__rich__`; it just gets its rows from the store rather than from `CatalogCache`.
473
474 Three things follow, and they are the point of the milestone:
475
476 - **A crashed session keeps its history**, because the row was written when the query ran.
477 - **`hsql`'s queries appear in the human's History screen**, which is B7 — "as an agent
478 joining a task mid-stream, I read the human's recent query history" — working in both
479 directions from one store.
480 - `CatalogCache.history` is removed and `CACHE_VERSION` goes to 3. A **one-time migration**
481 runs when the old cache is present and the store holds nothing for that connection: the
482 pickled records are inserted with their own timestamps and `program = 'harlequin'`. Fifteen
483 lines, and it is also the test that proves the writer accepts historical timestamps.
484
485 **The filter is #429, and it is an `Input` over the same query.** Typing narrows the list to
486 rows whose `sql` matches, over the whole store rather than the 500 the screen holds — which is
487 the point, since the query you are hunting for is usually not in the last 500. The query runs
488 on a worker thread, debounced the way the editor debounces its symbol scan, and 35ms over
489 100,000 rows (§3.2) is what makes that feel like typing rather than waiting. Escape clears the
490 filter; Enter still inserts the highlighted query into a new buffer, as it does today.
491
492 The screen is reworked in the same release (#850, §1.2): a `ModalScreen`, so the app's
493 bindings stop reaching through it; a preview that is a highlighted, **non-focusable** surface
494 rather than a read-only editor with a cursor in it; and the screen's own bindings shown the way
495 every other screen shows them — which the filter makes more pressing rather than less, since a
496 screen with a text input in it is a screen where every stray binding is a surprise. Textual
497 8.2.8 has no `textual.highlights`, so the preview stays a `TextEditor` that cannot take focus
498 rather than becoming a `Static` — a swap to make when the version that offers it is pinned, not
499 before.
500
501 ### 3.5 "Copy CLI command", and the module both directions share
502
503 `harlequin.invocation` holds what a command line said:
504
505 ```python
506 @dataclass(frozen=True)
507 class Invocation:
508 adapter: str | None # only when it was typed
509 conn_str: tuple[str, ...]
510 profile: str | None
511 config_path: Path | None
512 read_only: bool
513 adapter_options: Mapping[str, Any] # typed, not defaulted, not from the profile
514
515 def to_hsql_argv(self, sql: str, *, limit: int | None) -> list[str]: ...
516 def to_harlequin_argv(self, open_paths: Sequence[Path]) -> list[str]: ...
517 ```
518
519 Both commands build one — `harlequin/cli.py` from its own `explicitly_set` set, `hsql/cli.py`
520 from its own — and each renders the *other* command's argv. §3.1's handoff is
521 `to_harlequin_argv()`; the TUI action is `to_hsql_argv()`. One module, two pure functions, no
522 subprocess and no widgets in the test.
523
524 The action, `copy_cli_command`, renders the queries that **would run** —
525 `_get_selected_queries()`, the same call `Ctrl+Enter` makes, so the copied command is what the
526 human is looking at — and the Run Query Bar's limit when the box is checked:
527
528 ```
529 hsql -P prod -c 'select * from orders where day = current_date' --limit 500
530 ```
531
532 Quoting is `shlex.quote` on POSIX and `subprocess.list2cmdline` on Windows. It goes through
533 `_copy_to_clipboard()`, so it also goes out over OSC 52 and works across ssh. **No format
534 flag**: `table` is the default and is what the human is looking at; an agent handed the string
535 adds `--csv` because the skill tells it to (§6.9). A secret in a typed adapter option is
536 masked rather than copied, with a notification saying so — the same rule as §3.1, for the same
537 reason, since a clipboard outlives the app too.
538
539 Shipped **unbound**: every obvious key is taken, and `harlequin --keys` plus the docs are how
540 a user picks one. The action is in the registry, so it is bindable and listed the day it
541 lands.
542
543 ### 3.6 The external editor (#1102)
544
545 The small one, and it can ship first because it needs nothing else in this milestone.
546
547 ```
548 capture the buffer -> temp file -> suspend the app -> run the editor ->
549 read the file back -> one undoable edit -> delete the temp file
550 ```
551
552 - **Resolution order: config `editor`, then `$VISUAL`, then `$EDITOR`, then refuse.** No
553 built-in fallback to `vi` or `notepad`: launching an editor the user never named is the one
554 outcome nobody asked for. The refusal names both spellings.
555 - **`$EDITOR` and `$VISUAL` need no confirmation.** The environment is the user's own shell
556 session (Ted's call, and the reason). A config-defined `editor` is a config-defined shell
557 command and goes through §3.8 like any other.
558 - **The exchange is a file, because editors do not read stdin.** A
559 `NamedTemporaryFile(suffix=".sql")` written from the active buffer, handed to the editor as
560 its last argument — the `git rebase -i` shape that #767 identified and that Posting
561 implements.
562 - **`with app.suspend():`, on the main thread.** Wrapped so `SuspendNotSupported` and `OSError`
563 become an error modal rather than a traceback, and behind
564 `harlequin.external.run_in_terminal(app, argv)` — one seam, because §1.6 measured that no
565 test can enter the real thing.
566 - **A non-zero exit discards the edit**, with a notification naming the status. That is the
567 `git commit`/`:cq` convention, and it is the only escape hatch a user has once the editor is
568 open.
569 - The result is applied by assigning `CodeEditor.text`, which in textual-textarea 0.18.1
570 checkpoints undo history and calls `replace()` over the whole document — so the round trip
571 is one `Ctrl+Z` away, and the buffer's selection and scroll are the editor's to restore.
572
573 The action is `code_editor.edit_externally`, on `CodeEditor`, and #1102's third checkbox —
574 "post-external-editor action", e.g. format or run on return — is **not** in M4 (§7): the
575 buffer is back in the editor and the existing keys already do those things.
576
577 ### 3.7 The command hook (#952)
578
579 The other shape: a **filter**, not a takeover.
580
581 ```toml
582 [commands.ai]
583 command = "claude -p 'Rewrite this SQL. Output SQL only, no code fences.'"
584 description = "Rewrite with Claude" # what --keys and the footer call it
585 stdin = "buffer" # buffer | selection | none
586 output = "replace" # replace | insert | new-buffer | none
587 timeout = 120
588 ```
589
590 - **It runs on a worker thread** — `@work(thread=True, exclusive=True, group="external_commands",
591 exit_on_error=False)` — so the app stays alive, the catalog keeps loading, and a query the
592 user already started keeps running. Nothing in it touches a widget: it posts
593 `ExternalCommandFinished(name, stdout, stderr, code)` and an `@on` handler applies the
594 result, exactly as the query workers do.
595 - **stdin in, stdout out.** The buffer (or the selection) goes in; stdout replaces the buffer
596 as one undoable edit, or is inserted at the cursor, or opens a new buffer. **Empty stdout is
597 never applied**: a model that returned nothing must not blank a human's query. Non-zero exit
598 → error modal carrying stderr, buffer untouched. stderr on a successful run → a
599 notification, because plenty of tools log there.
600 - **The context is a profile name, not a payload.** The child is handed `HARLEQUIN_PROFILE`,
601 `HARLEQUIN_ADAPTER` and `HARLEQUIN_CONN_STR` in its environment, and that is the whole of
602 the "and optionally the catalog" the product plan wanted: a hook that needs the schema runs
603 `hsql -P "$HARLEQUIN_PROFILE" --catalog` or `--catalog-search`, which is the command M2 built
604 and M3 documented, against the same profile, with the same redaction. Marshalling a catalog
605 onto stdin would be a second, worse copy of a thing this project already ships — and it
606 would pay for a walk the user may not need.
607 - **`timeout` bounds it** (default 120s): `terminate()`, two seconds of grace, `kill()`. While
608 a hook is running the Cancel Query binding stops it too — to a user, "stop" is one idea, and
609 a second cancel key for a second kind of work is a worse answer than one key that stops
610 whatever is running.
611 - **No `shell = true`.** A pipeline goes in a script and the script goes in `command`; a shell
612 string would mean two quoting rules (POSIX and `cmd.exe`) for a feature whose whole value is
613 running something the user already has. `command` takes a list, or a string that `shlex`
614 splits.
615 - **`hsql` runs no hooks, ever.** A headless command that executes shell commands out of a
616 config file it found in `$CWD` is a supply-chain hazard in CI. `hsql` reads the table for
617 `--config validate` and ignores it otherwise.
618
619 ### 3.8 Trust: what a config file may make Harlequin execute
620
621 Two rules, and neither is a preference the config file can set for itself.
622
623 **Rule 1 — provenance.** `[commands]` and a top-level `editor` are honored only from a config
624 file the user named or keeps: an explicit `--config-path`, the user config dir, or home. A
625 definition found in `./.harlequin.toml` or `./pyproject.toml` is **ignored**, with one
626 notification naming the file and the key. Merging already tracks which file supplied each key
627 (`Provenance`, M2 §3.6), so this is a check at the point of use, not a second pass.
628
629 **Rule 2 — consent, per definition.** Before a command runs for the first time, a modal shows
630 the exact argv, the config file it came from, and three choices — Run once / Always allow /
631 Cancel — with **Cancel focused**. "Always allow" appends a record to
632 `<user_state_dir>/harlequin/trusted_commands.json`:
633
634 ```json
635 {"name":"ai","source":"/home/ted/.config/harlequin/config.toml",
636 "command":"claude -p 'Rewrite this SQL…'","fingerprint":"sha256:…","trusted_at":"2026-09-02T…"}
637 ```
638
639 The fingerprint covers the name, the resolved argv and the source path, so **editing the
640 command re-prompts**. The store is in state, not in config, deliberately: a synced config file
641 that could carry its own approval would defeat the gate it is supposed to pass. The plaintext
642 command sits beside the hash so the file can be audited by the person it protects, and revoking
643 is deleting a line.
644
645 **What is not gated:** `$EDITOR`/`$VISUAL` (§3.6), and `hsql --open` launching `harlequin`
646 (a known entry point in the same interpreter, not a user string).
647
648 **What is never automatic:** a hook runs only from a key the user pressed. No hook on start-up,
649 on connect, on error, or on quit — that is how a config-defined command becomes a startup
650 payload, and there is no version of it M4 wants.
651
652 ### 3.9 Actions can come from config, so the registry becomes a function
653
654 `HARLEQUIN_ACTIONS` stays as the static base; `build_actions(command_names)` returns it plus
655 one `command.<name>` entry per configured hook, targeting `CodeEditor` with
656 `run_command('<name>')` and the hook's `description`. `app.py`, `keys_app.py` and the keymap
657 loader all take the built registry — `keys_app` already loads config to find keymaps, so it
658 can list a user's own commands in the binding editor beside the built-in actions.
659
660 And the crash in §1.5 gets fixed on the way, because it is now reachable by typo *and* by a
661 command that was renamed: an unknown action name is **skipped with one notification naming the
662 keymap and the action**, not a `KeyError` in mount. A keymap with one bad line should cost the
663 user that line, not the application.
664
665 ---
666
667 ## 4. Sequencing
668
669 Three releases, and **the editor and the hooks go first** (Ted's call). Nothing in this
670 milestone depends on anything else in it — that is what makes the order a choice rather than a
671 constraint — so the order is by what users are waiting for and by how much design risk each
672 group carries. [#1102](https://github.com/tconbeer/harlequin/issues/1102) is open, has a
673 reference implementation, and needs nothing else here; the trust model under it is the most
674 consequential decision in M4 and benefits from being in the world early rather than shipping
675 last with two other features on top of it. The query history follows, because it changes a
676 stored format and a screen, because it is what makes an agent's queries visible to a human at
677 all, and because search ([#429](https://github.com/tconbeer/harlequin/issues/429)) is what
678 decides the format it changes to. The handoff is last: it is the largest new public surface —
679 two flags across two commands — and it lands better after the history, since a draft handed to
680 a human and the queries they run against it are then one story rather than two.
681
682 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.
683
684 Numbering assumes M3's remaining work releases as 2.13.
685
686 ### Release A — the editor and the hooks (2.13)
687
688 **PR 1 — The external editor.** `$EDITOR`/`$VISUAL` only, `harlequin.external.run_in_terminal()`,
689 the suspend wrapper and its unsupported-environment path, temp-file exchange, non-zero-exit
690 discard, and the `code_editor.edit_externally` action. No config key and no trust store yet, so
691 it is reviewable on its own. Closes
692 [#1102](https://github.com/tconbeer/harlequin/issues/1102) for the request as filed.
693
694 **PR 2 — The trust gate.** Provenance rule, consent modal, trust store, and the config
695 `editor` key as its first consumer. The gate ships with something small enough to review it
696 against, and a release before anything larger runs through it.
697
698 **PR 3 — `[commands]` in config, and actions from config.** The `Config` member, the schema
699 regeneration (`scripts/write_config_schema.py`, and the pinned artifact), `build_actions()`,
700 the keymap-validation fix from §1.5, and `--config validate`'s coverage of the new table.
701 Nothing executes yet; the keys bind to an action that reports "not implemented" in exactly one
702 commit, or PR 3 and PR 4 land together if that reads badly in review.
703
704 **PR 4 — Running a hook.** The worker, stdin/stdout, the four `output` modes, the empty-output
705 rule, timeout and cancel, error surfacing. Answers
706 [#952](https://github.com/tconbeer/harlequin/issues/952).
707
708 **PR 5 — Docs** (`harlequin-web`): "External editor" and "Bring your own AI" pages, the trust
709 model stated plainly, and a worked `claude -p` config with the prompt that keeps code fences
710 out of the buffer.
711
712 ### Release B — query history, and search (2.14)
713
714 **PR 6 — `harlequin.query_log`.** The schema, the pragmas, `user_version` and its migration
715 step, the writer, retention, `get_connection_hash()`'s move out of `catalog_cache`,
716 `history = false`, and both commands writing. The IDE starts calling `hide_secrets_in()`
717 here — the store is the first thing it persists that could carry a value from a profile
718 (§1.4). Guards: `hsql`'s import set still contains no rich, and `hsql --version` is still
719 ~120ms.
720
721 **PR 7 — `hsql --history` and `--history-search`.** Both modes, the connection filter, the
722 folded `sql` column, `--limit` as "the most recent N", and the search clause. Nothing new in
723 the output layer — the listing goes through the emitters `--catalog` already uses. Adds both
724 modes to the skill. Closes B7's headless half and #429's.
725
726 **PR 8 — The History screen reads the store.** `History.recent()`, `CatalogCache.history`
727 removed, `CACHE_VERSION` to 3, and the one-time migration. This is the PR where an agent's
728 queries first show up in a human's History screen, and where the human's show up under
729 `--history`.
730
731 **PR 9 — The History screen, reconsidered.** The filter input over the whole store, plus
732 modal, a non-focusable preview, and the screen's own bindings shown as every other screen
733 shows them (§1.2, §3.4). Search and the rework land together because they are the same
734 screen and the same reading of it: the pane is for choosing a query, not for editing one.
735 Closes [#429](https://github.com/tconbeer/harlequin/issues/429) and
736 [#850](https://github.com/tconbeer/harlequin/issues/850).
737
738 **PR 10 — Docs** (`harlequin-web`): the query history — where it lives, what it holds, how to
739 search it from either front end, and that it is a SQLite file the reader can open in Harlequin
740 itself — and `--history` in "Headless & Agents".
741
742 ### Release C — the handoff (2.15)
743
744 **PR 11 — `harlequin.invocation`, and `harlequin --open`.** The dataclass, both argv renderers,
745 and the IDE flag that loads files into buffers without executing them. `cli.py` builds an
746 `Invocation` and hands it to the app. Closes the half of F1 the IDE owns, and is useful on its
747 own (`harlequin --open report.sql`).
748
749 **PR 12 — `hsql --open`.** The mode option, the secret refusal, the scratch file and its
750 pruning, the exec/subprocess split, and the `/dev/tty` reattach. Rewrites the skill's section
751 9 (`hsql --skill` ships from the wheel, so this is the same PR). Closes F1.
752
753 **PR 13 — Copy CLI command.** The action, the quoting, the masking, the registry entry. Closes
754 F2.
755
756 **PR 14 — Docs** (`harlequin-web`): the handoff section in "Headless & Agents", and `--open` on
757 both command pages.
758
759 **Ordering rationale.** Within a release, unchanged from M1 and M2: a contract or a gate lands
760 with the first consumer that needs it, and nothing declares a thing nothing reads. Across
761 releases, the three groups are independent, so the order is a product decision rather than a
762 technical one — which also means it can change again without rewriting §3.
763
764 ---
765
766 ## 5. Testing
767
768 **Unit, and most of the milestone is unit-testable.**
769
770 - `Invocation.to_hsql_argv()` / `to_harlequin_argv()`: profile vs conn_str, typed vs defaulted
771 options, the secret refusal, and quoting on both platforms (parametrized over
772 `shlex.quote`/`list2cmdline` rather than skipped on one).
773 - `query_log`: row round trip; the schema migration, from `user_version = 0` forward and on a
774 store already at the current version; retention trimming to the newest N; `redact_text()`
775 applied to `sql`; an unwritable directory and an unreadable store each disabling logging
776 without raising; and the WAL fallback, exercised by a store where `journal_mode=wal` does
777 not stick.
778 - The **concurrent write** measurement becomes a real test — 4 processes × 100 inserts,
779 asserting every row lands and no `sqlite3.Error` escapes — marked so it can be deselected on
780 a slow runner.
781 - The pickle migration, including timestamps that predate the store, and a second run that
782 does not double-insert.
783 - `--history`: the connection filter with two connections interleaved; `--limit` taking from
784 the newest end; `--history-search` matching mid-string, and its case behavior pinned where
785 SQLite's `like` would otherwise surprise us; the folded `sql` column matching between
786 `--format table` and `--format csv`, asserted the way the golden-format snapshots assert it
787 rather than against a copy of the folding rule; `--json` emitting `rows` and `elapsed_ms`
788 unquoted, and null for a statement that has neither; and an empty store printing a header
789 and no rows rather than nothing.
790 - A guard that `--history` opens no connection: the mode runs against a profile whose adapter
791 would raise on `connect()`, and still prints rows.
792 - Trust: fingerprint stability across a whitespace change (it should change — the argv is what
793 runs), and the provenance rule (a `[commands]` table in `./pyproject.toml` is ignored; the
794 same table under `--config-path` is not).
795 - `build_actions()`: a command name that collides with a built-in action, and a keymap naming
796 an action nothing defines.
797
798 **Functional (pilot + snapshot).**
799
800 - `harlequin --open a.sql b.sql`: two new buffers, the second active, **nothing executed** —
801 assert on the absence of a `QuerySubmitted`, not only on the snapshot.
802 - The copy action: assert the string, through the editor's clipboard rather than the system's.
803 - The hook worker against a **hermetic child** — `[sys.executable, "-c", …]`, never an external
804 binary — covering success, empty stdout, non-zero exit with stderr, and a timeout that kills
805 a child that ignores `terminate()`.
806 - The consent modal: cancel leaves the buffer alone and runs nothing; "always allow" writes one
807 record and the second invocation does not prompt.
808 - The History screen after #850 and #429: an app-level binding pressed on the screen does
809 nothing, Tab does not land focus in the preview, and typing in the filter narrows the list
810 to rows the 500-record window would not have held — all asserted on behavior, not on the
811 snapshot, since the snapshot changes for reasons none of them cares about.
812 - The editor round trip with `run_in_terminal` patched, plus the `SuspendNotSupported` path
813 asserted as a notification — §1.6 measured that the real suspend cannot be reached in
814 `run_test()`, so the seam is the test surface.
815
816 **Import hygiene.** `harlequin.invocation` and `harlequin.query_log` join `HEADLESS_IMPORTS`.
817 A run that logs must not import rich: that is the assertion that keeps §1.3's finding from
818 coming back as a 46ms regression on every `hsql -c`.
819
820 **Not tested, and said out loud:** no test runs a real editor or a real model; nothing asserts
821 on `/dev/tty` reattachment (CI has no controlling terminal) — the decision function is tested,
822 the two `dup2` calls are not.
823
824 ---
825
826 ## 6. Decisions
827
828 ### 6.1 The external editor and the AI hook are two features
829
830 The product plan folds them together — "same shape as the existing external-editor request" —
831 and the shape is where they differ:
832
833 | | External editor | Command hook |
834 | --- | --- | --- |
835 | The terminal | needs it; the app suspends | must not have it; the app stays live |
836 | Thread | main, blocking (suspend redirects the process's streams) | worker |
837 | Exchange | a temp file, edited in place | stdin → stdout |
838 | Duration | as long as the human takes | seconds, and needs a bound |
839 | Cancel | quitting the editor | a timeout, and a key |
840 | Failure | non-zero exit means "discard" | non-zero exit is an error to show |
841 | Config | one key; `$EDITOR` is usually all of it | a named command with a prompt, per task |
842 | Trust | the environment is the user | a file is not |
843 | Privacy | the query stays on the machine | the query may leave it |
844
845 What they share is four lines: build an argv, start a process, read a result, apply it as one
846 undoable edit. Unifying them means a single config table with an `interactive` switch, a
847 `{file}` placeholder whose presence silently changes the exchange, and a validity table where
848 most combinations are refused — a worse config than two tables, to save four lines. They also
849 close two different issues, for two different users, and the editor ships first because it
850 needs no trust store at all — `$EDITOR` is the user's own environment (§6.8).
851
852 ### 6.2 `hsql --open`, not `hsql open`
853
854 M2's rule, unchanged: `CONN_STR` is positional, so a subcommand named `open` would need a rule
855 to distinguish it from a DuckDB file named `open`. `--open` needs none, and it composes with
856 `-c`, `-f` and stdin, which a subcommand taking its own path argument would have duplicated.
857
858 ### 6.3 The handoff execs; it does not import, and it does not write the buffer cache
859
860 Measured in §1.1: the cache is Textual (+164ms and 341 modules) and is rewritten whole at
861 quit, so a second writer races the IDE. An in-process import of `harlequin.cli` would break
862 the one contract `hsql` is defined by. `python -m harlequin` in the same interpreter is the
863 only option that is both correct and cheap, and it is cheap only relative to what it launches
864 — a 620ms `harlequin --version` is the floor for anything that opens the IDE.
865
866 ### 6.4 One SQLite store, not JSONL, and not one file per connection
867
868 The roadmap says "JSONL history," and this plan said so too until #429 came into scope. The
869 reversal is in §3.2 and rests on one number: searching 100,000 records is 396ms as a file scan
870 and 35ms as a `like`. Everything else was close enough to be a preference — writes 14µs apart,
871 `sqlite3` importing cheaper than `json`, files within 15% in size, tail reads a wash — and
872 search is not close.
873
874 Three second-order effects, all in the same direction. **The reader stops existing**: no
875 reverse-scan-by-chunks, no truncated last line, no "read further back until 500 match" — one
876 indexed query instead, and a whole class of §5 tests with it. **A schema change becomes an
877 `alter table`**, where the pickle caches bump a version and discard, which is the wrong
878 behavior for the one store whose contents cannot be re-fetched. And **the file is a database
879 Harlequin can open**: `harlequin -a sqlite ~/.local/state/harlequin/history.db` is a better
880 answer to "readable with ordinary tools" than `jq` was, on every platform.
881
882 What is given up is `tail -f`, and `hsql --history --jsonl` gives back the format if not the
883 follow. Still one store rather than one per connection, for the reason it always was: an agent
884 asking what has been run against a warehouse should not have to know a connection hash to find
885 a file, and ordering across databases is a `order by`, not a merge.
886
887 ### 6.5 `--history` is a mode, and the store's path is not in `--info`
888
889 When the store was a JSONL file, the tempting cut was to ship it and let `tail` and `jq` be
890 the reader. It is a mode (Ted's call), and three things say so — the first two of which
891 outlived the format, and the third of which is why a SQLite store needs one even more.
892
893 **A mode is nearly free, because a listing is a result set.** M2 §3.3 built that road for
894 `--catalog`: hand the emitters a `ResultSet` and every format, every layout flag and `-o`
895 follow. `--history` is a reader plus a table; it is not a second output stack.
896
897 **The pipeline is not portable and not self-describing.** It needed `jq`, a path, a filter by
898 connection, and a shell that has `tail` — which Windows does not. "Read the human's recent
899 queries" is a thing the skill should be able to teach in one line that works everywhere. With
900 a SQLite store the pipeline would need `sqlite3` and a schema besides, so the mode carries
901 more weight now, not less.
902
903 **And `--info` is the wrong place for the path.** `--info` reports on the installation —
904 versions, platform, config files, adapter capabilities. A pointer into the user's own query
905 history is a different kind of fact, and putting it there invites a reader to go parse the file
906 by hand when a mode can hand them rows. The path stays in the docs, where a person who wants to
907 back the file up or delete it will look.
908
909 ### 6.6 The hook's context is a profile name, not a catalog
910
911 Harlequin already ships the best catalog-for-agents interface it has (`--catalog`,
912 `--catalog-search`, `--info`), documented in M3 and taught by the skill. A hook that gets
913 `HARLEQUIN_PROFILE` can call it; a hook that gets 40 KB of marshalled catalog on stdin pays
914 for a walk it may not need and gets a second, worse format for the same data.
915
916 ### 6.7 The trust store is not the config file
917
918 If "always allow" wrote back into the config, a synced config could ship its own approval and
919 the gate would protect nothing. State dir, fingerprinted by argv and source, plaintext beside
920 the hash so the person it protects can audit it.
921
922 ### 6.8 `$EDITOR` is trusted; a config file is not
923
924 Ted's call, and the line generalizes: the environment is the user's own session, and a config
925 file is a document that arrives from a directory (`$CWD`) or a sync (dotfiles) that the user
926 may not have read. That is also why the provenance rule (§3.8) is separate from the consent
927 prompt — one keeps a stranger's file from ever asking, the other keeps the user's own file
928 honest.
929
930 ### 6.9 The copied command carries no `--csv`
931
932 The product plan's example is `hsql -P prod -c '…' --csv`. The human copying it is looking at
933 a table, and the agent receiving it knows from the skill to pick a format on purpose (§5 of
934 `SKILL.md`). A format flag in the copied string is a guess about the recipient; the profile,
935 the connection and the SQL are not.
936
937 ---
938
939 ## 7. Explicitly not in M4
940
941 - **`hsql mcp`** — M6, unchanged.
942 - **Streaming, `--offset`, and the memory work in #875** — M5.
943 - **A post-editor action** (#1102's third checkbox: format or run on return). The buffer is
944 back in the editor and `code_editor.format` and `code_editor.run_query` are already bound.
945 - **Hooks anywhere but the Query Editor.** A hook over a *result set* — "explain this table" —
946 is a real idea and a different feature: it needs a serialization of the result, a size
947 policy, and an answer for where the output goes.
948 - **Code-fence stripping on hook output.** The prompt is the config author's, and the docs give
949 one that works. A heuristic here would be Harlequin guessing at model output.
950 - **`shell = true`, and placeholders beyond none.** §3.7.
951 - **Action-name validation in `hsql --config validate`.** It would be genuinely useful — an
952 agent editing a keymap would learn about a typo without starting a TUI — but the registry
953 lives in `harlequin.actions`, which imports `harlequin.components` and therefore Textual.
954 Doing it properly means splitting the *names* into a leaf module and leaving the widget
955 targets behind, which is a refactor to make on purpose, with the second consumer in hand.
956 - **A `--open` that starts a query running.** It would collapse the review step F1 exists for.
957 - **`--history --since 2h`.** Obvious the moment the mode exists, and one more `where` clause
958 once the store is a database — but `--limit` and newest-first cover the case this milestone
959 is for. Worth doing next, not now.
960 - **FTS5 over the history.** `like` is 35ms over 100,000 rows (§3.2), an FTS table is a second
961 thing to keep in step with the first, tokenizing SQL is a poor fit for a tokenizer built for
962 prose, and FTS5 is a compile-time option that is *usually* present. Revisit at a million
963 rows, with a measurement rather than an instinct.
964 - **Anything else in the history store.** The catalog and buffer caches are still pickles, and
965 the database that now exists is an obvious home for them. It is also a separate change, with
966 a separate migration and a separate failure mode, and this milestone has enough of both.
967 - **Per-hook cancel keys, hook chaining, and hooks that write config.** Each is a feature
968 request that will read as obvious once one hook works, and none of them is M4's.
969
970 ---
971
972 ## 8. Corrections to the product plan
973
974 Recorded here; applied to `harlequin-for-agents.md` in the same PR as this document.
975
976 - **§11's M4 row still lists the skill**, which shipped in M3 (`hsql --skill`, the packaged
977 `SKILL.md`, and the marketplace entry). The row is `hsql --open`, the query log, "Copy CLI
978 command", the external editor, and command hooks.
979 - **§10's `hsql open query.sql` is a subcommand, and M2 settled on mode options.** The spelling
980 is `hsql --open`, reading its SQL from `-c`, `-f` or stdin like every other run (§6.2).
981 - **§10's "buffers already persist through `editor_cache.py`, so the machinery is close at
982 hand" is measurably wrong in the direction that matters.** That cache imports Textual and is
983 rewritten whole at quit; it is the one mechanism the handoff cannot use (§1.1).
984 - **§10 treats the external editor and the AI hook as one feature.** They differ in the
985 terminal, the thread, the exchange, the failure mode and the trust model, and #1102 now
986 exists as its own issue with its own reference implementation (§6.1).
987 - **§10 does not mention consent, and a config-defined shell command needs it.** Config files
988 merge from `$CWD`, so a cloned repository can define one; a synced dotfiles repo can do the
989 same in the user's own config dir. §3.8 is the missing paragraph.
990 - **The roadmap's "JSONL history" names a format that search rules out.** M4 stores query
991 history in SQLite and *emits* JSON Lines: `hsql --history --jsonl` is the record the roadmap
992 described, and the store behind it is what makes #429 affordable (§3.2, §6.4).
993 - **§6's `hsql history --json -n 20` is the right feature under two wrong assumptions.** The
994 spelling is `hsql --history --json --limit 20` — a mode option, and `--limit` rather than a
995 new `-n`, because both commands already mean "the rows that leave the store" by it. And what
996 it reads is not the pickle §6 proposes to "expose": that one is written once, at quit, behind
997 a module headless code may not import (§1.2, §1.3). The log is the store; the mode is the
998 reader (§3.3).
999 - **§12's risk list says query history "sits outside that mechanism" and needs its own
1000 handling.** It needs one line of handling: `redact_text()` on the way into the log, plus the
1001 `hide_secrets_in()` call the IDE has never made (§1.4, §3.2).
1002 - **§9's skill section 9 is rewritten by this milestone**, as M3 §7 predicted: the handoff
1003 advice becomes `hsql --open -f draft.sql -P prod` rather than "tell them to run `harlequin`".
1004 - **#952 is closed as `not planned`**, with "I won't be adding this to Harlequin. But shortly I
1005 am releasing `hsql`." §10's "#952 answered without embedding an LLM" is still the right
1006 answer; the changelog entry should reference #952 for the hook and #1102 for the editor,
1007 and #952 can be reopened or left closed with a comment pointing at the hook.
1008 - **§13's success criteria should gain one line**: a query run by `hsql` appears in the human's
1009 History screen, and a draft written by an agent opens in the human's editor without being
1010 run. That is what Workstream F is for, and neither is measurable today.