@vibe-agent-toolkit/cli 0.2.0-rc.4 → 0.2.0-rc.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/bin.js +35 -2
  2. package/dist/bin.js.map +1 -1
  3. package/dist/commands/audit.d.ts.map +1 -1
  4. package/dist/commands/audit.js +23 -5
  5. package/dist/commands/audit.js.map +1 -1
  6. package/dist/commands/claude/plugin/install.js +0 -1
  7. package/dist/commands/claude/plugin/install.js.map +1 -1
  8. package/dist/commands/corpus/runner.d.ts.map +1 -1
  9. package/dist/commands/corpus/runner.js +1 -19
  10. package/dist/commands/corpus/runner.js.map +1 -1
  11. package/dist/commands/inventory.js +1 -1
  12. package/dist/commands/inventory.js.map +1 -1
  13. package/dist/commands/resources/check-progress.d.ts +145 -0
  14. package/dist/commands/resources/check-progress.d.ts.map +1 -0
  15. package/dist/commands/resources/check-progress.js +205 -0
  16. package/dist/commands/resources/check-progress.js.map +1 -0
  17. package/dist/commands/resources/check-supervisor.d.ts +465 -0
  18. package/dist/commands/resources/check-supervisor.d.ts.map +1 -0
  19. package/dist/commands/resources/check-supervisor.js +566 -0
  20. package/dist/commands/resources/check-supervisor.js.map +1 -0
  21. package/dist/commands/resources/check.d.ts +454 -0
  22. package/dist/commands/resources/check.d.ts.map +1 -0
  23. package/dist/commands/resources/check.js +1237 -0
  24. package/dist/commands/resources/check.js.map +1 -0
  25. package/dist/commands/resources/index.d.ts.map +1 -1
  26. package/dist/commands/resources/index.js +277 -6
  27. package/dist/commands/resources/index.js.map +1 -1
  28. package/dist/commands/resources/query.d.ts +89 -0
  29. package/dist/commands/resources/query.d.ts.map +1 -0
  30. package/dist/commands/resources/query.js +146 -0
  31. package/dist/commands/resources/query.js.map +1 -0
  32. package/dist/commands/resources/scan.js +1 -1
  33. package/dist/commands/resources/scan.js.map +1 -1
  34. package/dist/commands/skills/install.js +0 -1
  35. package/dist/commands/skills/install.js.map +1 -1
  36. package/dist/commands/skills/skill-discovery.d.ts.map +1 -1
  37. package/dist/commands/skills/skill-discovery.js +4 -2
  38. package/dist/commands/skills/skill-discovery.js.map +1 -1
  39. package/dist/utils/agent-runner.d.ts.map +1 -1
  40. package/dist/utils/agent-runner.js +7 -3
  41. package/dist/utils/agent-runner.js.map +1 -1
  42. package/dist/utils/command-error.d.ts +56 -1
  43. package/dist/utils/command-error.d.ts.map +1 -1
  44. package/dist/utils/command-error.js +66 -3
  45. package/dist/utils/command-error.js.map +1 -1
  46. package/dist/utils/config-loader.d.ts.map +1 -1
  47. package/dist/utils/config-loader.js +10 -3
  48. package/dist/utils/config-loader.js.map +1 -1
  49. package/dist/utils/issue-severity.d.ts +12 -5
  50. package/dist/utils/issue-severity.d.ts.map +1 -1
  51. package/dist/utils/issue-severity.js +1 -1
  52. package/dist/utils/issue-severity.js.map +1 -1
  53. package/dist/utils/projection-query.d.ts +263 -0
  54. package/dist/utils/projection-query.d.ts.map +1 -0
  55. package/dist/utils/projection-query.js +262 -0
  56. package/dist/utils/projection-query.js.map +1 -0
  57. package/dist/utils/projection-store.d.ts +104 -2
  58. package/dist/utils/projection-store.d.ts.map +1 -1
  59. package/dist/utils/projection-store.js +126 -4
  60. package/dist/utils/projection-store.js.map +1 -1
  61. package/dist/utils/vat-bin-path.d.ts +36 -0
  62. package/dist/utils/vat-bin-path.d.ts.map +1 -0
  63. package/dist/utils/vat-bin-path.js +49 -0
  64. package/dist/utils/vat-bin-path.js.map +1 -0
  65. package/package.json +25 -14
@@ -0,0 +1,263 @@
1
+ /**
2
+ * Populating a tree's resource projection and putting it somewhere ASKABLE —
3
+ * the shared half of every command that runs SQL over it.
4
+ *
5
+ * `vat resources query` runs one statement a person typed; `vat resources check`
6
+ * runs the statements a project wrote down. They differ in what they do with
7
+ * rows and in nothing else: same population, same store selection, same
8
+ * ephemeral fallback, same cache tell. This module is that "and in nothing
9
+ * else", stated once so the two cannot drift into answering about different
10
+ * corpora.
11
+ *
12
+ * ## ðŸšĻ The SQL ALWAYS runs against a per-run in-memory database. Never the store.
13
+ *
14
+ * This is a correctness property, not an optimisation choice, and it was learned
15
+ * the expensive way. The on-disk projection store is **one database per VAT
16
+ * release, shared by every root on the machine** (`defaultStoreDirectory()` is
17
+ * `tmpdir/.vat-cache/<version>/projection-<shapeDigest>`), it retains three tree
18
+ * hashes per root, and its blob tier is never evicted and carries no tree key at
19
+ * all. `ProjectionStore.readExtent` narrows by `(rootId, treeHash)`; **arbitrary
20
+ * SQL does not**, and cannot be made to — a `WHERE` clause the caller wrote is
21
+ * not a key predicate.
22
+ *
23
+ * So running a user's statement against the file-backed store answered from
24
+ * every projection on the machine. Measured on a two-file scratch repository:
25
+ * `SELECT COUNT(*) FROM resource_realizations` returned **3** with no store and
26
+ * **5,779** with one, and `WHERE path LIKE 'packages/%'` returned paths from a
27
+ * different repository entirely. That is a wrong answer and a cross-project
28
+ * disclosure of link text, heading text and frontmatter — the same material
29
+ * `store.ts` cites as the reason it chmods the cache `0o700`.
30
+ *
31
+ * ⇒ The store's job is to make the POPULATION cheap, and that is all. Whatever
32
+ * `populate()` returns — served from the store or derived — is written into a
33
+ * fresh in-memory database that holds this tree and nothing else, and the SQL
34
+ * runs there. The saving is untouched (it was always in the population: on this
35
+ * repository {@link ProjectionProvenance.populationMs} reads 1.16-1.18 s derived
36
+ * against 0.29-0.31 s served), and "one tree, one answer" stops being a claim
37
+ * about how callers behave and becomes a property of the shape.
38
+ *
39
+ * ## The store never reaches a caller
40
+ *
41
+ * Work runs against an `ask` closure rather than a store handle. That is
42
+ * deliberate: `utils/projection-store.ts` is the one module in the toolkit that
43
+ * knows `@vibe-agent-toolkit/projection-sqlite` exists, and handing commands a
44
+ * backend-typed object would spread that knowledge to every future verb. A
45
+ * closure also puts the legible-failure wrapper on the single path that can
46
+ * throw, so no command can forget it.
47
+ */
48
+ import type { Logger } from './logger.js';
49
+ /** Where the POPULATION a statement ran against came from. */
50
+ export type PopulationOrigin = 'derived' | 'store';
51
+ /**
52
+ * What a run's rows are, and where they came from.
53
+ *
54
+ * ⚠ïļ There is deliberately no `engine` field beside these. An earlier version
55
+ * published one (`sqlite | ephemeral`) to say which database answered the SQL;
56
+ * it is gone because the answer is now always the same — see the header — and a
57
+ * field with one possible value tells a reader nothing while implying the other
58
+ * value is reachable.
59
+ */
60
+ export interface ProjectionProvenance {
61
+ /**
62
+ * 🔑 The cache tell. Reported rather than inferred, because it CANNOT be
63
+ * inferred: a correct store hit and a correct re-derivation produce identical
64
+ * rows. A hit short-circuits `populate()` before the builder exists, so no
65
+ * contributor timing is filed — an empty record list IS the hit.
66
+ *
67
+ * It describes the POPULATION, which is the only thing the store now affects.
68
+ */
69
+ readonly population: PopulationOrigin;
70
+ /**
71
+ * 🔑 What that origin was WORTH. {@link population} says whether the
72
+ * projection was served or re-derived; this says what the difference cost, so
73
+ * the tell stops being a bare label a reader has to take on faith.
74
+ *
75
+ * Measured as THIS field, by running `vat resources query 'SELECT COUNT(*) AS
76
+ * n FROM blobs'` against this repository three times per arm with the parse
77
+ * cache warm: **1.16-1.18 s derived against 0.29-0.31 s served**. With a cold
78
+ * parse cache the derived arm is 33-35 s, so the pair above is the store's
79
+ * saving and not the parse cache's.
80
+ *
81
+ * The wall time of the SHARED setup and nothing else: everything
82
+ * {@link withQueriedProjection} does before it hands control to the caller's
83
+ * work — opening the population cache (which, when a store is selected, is a
84
+ * `git write-tree` spawn plus the backend's dynamic import and
85
+ * `openSqliteProjectionStore()`), the git tracker, `buildResourceProjection`,
86
+ * opening the ephemeral database, and writing the blob tier and the extent
87
+ * into it.
88
+ *
89
+ * ⚠ïļ The population cache's CLOSE is outside it, necessarily: that runs in
90
+ * `withPopulationCache`'s `finally`, after the caller's work returns, and a
91
+ * span that ends before the work begins cannot contain it. It is a handle
92
+ * release, not population.
93
+ *
94
+ * ðŸŠĪ **The span's start is load-bearing, and moving it inward is silent.**
95
+ * This shipped with the clock started on the first line INSIDE
96
+ * `withPopulationCache`'s callback — which put the population-cache open, the
97
+ * only part of the setup a store adds, OUTSIDE the measurement, and only on
98
+ * the arm where a store exists. Measured on a two-file corpus with identical
99
+ * total wall time on both arms: no store 0.145 of 0.146 s, cold store 0.0475
100
+ * of 0.161 s. Same work, `populationSecs` three times apart, and a reader
101
+ * comparing a no-store run to a warm-store run read a 42x saving where the
102
+ * honest totals differ by 1.75x. The field was added to stop the cache tell
103
+ * being a label taken on faith and had become the artifact instead. A
104
+ * measurement that flatters one arm is this repository's most-repeated
105
+ * defect; the system suite now pins `populationSecs / durationSecs > 0.6` on a
106
+ * cold run so the next inward move is red rather than quiet.
107
+ *
108
+ * ## Why it belongs on shared provenance rather than on one verb
109
+ *
110
+ * Both verbs pay it, identically, because it is the half of the run they hold
111
+ * in common — a `check` that runs forty statements and a `query` that runs one
112
+ * do the same population first. And a per-statement cost is UNREADABLE without
113
+ * it: `vat resources check` publishes what each rule's SQL cost, and a reader
114
+ * handed forty small numbers and a large total has no way to tell an expensive
115
+ * rule from a setup everybody shares. Absent this field the only arithmetic
116
+ * available is "total minus the statements", which silently attributes the
117
+ * shared setup to whichever rule the reader is looking at.
118
+ *
119
+ * ⚠ïļ Measured with `performance.now()`, not `Date.now()`. A warm population
120
+ * lands well under a millisecond on a small tree, and a millisecond-granularity
121
+ * clock reports that as `0` — which reads as "not measured" rather than "very
122
+ * fast", turning the best case the store has into its least credible number.
123
+ *
124
+ * ⚠ïļ Deliberately ONE number, not a breakdown. Splitting it into crawl, parse
125
+ * and store-load is a real question and it is the lab's: an instrument that
126
+ * gets reviewed and re-run, rather than a product document that would then owe
127
+ * every consumer a stable sub-phase vocabulary.
128
+ */
129
+ readonly populationMs: number;
130
+ }
131
+ /**
132
+ * How much of the tree the population actually covered.
133
+ *
134
+ * ## Why this is not a field on {@link ProjectionProvenance}
135
+ *
136
+ * Provenance is a fact both verbs PUBLISH verbatim — "these rows were served or
137
+ * re-derived" is the same sentence in either document. This is a fact a verb
138
+ * REASONS with, and only one of them has anything to reason about: `vat
139
+ * resources query` prints the rows a person selected, so its reader can see the
140
+ * extent for themselves, while `vat resources check` prints a verdict and a
141
+ * count of rules. Only the second can pass vacuously, and only the second needs
142
+ * to know.
143
+ *
144
+ * ## 🔑 The failure it exists to make visible
145
+ *
146
+ * `vat resources check` reported how many CHECKS ran; nothing said how many ROWS
147
+ * they ran against. So "four checks passed over eight thousand files" and "four
148
+ * checks passed over ZERO files" were byte-identical documents, and the second
149
+ * was a green gate asserting nothing. A broad `.gitignore`, a shallow or sparse
150
+ * checkout, a root that resolved elsewhere, or an extent source that enumerated
151
+ * nothing all produce it — and `buildResourceProjection` DECLINES ignored
152
+ * members rather than flagging them, so an emptied enumeration leaves no trace
153
+ * in the tables either.
154
+ */
155
+ export interface PopulationExtent {
156
+ /**
157
+ * One per `(extentId, path)` row the population enumerated.
158
+ *
159
+ * ðŸŠĪ Realizations rather than any other count, because every alternative
160
+ * fails to reach zero on the case that matters: `roots` always holds exactly
161
+ * one row (the invariant thrown for below), so a total over all twelve tables
162
+ * is never 0; `blobs` is content-keyed and deduped, so it counts parse REACH
163
+ * and already has its own guard in `onBlobPopulation`; and `resources` counts
164
+ * identities, which a corpus can legitimately have none of while enumerating
165
+ * plenty. One row per enumerated path is non-zero exactly when something was
166
+ * enumerated.
167
+ */
168
+ readonly membersEnumerated: number;
169
+ }
170
+ /** Run one read-only statement against the populated projection. */
171
+ export type AskProjection = (sql: string, ...parameters: readonly string[]) => readonly Record<string, unknown>[];
172
+ /**
173
+ * Compile every statement a run intends to ask, against the schema and NO rows,
174
+ * before anything is populated.
175
+ *
176
+ * ## 🔑 What this buys, measured
177
+ *
178
+ * SQLite resolves table and column names when a statement is *prepared*, not
179
+ * when it is stepped — so a typo is knowable before a single row exists. It was
180
+ * not knowable in practice, because the only place a statement met the schema
181
+ * was after the projection had been built. On a real adopter tree, `SELECT path,
182
+ * no_such_column â€Ķ` cost **8.3 s**, every millisecond of it spent building a
183
+ * projection the statement could never have read. The same typo now costs the
184
+ * price of an empty in-memory database — one extra `createSchema` into
185
+ * `:memory:`, which is the whole overhead this adds on the happy path.
186
+ *
187
+ * It also moves the KIND refusals — a second statement, an `ATTACH`, a `PRAGMA`
188
+ * — in front of the population, so a statement rejected for what it is costs no
189
+ * more than one rejected for what it names.
190
+ *
191
+ * ⚠ïļ **This is a pre-flight, not a second gate.** `ask` still compiles and runs
192
+ * the real statement against the real projection, and nothing here is trusted in
193
+ * place of that. A statement that compiles here can still fail there — SQLite
194
+ * resolves names against a schema, and this is the same schema, but a run-time
195
+ * error (a bad cast, an overflow) belongs to stepping and is unreachable from a
196
+ * prepare.
197
+ *
198
+ * ⚠ïļ It deliberately does not STEP anything. Stepping is where a check's
199
+ * unbounded cost lives, and a preflight that ran `WITH RECURSIVE â€Ķ` would hang
200
+ * before the run it exists to make cheap had begun.
201
+ *
202
+ * @param statements - Every statement the run will ask, in any order
203
+ * @throws The same legible failure `ask` throws, for the first statement that
204
+ * does not compile
205
+ */
206
+ export declare function assertQueriesCompile(statements: readonly string[]): Promise<void>;
207
+ /**
208
+ * Populate the tree, load it into something askable, and hand the caller a way
209
+ * to ask.
210
+ *
211
+ * @param options - The run
212
+ * @param options.root - Absolute corpus root
213
+ * @param options.logger - Where blob-stage refusals are reported (stderr, so a
214
+ * parseable document on stdout stays parseable)
215
+ * @param options.preflight - Every statement this run intends to ask, compiled
216
+ * against the empty schema BEFORE the population starts. See
217
+ * {@link assertQueriesCompile}
218
+ * @param work - Given the asker, where its rows came from, and how much of the
219
+ * tree they cover. The store is open for exactly this call and closed however
220
+ * it ends
221
+ * @returns Whatever `work` returned
222
+ */
223
+ export declare function withQueriedProjection<T>(options: {
224
+ root: string;
225
+ logger: Logger;
226
+ preflight?: readonly string[];
227
+ }, work: (ask: AskProjection, provenance: ProjectionProvenance, extent: PopulationExtent) => Promise<T> | T): Promise<T>;
228
+ /**
229
+ * Turn a rejected statement into a message that names the surface it missed.
230
+ *
231
+ * ## Why this wrapper exists
232
+ *
233
+ * VAT ships no schema version, by standing rule — the *cache* is safe across a
234
+ * shape change because its digest self-invalidates, but submitted SQL is not: it
235
+ * simply breaks. Pre-1.0 that is acceptable. A raw SQLite error reaching the
236
+ * user is not, because `no such column: contentHash` says nothing about what the
237
+ * column is called now. It matters more for a CHECK than for a query: a query's
238
+ * author is at the keyboard, while a check's author wrote it months ago and the
239
+ * person reading the failure is someone else.
240
+ *
241
+ * ⚠ïļ **A legibility wrapper, not a validator.** It does not parse SQL and does
242
+ * not check a statement before running it — it reacts to a failure by listing
243
+ * what the query COULD have named. When the statement mentions a known table,
244
+ * that table's columns are listed, which is the case that actually answers "what
245
+ * moved"; otherwise the table names are, which at least answers "what is there".
246
+ *
247
+ * ðŸŠĪ **Only a name that was not found gets the listing.** The engine also refuses
248
+ * a write and this backend refuses a second statement, and neither is answered by
249
+ * a column list — appending one says the problem is the schema when the problem
250
+ * is what the caller asked for. A wrapper that decorates every failure identically
251
+ * teaches the reader to skip the decoration, which costs the case it was written for.
252
+ *
253
+ * Matching is a plain lowercase substring test rather than a regex: the input is
254
+ * user text, and a pattern built from it is both a lint failure here and a
255
+ * needless hazard.
256
+ *
257
+ * @param sql - The statement that was submitted
258
+ * @param message - What the engine said
259
+ * @returns The message to surface, with the queryable surface appended when the
260
+ * failure was a name this projection does not have
261
+ */
262
+ export declare function describeQueryFailure(sql: string, message: string): string;
263
+ //# sourceMappingURL=projection-query.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"projection-query.d.ts","sourceRoot":"","sources":["../../src/utils/projection-query.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AAYH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAkB1C,8DAA8D;AAC9D,MAAM,MAAM,gBAAgB,GAAG,SAAS,GAAG,OAAO,CAAC;AAEnD;;;;;;;;GAQG;AACH,MAAM,WAAW,oBAAoB;IACnC;;;;;;;OAOG;IACH,QAAQ,CAAC,UAAU,EAAE,gBAAgB,CAAC;IAEtC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA0DG;IACH,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;CAC/B;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;;;;;;;;;;OAWG;IACH,QAAQ,CAAC,iBAAiB,EAAE,MAAM,CAAC;CACpC;AAED,oEAAoE;AACpE,MAAM,MAAM,aAAa,GAAG,CAC1B,GAAG,EAAE,MAAM,EACX,GAAG,UAAU,EAAE,SAAS,MAAM,EAAE,KAC7B,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC;AAExC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,wBAAsB,oBAAoB,CAAC,UAAU,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAgBvF;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,qBAAqB,CAAC,CAAC,EAC3C,OAAO,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,EACxE,IAAI,EAAE,CACJ,GAAG,EAAE,aAAa,EAClB,UAAU,EAAE,oBAAoB,EAChC,MAAM,EAAE,gBAAgB,KACrB,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,GAClB,OAAO,CAAC,CAAC,CAAC,CA4FZ;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAezE"}
@@ -0,0 +1,262 @@
1
+ /**
2
+ * Populating a tree's resource projection and putting it somewhere ASKABLE —
3
+ * the shared half of every command that runs SQL over it.
4
+ *
5
+ * `vat resources query` runs one statement a person typed; `vat resources check`
6
+ * runs the statements a project wrote down. They differ in what they do with
7
+ * rows and in nothing else: same population, same store selection, same
8
+ * ephemeral fallback, same cache tell. This module is that "and in nothing
9
+ * else", stated once so the two cannot drift into answering about different
10
+ * corpora.
11
+ *
12
+ * ## ðŸšĻ The SQL ALWAYS runs against a per-run in-memory database. Never the store.
13
+ *
14
+ * This is a correctness property, not an optimisation choice, and it was learned
15
+ * the expensive way. The on-disk projection store is **one database per VAT
16
+ * release, shared by every root on the machine** (`defaultStoreDirectory()` is
17
+ * `tmpdir/.vat-cache/<version>/projection-<shapeDigest>`), it retains three tree
18
+ * hashes per root, and its blob tier is never evicted and carries no tree key at
19
+ * all. `ProjectionStore.readExtent` narrows by `(rootId, treeHash)`; **arbitrary
20
+ * SQL does not**, and cannot be made to — a `WHERE` clause the caller wrote is
21
+ * not a key predicate.
22
+ *
23
+ * So running a user's statement against the file-backed store answered from
24
+ * every projection on the machine. Measured on a two-file scratch repository:
25
+ * `SELECT COUNT(*) FROM resource_realizations` returned **3** with no store and
26
+ * **5,779** with one, and `WHERE path LIKE 'packages/%'` returned paths from a
27
+ * different repository entirely. That is a wrong answer and a cross-project
28
+ * disclosure of link text, heading text and frontmatter — the same material
29
+ * `store.ts` cites as the reason it chmods the cache `0o700`.
30
+ *
31
+ * ⇒ The store's job is to make the POPULATION cheap, and that is all. Whatever
32
+ * `populate()` returns — served from the store or derived — is written into a
33
+ * fresh in-memory database that holds this tree and nothing else, and the SQL
34
+ * runs there. The saving is untouched (it was always in the population: on this
35
+ * repository {@link ProjectionProvenance.populationMs} reads 1.16-1.18 s derived
36
+ * against 0.29-0.31 s served), and "one tree, one answer" stops being a claim
37
+ * about how callers behave and becomes a property of the shape.
38
+ *
39
+ * ## The store never reaches a caller
40
+ *
41
+ * Work runs against an `ask` closure rather than a store handle. That is
42
+ * deliberate: `utils/projection-store.ts` is the one module in the toolkit that
43
+ * knows `@vibe-agent-toolkit/projection-sqlite` exists, and handing commands a
44
+ * backend-typed object would spread that knowledge to every future verb. A
45
+ * closure also puts the legible-failure wrapper on the single path that can
46
+ * throw, so no command can forget it.
47
+ */
48
+ import { performance } from 'node:perf_hooks';
49
+ import { buildResourceProjection, PROJECTION_TABLES, splitProjectionByScope, } from '@vibe-agent-toolkit/resources';
50
+ import { gitTrackerForProjectRoot } from '../commands/audit/distributed-tree.js';
51
+ import { populationWiring } from './population-wiring.js';
52
+ import { openEphemeralQueryStore, withPopulationCache } from './projection-store.js';
53
+ /**
54
+ * The tree hash an in-memory store's one population is filed under.
55
+ *
56
+ * ⚠ïļ Deliberately NOT a tree hash. Nothing else ever opens this database, no
57
+ * read-back compares the key against another run's, and the store is gone at the
58
+ * end of the call — so the key only has to be internally consistent. A real
59
+ * `git write-tree` here would cost a spawn to produce a value nobody reads, and
60
+ * would invite the reader to believe the ephemeral store is shareable.
61
+ */
62
+ const EPHEMERAL_TREE_HASH = 'ephemeral';
63
+ /** What SQLite says when a statement names something the schema does not have. */
64
+ const NAME_NOT_FOUND = ['no such table:', 'no such column:'];
65
+ /**
66
+ * Compile every statement a run intends to ask, against the schema and NO rows,
67
+ * before anything is populated.
68
+ *
69
+ * ## 🔑 What this buys, measured
70
+ *
71
+ * SQLite resolves table and column names when a statement is *prepared*, not
72
+ * when it is stepped — so a typo is knowable before a single row exists. It was
73
+ * not knowable in practice, because the only place a statement met the schema
74
+ * was after the projection had been built. On a real adopter tree, `SELECT path,
75
+ * no_such_column â€Ķ` cost **8.3 s**, every millisecond of it spent building a
76
+ * projection the statement could never have read. The same typo now costs the
77
+ * price of an empty in-memory database — one extra `createSchema` into
78
+ * `:memory:`, which is the whole overhead this adds on the happy path.
79
+ *
80
+ * It also moves the KIND refusals — a second statement, an `ATTACH`, a `PRAGMA`
81
+ * — in front of the population, so a statement rejected for what it is costs no
82
+ * more than one rejected for what it names.
83
+ *
84
+ * ⚠ïļ **This is a pre-flight, not a second gate.** `ask` still compiles and runs
85
+ * the real statement against the real projection, and nothing here is trusted in
86
+ * place of that. A statement that compiles here can still fail there — SQLite
87
+ * resolves names against a schema, and this is the same schema, but a run-time
88
+ * error (a bad cast, an overflow) belongs to stepping and is unreachable from a
89
+ * prepare.
90
+ *
91
+ * ⚠ïļ It deliberately does not STEP anything. Stepping is where a check's
92
+ * unbounded cost lives, and a preflight that ran `WITH RECURSIVE â€Ķ` would hang
93
+ * before the run it exists to make cheap had begun.
94
+ *
95
+ * @param statements - Every statement the run will ask, in any order
96
+ * @throws The same legible failure `ask` throws, for the first statement that
97
+ * does not compile
98
+ */
99
+ export async function assertQueriesCompile(statements) {
100
+ if (statements.length === 0)
101
+ return;
102
+ const probe = await openEphemeralQueryStore();
103
+ try {
104
+ for (const sql of statements) {
105
+ try {
106
+ probe.assertCompiles(sql);
107
+ }
108
+ catch (error) {
109
+ throw new Error(describeQueryFailure(sql, error instanceof Error ? error.message : String(error)));
110
+ }
111
+ }
112
+ }
113
+ finally {
114
+ await probe.close();
115
+ }
116
+ }
117
+ /**
118
+ * Populate the tree, load it into something askable, and hand the caller a way
119
+ * to ask.
120
+ *
121
+ * @param options - The run
122
+ * @param options.root - Absolute corpus root
123
+ * @param options.logger - Where blob-stage refusals are reported (stderr, so a
124
+ * parseable document on stdout stays parseable)
125
+ * @param options.preflight - Every statement this run intends to ask, compiled
126
+ * against the empty schema BEFORE the population starts. See
127
+ * {@link assertQueriesCompile}
128
+ * @param work - Given the asker, where its rows came from, and how much of the
129
+ * tree they cover. The store is open for exactly this call and closed however
130
+ * it ends
131
+ * @returns Whatever `work` returned
132
+ */
133
+ export async function withQueriedProjection(options, work) {
134
+ const { root, logger } = options;
135
+ // 🔑 BEFORE the clock and before the population, because being before the
136
+ // population is the entire point — see {@link assertQueriesCompile}. It is an
137
+ // option rather than a step each verb remembers for the same reason everything
138
+ // else here is shared: a verb that forgot it would silently go back to paying
139
+ // a full population to learn about a typo, and nothing in its output would say
140
+ // so.
141
+ await assertQueriesCompile(options.preflight ?? []);
142
+ // ðŸšĻ OUTSIDE `withPopulationCache`, and it must stay outside. That helper
143
+ // awaits `openPopulationCache` — a `git write-tree` spawn plus the backend's
144
+ // dynamic import and `openSqliteProjectionStore()` — BEFORE it invokes the
145
+ // callback below, and it pays that cost ONLY when a store is selected. A clock
146
+ // started inside the callback therefore drops the store's own setup out of the
147
+ // measurement on precisely the arm the number is used to praise. See
148
+ // `populationMs` for what that shipped as.
149
+ //
150
+ // What is NOT in the span, deliberately: `withPopulationCache`'s `finally`,
151
+ // which closes the opened cache AFTER `work` returns. A span that ends before
152
+ // `work` begins cannot contain it, and stretching the span past `work` would
153
+ // fold the caller's statements into a number whose entire purpose is to be
154
+ // read against them. The close is a handle release on an already-open
155
+ // database, not population.
156
+ let contributorRecords = 0;
157
+ const populationStart = performance.now();
158
+ // The file-backed store, when one is selected, and ONLY as a population cache.
159
+ // Its rows are never queried — see the header.
160
+ return withPopulationCache({ root }, async (cache) => {
161
+ // The cache tell. `populate()` short-circuits a hit before any contributor
162
+ // is constructed, so this staying at zero is the ONLY observable difference
163
+ // between a served population and a re-derived one. Declared with the clock
164
+ // above rather than here so the two cannot drift apart when one moves.
165
+ const gitTracker = await gitTrackerForProjectRoot(root);
166
+ const projection = await buildResourceProjection({
167
+ root,
168
+ ...populationWiring(logger, gitTracker, cache, root),
169
+ onContributorTiming: () => {
170
+ contributorRecords += 1;
171
+ },
172
+ });
173
+ // ONE tree, in a database nothing else can reach, built fresh for this call.
174
+ const store = await openEphemeralQueryStore();
175
+ try {
176
+ // The key is read OFF the projection rather than re-derived from the root.
177
+ // The driver mints `roots.id` with `rootIdFor` and every
178
+ // `resolution_contexts.rootId` is a foreign key into it, so taking it from
179
+ // the rows means the key provably describes them — a second derivation
180
+ // could drift from the first and file rows under an id they do not carry.
181
+ const rootId = projection.roots[0]?.id;
182
+ if (rootId === undefined) {
183
+ throw new Error('The population produced no root row, so there is no id to file its extent under.'
184
+ + ' This is a driver invariant rather than a user error — `populate()` adds exactly'
185
+ + ' one, and a projection without it cannot be stored or queried.');
186
+ }
187
+ const { blobs, extent } = splitProjectionByScope(projection);
188
+ await store.writeBlobFacts(blobs);
189
+ await store.writeExtent({ rootId, treeHash: EPHEMERAL_TREE_HASH }, extent);
190
+ // The shared setup is done. Everything after this line is the caller's.
191
+ const populationMs = performance.now() - populationStart;
192
+ const ask = (sql, ...parameters) => {
193
+ try {
194
+ return store.query(sql, ...parameters);
195
+ }
196
+ catch (error) {
197
+ throw new Error(describeQueryFailure(sql, error instanceof Error ? error.message : String(error)));
198
+ }
199
+ };
200
+ return await work(ask, { population: contributorRecords === 0 ? 'store' : 'derived', populationMs },
201
+ // Read off the PROJECTION rather than counted back out of the store with
202
+ // a `SELECT COUNT(*)`: a count that travelled through the same `ask` the
203
+ // caller's statements do would be broken by the very schema drift it
204
+ // exists to survive, and it is the population's size either way.
205
+ { membersEnumerated: projection.resourceRealizations.length });
206
+ }
207
+ finally {
208
+ // Closed however the work ends. An in-memory database is reclaimed with the
209
+ // process either way, but a command that runs several of these in one
210
+ // process would otherwise hold every one of them open.
211
+ await store.close();
212
+ }
213
+ });
214
+ }
215
+ /**
216
+ * Turn a rejected statement into a message that names the surface it missed.
217
+ *
218
+ * ## Why this wrapper exists
219
+ *
220
+ * VAT ships no schema version, by standing rule — the *cache* is safe across a
221
+ * shape change because its digest self-invalidates, but submitted SQL is not: it
222
+ * simply breaks. Pre-1.0 that is acceptable. A raw SQLite error reaching the
223
+ * user is not, because `no such column: contentHash` says nothing about what the
224
+ * column is called now. It matters more for a CHECK than for a query: a query's
225
+ * author is at the keyboard, while a check's author wrote it months ago and the
226
+ * person reading the failure is someone else.
227
+ *
228
+ * ⚠ïļ **A legibility wrapper, not a validator.** It does not parse SQL and does
229
+ * not check a statement before running it — it reacts to a failure by listing
230
+ * what the query COULD have named. When the statement mentions a known table,
231
+ * that table's columns are listed, which is the case that actually answers "what
232
+ * moved"; otherwise the table names are, which at least answers "what is there".
233
+ *
234
+ * ðŸŠĪ **Only a name that was not found gets the listing.** The engine also refuses
235
+ * a write and this backend refuses a second statement, and neither is answered by
236
+ * a column list — appending one says the problem is the schema when the problem
237
+ * is what the caller asked for. A wrapper that decorates every failure identically
238
+ * teaches the reader to skip the decoration, which costs the case it was written for.
239
+ *
240
+ * Matching is a plain lowercase substring test rather than a regex: the input is
241
+ * user text, and a pattern built from it is both a lint failure here and a
242
+ * needless hazard.
243
+ *
244
+ * @param sql - The statement that was submitted
245
+ * @param message - What the engine said
246
+ * @returns The message to surface, with the queryable surface appended when the
247
+ * failure was a name this projection does not have
248
+ */
249
+ export function describeQueryFailure(sql, message) {
250
+ if (!NAME_NOT_FOUND.some((prefix) => message.includes(prefix)))
251
+ return message;
252
+ const lowered = sql.toLowerCase();
253
+ const named = Object.values(PROJECTION_TABLES).filter((spec) => lowered.includes(spec.name.toLowerCase()));
254
+ const surface = named.length > 0
255
+ ? named.map((spec) => ` ${spec.name}(${spec.columns.join(', ')})`).join('\n')
256
+ : Object.values(PROJECTION_TABLES).map((spec) => ` ${spec.name}`).join('\n');
257
+ const heading = named.length > 0
258
+ ? 'The tables this statement names hold these columns:'
259
+ : 'The projection holds these tables:';
260
+ return `${message}\n\n${heading}\n${surface}`;
261
+ }
262
+ //# sourceMappingURL=projection-query.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"projection-query.js","sourceRoot":"","sources":["../../src/utils/projection-query.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAE9C,OAAO,EACL,uBAAuB,EACvB,iBAAiB,EACjB,sBAAsB,GACvB,MAAM,+BAA+B,CAAC;AAEvC,OAAO,EAAE,wBAAwB,EAAE,MAAM,uCAAuC,CAAC;AAGjF,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,uBAAuB,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAErF;;;;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