@mnmal-ai/substrate-nl 1.0.0-alpha.2 → 1.0.0-alpha.20

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.
@@ -0,0 +1,3710 @@
1
+ import { METADATA_AUTHOR_FIELDS, METADATA_FILTER_FIELDS, ROW_POLICY_BLOCKS_WALK, WALKS_NEED_PARTITIONED, WALKS_UNSUPPORTED_STORE, defineBootstrap, error400, jsonResponse, parseJsonBody, trimTrailingSlashes } from "@mnmal-ai/substrate/sdk";
2
+ import { z } from "zod";
3
+ import { createHash } from "node:crypto";
4
+ import { FRAMES_JSON_MIME, encodeStreamFrame, framesEncodingFromAccept } from "@mnmal-ai/substrate/pack";
5
+
6
+ //#region src/own.ts
7
+ /**
8
+ * A lookup into a plain-object record by a user-supplied key. Inherited
9
+ * names (`constructor`, `__proto__`, `toString`) are not entries.
10
+ */
11
+ function own(rec, key) {
12
+ return rec !== void 0 && Object.hasOwn(rec, key) ? rec[key] : void 0;
13
+ }
14
+
15
+ //#endregion
16
+ //#region src/pack/words.ts
17
+ /** `AgentMessage` -> ['agent', 'message']; `shortId` -> ['short', 'id']. */
18
+ function splitWords(name) {
19
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").toLowerCase().split(/[\s_-]+/).filter((w) => w.length > 0);
20
+ }
21
+ /** English plural for a lower-case noun, by suffix rule. */
22
+ function pluralize(word) {
23
+ if (/(s|x|z|ch|sh)$/.test(word)) return `${word}es`;
24
+ if (/[^aeiou]y$/.test(word)) return `${word.slice(0, -1)}ies`;
25
+ return `${word}s`;
26
+ }
27
+ /** Sorted, de-duplicated. */
28
+ function uniqueSorted(xs) {
29
+ return [...new Set(xs)].sort();
30
+ }
31
+
32
+ //#endregion
33
+ //#region src/rulings/schema.ts
34
+ /**
35
+ * Rulings arrive from two places: declared by the namespace owner in
36
+ * `defineNamespace(..., { annotations: { nl } })`, and overridden by the
37
+ * operator in `substrate-nl.config.json`. Both are validated here. Bad declared
38
+ * rulings are dropped with a warning rather than failing the boot: one
39
+ * namespace's typo must not take NL down for every namespace, and must not
40
+ * pass silently either.
41
+ */
42
+ const ValueAliasSchema = z.object({
43
+ type: z.string().min(1),
44
+ field: z.string().min(1),
45
+ in: z.array(z.string()).optional(),
46
+ eq: z.string().optional(),
47
+ startsWith: z.string().optional(),
48
+ contains: z.string().optional()
49
+ }).strict().refine((v) => [
50
+ v.in,
51
+ v.eq,
52
+ v.startsWith,
53
+ v.contains
54
+ ].filter((x) => x !== void 0).length === 1, { message: "a value alias names exactly one of in, eq, startsWith, contains" });
55
+ const norm = (p) => p.trim().replace(/\s+/g, " ").toLowerCase();
56
+ const FieldPhraseSchema = z.object({
57
+ field: z.string().min(1).optional(),
58
+ value: z.unknown().optional(),
59
+ exclude: z.record(z.string(), z.unknown()).optional(),
60
+ select: z.union([z.object({ sub: z.tuple([z.string(), z.string()]) }).strict(), z.object({ div: z.tuple([z.string(), z.string()]) }).strict()]).optional(),
61
+ pick: z.enum([
62
+ "latest",
63
+ "max",
64
+ "min"
65
+ ]).optional()
66
+ }).strict().refine((v) => v.field !== void 0 || v.value === void 0 && v.exclude === void 0, { message: "value and exclude require field" }).refine((v) => v.field !== void 0 || v.select !== void 0 || v.pick !== void 0, { message: "an entry needs at least one of field, select, pick" });
67
+ const FieldPhrasesSchema = z.record(z.string(), FieldPhraseSchema).transform((rec, ctx) => {
68
+ const out = {};
69
+ for (const [phrase, entry] of Object.entries(rec)) {
70
+ const key = norm(phrase);
71
+ if (Object.hasOwn(out, key)) {
72
+ ctx.addIssue({
73
+ code: "custom",
74
+ message: `two phrases normalise to '${key}'`
75
+ });
76
+ return z.NEVER;
77
+ }
78
+ out[key] = entry;
79
+ }
80
+ return out;
81
+ });
82
+ const record = z.record(z.string(), z.string());
83
+ const NamespaceRulingsSchema = z.object({
84
+ fieldPhrases: FieldPhrasesSchema.optional(),
85
+ unscopedTypes: z.array(z.string()).optional(),
86
+ typeAliases: record.optional(),
87
+ fieldAliases: record.optional(),
88
+ liveStatus: record.optional(),
89
+ timeField: record.optional(),
90
+ typeNotes: record.optional(),
91
+ valueAliases: z.record(z.string(), z.array(ValueAliasSchema)).optional(),
92
+ typeExcludes: z.record(z.string(), z.record(z.string(), z.unknown())).optional()
93
+ }).strict();
94
+ /** Per top-level key: records merge entry-by-entry (override wins), arrays replace. */
95
+ function mergeRulings(declared, override) {
96
+ if (override === void 0) return declared;
97
+ const out = { ...declared };
98
+ for (const [key, value] of Object.entries(override)) {
99
+ const prior = out[key];
100
+ out[key] = Array.isArray(value) || prior === void 0 || Array.isArray(prior) ? value : {
101
+ ...prior,
102
+ ...value
103
+ };
104
+ }
105
+ return out;
106
+ }
107
+ const COMBINATORS = [
108
+ "AND",
109
+ "OR",
110
+ "NOT"
111
+ ];
112
+ /** Field names an `exclude` clause names, walked through AND/OR/NOT. Structural only: operator spellings are the engine's to refuse at query time. */
113
+ function whereFields(w, out) {
114
+ if (Array.isArray(w)) for (const x of w) whereFields(x, out);
115
+ else if (typeof w === "object" && w !== null) for (const [k, v] of Object.entries(w)) if (COMBINATORS.includes(k)) whereFields(v, out);
116
+ else out.push(k);
117
+ }
118
+ /** Why a `fieldPhrases` entry does not fit the schema, or undefined. */
119
+ function phraseProblem(schema, e) {
120
+ const types = /* @__PURE__ */ new Set();
121
+ const refs = [...e.field !== void 0 ? [e.field] : [], ...e.select ? Object.values(e.select)[0] ?? [] : []];
122
+ for (const r of refs) {
123
+ const dot = r.indexOf(".");
124
+ const type = dot < 0 ? r : r.slice(0, dot);
125
+ const field = dot < 0 ? "" : r.slice(dot + 1);
126
+ const t = Object.hasOwn(schema.types, type) ? schema.types[type] : void 0;
127
+ if (t === void 0) return `unknown type '${type}'`;
128
+ if (!Object.hasOwn(t.fields, field)) return `unknown field '${type}.${field}'`;
129
+ types.add(type);
130
+ }
131
+ if (types.size > 1) return `refers to more than one type (${[...types].join(", ")})`;
132
+ const [type] = types;
133
+ if (e.exclude !== void 0 && type !== void 0) return excludeProblem(schema, type, e.exclude);
134
+ }
135
+ /** Why an exclude clause does not fit `type`, or undefined. */
136
+ function excludeProblem(schema, type, exclude) {
137
+ const names = [];
138
+ whereFields(exclude, names);
139
+ const fields = schema.types[type]?.fields ?? {};
140
+ const bad = names.find((n) => !n.startsWith("_") && !Object.hasOwn(fields, n) && !Object.hasOwn(METADATA_FILTER_FIELDS, n) && !Object.hasOwn(METADATA_AUTHOR_FIELDS, n));
141
+ return bad !== void 0 ? `exclude names unknown field '${type}.${bad}'` : void 0;
142
+ }
143
+ /** The effective rulings for one namespace's schema, plus anything that was dropped. */
144
+ function readRulings(schema, override) {
145
+ const warnings = [];
146
+ let declared = {};
147
+ const raw = schema.annotations?.nl;
148
+ if (raw !== void 0) {
149
+ const parsed = NamespaceRulingsSchema.safeParse(raw);
150
+ if (parsed.success) declared = parsed.data;
151
+ else {
152
+ const where = parsed.error.issues.map((i) => i.path.join(".") || "(root)").join(", ");
153
+ warnings.push(`declared rulings are invalid and were ignored (${where})`);
154
+ }
155
+ }
156
+ let normOverride = override;
157
+ if (override?.fieldPhrases !== void 0) {
158
+ const p = FieldPhrasesSchema.safeParse(override.fieldPhrases);
159
+ const { fieldPhrases: _drop, ...rest } = override;
160
+ if (p.success) normOverride = {
161
+ ...rest,
162
+ fieldPhrases: p.data
163
+ };
164
+ else {
165
+ normOverride = rest;
166
+ warnings.push(`override fieldPhrases are invalid and were ignored (${p.error.issues.map((i) => i.message).join("; ")})`);
167
+ }
168
+ }
169
+ const rulings = mergeRulings(declared, normOverride);
170
+ if (rulings.fieldPhrases !== void 0) {
171
+ const kept = {};
172
+ for (const [phrase, entry] of Object.entries(rulings.fieldPhrases)) {
173
+ const problem = phraseProblem(schema, entry);
174
+ if (problem === void 0) kept[phrase] = entry;
175
+ else warnings.push(`fieldPhrases '${phrase}' was ignored: ${problem}`);
176
+ }
177
+ rulings.fieldPhrases = kept;
178
+ }
179
+ if (rulings.typeExcludes !== void 0) {
180
+ const kept = {};
181
+ for (const [type, where] of Object.entries(rulings.typeExcludes)) {
182
+ const problem = Object.hasOwn(schema.types, type) ? excludeProblem(schema, type, where) : `unknown type '${type}'`;
183
+ if (problem === void 0) kept[type] = where;
184
+ else warnings.push(`typeExcludes '${type}' was ignored: ${problem}`);
185
+ }
186
+ rulings.typeExcludes = kept;
187
+ }
188
+ return {
189
+ rulings,
190
+ warnings
191
+ };
192
+ }
193
+
194
+ //#endregion
195
+ //#region src/parse/time.ts
196
+ const WEEKDAYS = [
197
+ "sunday",
198
+ "monday",
199
+ "tuesday",
200
+ "wednesday",
201
+ "thursday",
202
+ "friday",
203
+ "saturday"
204
+ ];
205
+ /** An ISO-8601 date-time with an offset: the only accepted `asOf`. */
206
+ const AS_OF = /^(\d{4})-(\d{2})-(\d{2})T[\d:.]+(Z|[+-]\d{2}:\d{2})$/;
207
+ /** True when `asOf` is an ISO-8601 date-time with an offset naming a real instant. */
208
+ function validAsOf(asOf) {
209
+ if (typeof asOf !== "string") return false;
210
+ const m = AS_OF.exec(asOf);
211
+ if (m === null || !Number.isFinite(Date.parse(asOf))) return false;
212
+ const [y, mo, d] = [
213
+ Number(m[1]),
214
+ Number(m[2]),
215
+ Number(m[3])
216
+ ];
217
+ return new Date(Date.UTC(y, mo - 1, d)).getUTCDate() === d;
218
+ }
219
+ /**
220
+ * The range a time phrase names, relative to `asOf` and in its offset:
221
+ * today, yesterday, this/last week (weeks start Monday), this/last month,
222
+ * rolling "past <unit>" and "last N <units>", "since <weekday>"; and explicit
223
+ * dates (see `explicitRange`). Null when the phrase is not a time phrase.
224
+ */
225
+ function rangeFor(phrase, asOf) {
226
+ const m = AS_OF.exec(asOf);
227
+ if (m === null) throw new Error(`asOf must be ISO-8601 with an offset: ${asOf}`);
228
+ const [, y, mo, d, offset] = m;
229
+ const today = Date.UTC(Number(y), Number(mo) - 1, Number(d));
230
+ const day = 864e5;
231
+ const at = (utcMidnight) => `${new Date(utcMidnight).toISOString().slice(0, 10)}T00:00:00${offset === "Z" ? "Z" : offset}`;
232
+ const weekday = new Date(today).getUTCDay();
233
+ const monday = today - (weekday + 6) % 7 * day;
234
+ const monthStart = Date.UTC(Number(y), Number(mo) - 1, 1);
235
+ const nextMonth = Date.UTC(Number(y), Number(mo), 1);
236
+ const lastMonth = Date.UTC(Number(y), Number(mo) - 2, 1);
237
+ switch (phrase) {
238
+ case "today": return {
239
+ gte: at(today),
240
+ lt: at(today + day)
241
+ };
242
+ case "yesterday": return {
243
+ gte: at(today - day),
244
+ lt: at(today)
245
+ };
246
+ case "this week": return {
247
+ gte: at(monday),
248
+ lt: at(monday + 7 * day)
249
+ };
250
+ case "last week": return {
251
+ gte: at(monday - 7 * day),
252
+ lt: at(monday)
253
+ };
254
+ case "this month": return {
255
+ gte: at(monthStart),
256
+ lt: at(nextMonth)
257
+ };
258
+ case "last month": return {
259
+ gte: at(lastMonth),
260
+ lt: at(monthStart)
261
+ };
262
+ }
263
+ const rolling = /^(?:past|last) (\d+ )?(day|week|month|year)s?$/.exec(phrase);
264
+ if (rolling !== null && (rolling[1] !== void 0 || phrase.startsWith("past"))) {
265
+ const n = rolling[1] === void 0 ? 1 : Number(rolling[1]);
266
+ const unit = rolling[2];
267
+ const back = new Date(today);
268
+ if (unit === "day") back.setUTCDate(back.getUTCDate() - n);
269
+ if (unit === "week") back.setUTCDate(back.getUTCDate() - 7 * n);
270
+ if (unit === "month") back.setUTCMonth(back.getUTCMonth() - n);
271
+ if (unit === "year") back.setUTCFullYear(back.getUTCFullYear() - n);
272
+ return {
273
+ gte: at(back.getTime()),
274
+ lt: at(today + day)
275
+ };
276
+ }
277
+ const since = /^since (\w+)$/.exec(phrase);
278
+ if (since !== null) {
279
+ const target = WEEKDAYS.indexOf(since[1]);
280
+ if (target < 0) return null;
281
+ return {
282
+ gte: at(today - (weekday - target + 7) % 7 * day),
283
+ lt: at(today + day)
284
+ };
285
+ }
286
+ return explicitRange(phrase, today, at, offset);
287
+ }
288
+ const MONTHS = [
289
+ "january",
290
+ "february",
291
+ "march",
292
+ "april",
293
+ "may",
294
+ "june",
295
+ "july",
296
+ "august",
297
+ "september",
298
+ "october",
299
+ "november",
300
+ "december"
301
+ ];
302
+ const DAY_MS = 864e5;
303
+ /**
304
+ * Explicit dates, always after a lead word: "on D" (that day), "from D to D" and
305
+ * "between D and D" (inclusive of the last day), "since D" / "after D" (from
306
+ * D / the day after), "before D" / "until D" (before D / through D). A date
307
+ * is ISO `YYYY-MM-DD`, an ISO date-time (an exact instant), or a month name
308
+ * (full, three-letter, or "sept") with a day, optional ordinal and optional year, in
309
+ * either order. A month-day without a year is the most recent one not after
310
+ * `today`. An invalid date is not a date.
311
+ */
312
+ function explicitRange(phrase, today, at, offset) {
313
+ const operand = (words) => {
314
+ if (words.length === 1) {
315
+ const w = words[0];
316
+ const iso = /^(\d{4})-(\d{2})-(\d{2})$/.exec(w);
317
+ if (iso !== null) return dayOf(Number(iso[1]), Number(iso[2]), Number(iso[3]));
318
+ const dt = /^(\d{4})-(\d{2})-(\d{2})t((?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?)(z|[+-](?:[01]\d|2[0-3]):[0-5]\d)?$/.exec(w);
319
+ if (dt === null || dayOf(Number(dt[1]), Number(dt[2]), Number(dt[3])) === null) return null;
320
+ const instant = `${dt[1]}-${dt[2]}-${dt[3]}T${dt[4]}${dt[5] === void 0 ? offset : dt[5].toUpperCase()}`;
321
+ return {
322
+ start: instant,
323
+ end: instant
324
+ };
325
+ }
326
+ if (words.length !== 2 && words.length !== 3) return null;
327
+ const [a = "", b = "", year] = words;
328
+ const month = (w) => MONTHS.findIndex((m) => w === m || w.length === 3 && m.startsWith(w)) + 1 || (w === "sept" ? 9 : 0);
329
+ const dom = (w) => /^(\d{1,2})(?:st|nd|rd|th)?$/.exec(w)?.[1];
330
+ const [mo, d] = month(a) > 0 ? [month(a), dom(b)] : [month(b), dom(a)];
331
+ if (mo === 0 || d === void 0) return null;
332
+ if (year !== void 0) return /^\d{4}$/.test(year) ? dayOf(Number(year), mo, Number(d)) : null;
333
+ for (let y = new Date(today).getUTCFullYear(), n = 0; n < 8; y--, n++) {
334
+ const t = Date.UTC(y, mo - 1, Number(d));
335
+ if (t <= today && valid(y, mo, Number(d))) return {
336
+ start: at(t),
337
+ end: at(t + DAY_MS)
338
+ };
339
+ }
340
+ return null;
341
+ };
342
+ const valid = (y, mo, d) => {
343
+ const t = new Date(Date.UTC(y, mo - 1, d));
344
+ return t.getUTCFullYear() === y && t.getUTCMonth() === mo - 1 && t.getUTCDate() === d;
345
+ };
346
+ const dayOf = (y, mo, d) => {
347
+ if (!valid(y, mo, d)) return null;
348
+ const t = Date.UTC(y, mo - 1, d);
349
+ return {
350
+ start: at(t),
351
+ end: at(t + DAY_MS)
352
+ };
353
+ };
354
+ const [head = "", ...rest] = phrase.split(" ");
355
+ if (head === "from" || head === "between") {
356
+ const sep = head === "from" ? "to" : "and";
357
+ const i = rest.indexOf(sep);
358
+ if (i < 0) return null;
359
+ const x = operand(rest.slice(0, i));
360
+ const y = operand(rest.slice(i + 1));
361
+ if (x === null || y === null || Date.parse(y.end) <= Date.parse(x.start)) return null;
362
+ return {
363
+ gte: x.start,
364
+ lt: y.end
365
+ };
366
+ }
367
+ const o = operand(rest);
368
+ if (o === null) return null;
369
+ switch (head) {
370
+ case "on": return o.start === o.end ? null : {
371
+ gte: o.start,
372
+ lt: o.end
373
+ };
374
+ case "since": return { gte: o.start };
375
+ case "after": return { gte: o.end };
376
+ case "before": return { lt: o.start };
377
+ case "until": return { lt: o.end };
378
+ }
379
+ return null;
380
+ }
381
+
382
+ //#endregion
383
+ //#region src/parse/compare.ts
384
+ const NUMBER = /^\$?(\d+(?:\.\d+)?)$/;
385
+ /** The comparison phrase starting at `words[0]`, or null. */
386
+ function parseComparison(words) {
387
+ const [a = "", b = "", c = ""] = words;
388
+ const pct = /^(\d+(?:\.\d+)?)%$/.exec(a);
389
+ if (pct !== null) {
390
+ const n = Number(pct[1]);
391
+ const up = (100 + n) / 100;
392
+ if (b === "over" || b === "above") return {
393
+ op: "gte",
394
+ times: up,
395
+ length: 2
396
+ };
397
+ if (b === "more" && c === "than") return {
398
+ op: "gte",
399
+ times: up,
400
+ length: 3
401
+ };
402
+ const length = c === "than" ? 3 : 2;
403
+ if (b === "slower") return {
404
+ op: "gte",
405
+ times: up,
406
+ length
407
+ };
408
+ if (b === "faster") return n < 100 ? {
409
+ op: "lte",
410
+ times: (100 - n) / 100,
411
+ length
412
+ } : {
413
+ op: "lte",
414
+ length,
415
+ invalid: `${n}% faster leaves no time to compare against`
416
+ };
417
+ return null;
418
+ }
419
+ const lead = a === "at" && b === "least" ? 2 : 0;
420
+ const w = words[lead] ?? "";
421
+ const mult = /^(\d+(?:\.\d+)?)(?:x|×)$/.exec(w);
422
+ if (mult !== null) return {
423
+ op: "gte",
424
+ times: Number(mult[1]),
425
+ length: lead + 1
426
+ };
427
+ const next = words[lead + 1];
428
+ if (/^\d+(?:\.\d+)?$/.test(w) && (next === "times" || next === "x" || next === "×")) return {
429
+ op: "gte",
430
+ times: Number(w),
431
+ length: lead + 2
432
+ };
433
+ if (lead > 0) return null;
434
+ const amount = /^\$(\d+(?:\.\d+)?)$/.exec(a);
435
+ if (amount !== null) {
436
+ const plus = Number(amount[1]);
437
+ if (b === "over") return {
438
+ op: "gte",
439
+ plus,
440
+ length: 2
441
+ };
442
+ if (b === "more" && c === "than") return {
443
+ op: "gte",
444
+ plus,
445
+ length: 3
446
+ };
447
+ return null;
448
+ }
449
+ const head = a === "over" ? ["gt", 1] : a === "under" ? ["lt", 1] : a === "more" && b === "than" ? ["gt", 2] : a === "less" && b === "than" ? ["lt", 2] : null;
450
+ if (head === null) return null;
451
+ const [op, length] = head;
452
+ const lit = NUMBER.exec(words[length] ?? "");
453
+ return lit !== null ? {
454
+ op,
455
+ value: Number(lit[1]),
456
+ length: length + 1
457
+ } : {
458
+ op,
459
+ length
460
+ };
461
+ }
462
+
463
+ //#endregion
464
+ //#region src/parse/walks.ts
465
+ /** The plan note for a type's default exclusion that yielded to the question's own filter on `field`. */
466
+ function defaultYield(type, field, path = ["where"]) {
467
+ return {
468
+ path: [...path, `ruling:${type} default exclude (yields to the question's ${field} filter)`],
469
+ kind: "filter",
470
+ served: false
471
+ };
472
+ }
473
+ /** Every crossRef hop out of `type`, both directions, inside the pack's namespace. */
474
+ function hopsFrom(pack, type) {
475
+ const out = [];
476
+ for (const [owner, t] of Object.entries(pack.types)) for (const [field, f] of Object.entries(t.fields)) {
477
+ const target = f.kind === "crossRef" ? f.target : void 0;
478
+ if (target === void 0 || target.namespace !== pack.namespace) continue;
479
+ if (own(pack.types, target.type) === void 0) continue;
480
+ if (owner === type) out.push({
481
+ dir: "out",
482
+ from: type,
483
+ owner,
484
+ field,
485
+ to: target.type
486
+ });
487
+ if (target.type === type) out.push({
488
+ dir: "in",
489
+ from: type,
490
+ owner,
491
+ field,
492
+ to: owner
493
+ });
494
+ }
495
+ return out;
496
+ }
497
+ /** All shortest crossRef paths from `from` to `to` (BFS, both directions, no type revisited). */
498
+ function findPaths(pack, from, to, maxHops = 3) {
499
+ if (from === to) return [[]];
500
+ let frontier = [[]];
501
+ for (let depth = 1; depth <= maxHops; depth++) {
502
+ const next = [];
503
+ for (const p of frontier) {
504
+ const at = p[p.length - 1]?.to ?? from;
505
+ for (const h of hopsFrom(pack, at)) {
506
+ if (h.to === from || p.some((x) => x.to === h.to)) continue;
507
+ next.push([...p, h]);
508
+ }
509
+ }
510
+ const done = next.filter((p) => p[p.length - 1]?.to === to);
511
+ if (done.length > 0) return done;
512
+ frontier = next;
513
+ }
514
+ return [];
515
+ }
516
+ function pathLabel(ns, p) {
517
+ return p.map((h) => h.dir === "in" ? `in ${ns}/${h.owner}.${h.field}` : `out ${h.field}`).join(" > ");
518
+ }
519
+ const PICKED = {
520
+ latest: "latest",
521
+ max: "highest",
522
+ min: "lowest"
523
+ };
524
+ const PICK_WORDS = {
525
+ latest: "latest",
526
+ current: "latest",
527
+ "most recent": "latest",
528
+ highest: "max",
529
+ best: "max",
530
+ lowest: "min",
531
+ cheapest: "min"
532
+ };
533
+ const COMPUTED_WORDS = /* @__PURE__ */ new Set([
534
+ "margin",
535
+ "spread",
536
+ "gap"
537
+ ]);
538
+ /** A comparative the lexicon does not cover. */
539
+ const COMPARATIVE = /%$|^\d+(?:\.\d+)?(?:x|×)$|^(?:than|twice|double|half|triple)$/;
540
+ const text = (tokens, [s, e]) => tokens.slice(s, e + 1).map((t) => t.text).join(" ");
541
+ const range = ([s, e]) => Array.from({ length: e - s + 1 }, (_, k) => s + k);
542
+ const take = (tokens, [s, e]) => {
543
+ for (let i = s; i <= e; i++) tokens[i].used = true;
544
+ };
545
+ /**
546
+ * Claims field phrases, pick words, "by <computed>" and comparisons. Only a
547
+ * namespace that declares `fieldPhrases` composes walks, so nothing changes
548
+ * for one that does not.
549
+ */
550
+ function claimWalkParts(tokens, rulings, glue) {
551
+ const claims = {
552
+ phrases: [],
553
+ compares: [],
554
+ picks: [],
555
+ computed: [],
556
+ dropped: []
557
+ };
558
+ const table = rulings.fieldPhrases;
559
+ if (table === void 0 || Object.keys(table).length === 0) return claims;
560
+ for (let n = 6; n >= 1; n--) for (let i = 0; i + n <= tokens.length; i++) {
561
+ const at = [i, i + n - 1];
562
+ if (tokens.slice(i, i + n).some((t) => t.used)) continue;
563
+ const entry = own(table, text(tokens, at));
564
+ if (entry === void 0) continue;
565
+ take(tokens, at);
566
+ const dot = entry.field?.indexOf(".") ?? -1;
567
+ claims.phrases.push({
568
+ span: text(tokens, at),
569
+ at,
570
+ entry,
571
+ ...entry.field !== void 0 && dot > 0 ? {
572
+ type: entry.field.slice(0, dot),
573
+ field: entry.field.slice(dot + 1)
574
+ } : {}
575
+ });
576
+ }
577
+ claims.phrases.sort((x, y) => x.at[0] - y.at[0]);
578
+ for (const p of claims.phrases) {
579
+ const s = p.at[0];
580
+ for (const [word, kind] of Object.entries(PICK_WORDS)) {
581
+ const at = [s - word.split(" ").length, s - 1];
582
+ if (at[0] < 0 || tokens.slice(at[0], s).some((t) => t.used)) continue;
583
+ if (text(tokens, at) !== word) continue;
584
+ take(tokens, at);
585
+ claims.picks.push({
586
+ span: word,
587
+ at,
588
+ phrase: p,
589
+ kind
590
+ });
591
+ break;
592
+ }
593
+ }
594
+ for (const p of claims.phrases) {
595
+ if (p.entry.select === void 0) continue;
596
+ const by = tokens[p.at[0] - 1];
597
+ if (by?.text === "by" && !by.used) {
598
+ by.used = true;
599
+ claims.computed.push(p);
600
+ } else claims.dropped.push({
601
+ span: p.span,
602
+ reason: `"${p.span}" is a derived value; it orders a list only as "by ${p.span}"`,
603
+ kind: "filter"
604
+ });
605
+ }
606
+ tokens.forEach((t, i) => {
607
+ const next = tokens[i + 1];
608
+ if (t.text !== "by" || t.used || next === void 0 || next.used) return;
609
+ if (!COMPUTED_WORDS.has(next.text)) return;
610
+ t.used = true;
611
+ next.used = true;
612
+ claims.dropped.push({
613
+ span: `by ${next.text}`,
614
+ reason: `no derived value "${next.text}" is declared for this namespace`,
615
+ kind: "order"
616
+ });
617
+ });
618
+ const phraseAt = (i) => claims.phrases.find((p) => p.at[0] === i);
619
+ for (let i = 0; i < tokens.length; i++) {
620
+ if (tokens[i]?.used === true) continue;
621
+ const cmp = parseComparison(tokens.slice(i).map((t) => t.text));
622
+ if (cmp === null) continue;
623
+ const at = [i, i + cmp.length - 1];
624
+ const usedAt = range(at).filter((k) => tokens[k]?.used === true);
625
+ const wordPhrase = usedAt.length === 1 ? phraseAt(usedAt[0]) : void 0;
626
+ if (usedAt.length > 0 && (wordPhrase === void 0 || wordPhrase.at[1] !== usedAt[0] || !/^(?:slower|faster)$/.test(wordPhrase.span))) continue;
627
+ let object;
628
+ if (cmp.value === void 0) {
629
+ const pickAt = new Set(claims.picks.flatMap((k) => range(k.at)));
630
+ let j = at[1] + 1;
631
+ while (j < tokens.length && phraseAt(j) === void 0) {
632
+ const t = tokens[j];
633
+ if (!(glue.has(t.text) && !t.used) && !pickAt.has(j)) break;
634
+ j++;
635
+ }
636
+ object = phraseAt(j);
637
+ if (object === void 0) continue;
638
+ }
639
+ const before = [...claims.phrases].reverse().find((p) => p.at[1] < i);
640
+ const adjacent = before !== void 0 && tokens.slice(before.at[1] + 1, i).every((t) => !t.used && glue.has(t.text)) && before.field !== void 0 && before.entry.value === void 0;
641
+ const subject = wordPhrase ?? (adjacent ? before : void 0);
642
+ for (let k = i; k <= at[1]; k++) tokens[k].used = true;
643
+ const span = text(tokens, at);
644
+ claims.compares.push({
645
+ span,
646
+ at,
647
+ cmp,
648
+ ...subject !== void 0 ? { subject } : {},
649
+ ...object !== void 0 ? { object } : {}
650
+ });
651
+ i = at[1];
652
+ }
653
+ return claims;
654
+ }
655
+ /** Comparatives the lexicon did not claim: dropped, never approximated. */
656
+ function dropComparatives(tokens, dropped) {
657
+ tokens.forEach((t, i) => {
658
+ if (t.used || !COMPARATIVE.test(t.text)) return;
659
+ const prev = tokens[i - 1];
660
+ const words = prev !== void 0 && !prev.used && t.text === "than" ? [prev, t] : [t];
661
+ for (const w of words) w.used = true;
662
+ dropped.push({
663
+ span: words.map((w) => w.text).join(" "),
664
+ reason: "this comparison is not in the comparison lexicon",
665
+ kind: "filter"
666
+ });
667
+ });
668
+ }
669
+ const filter = (clause, path, label) => ({
670
+ clause,
671
+ plan: [{
672
+ path: [...path, label],
673
+ kind: "filter",
674
+ served: false
675
+ }]
676
+ });
677
+ /** Clauses as one where: the clause itself, or an AND with plan paths re-rooted. */
678
+ function andOf(parts) {
679
+ if (parts.length === 0) return null;
680
+ if (parts.length === 1) return {
681
+ where: parts[0].clause,
682
+ plan: parts[0].plan
683
+ };
684
+ return {
685
+ where: { AND: parts.map((p) => p.clause) },
686
+ plan: parts.flatMap((p, i) => p.plan.map((c) => ({
687
+ ...c,
688
+ path: [
689
+ "AND",
690
+ String(i),
691
+ ...c.path
692
+ ]
693
+ })))
694
+ };
695
+ }
696
+ /** Binding names: the type name's capitals ("Listing" -> L, "CiRun" -> CR). */
697
+ function aliasFor(type, taken) {
698
+ const base = type.replace(/[^A-Z]/g, "") || type.slice(0, 1).toUpperCase();
699
+ let name = base;
700
+ for (let n = 2; taken.has(name); n++) name = `${base}${n}`;
701
+ taken.add(name);
702
+ return name;
703
+ }
704
+ function compose(input) {
705
+ const { pack, rulings, seed, claims } = input;
706
+ const ns = pack.namespace;
707
+ const dropped = [...claims.dropped];
708
+ const seedParts = [];
709
+ const walks = /* @__PURE__ */ new Map();
710
+ const dead = /* @__PURE__ */ new Set();
711
+ let clarify = null;
712
+ const timeField = (type) => own(rulings.timeField, type) ?? "createdAt";
713
+ const typeExclude = (type) => {
714
+ const where = own(rulings.typeExcludes, type);
715
+ return where === void 0 ? null : filter({ NOT: where }, ["NOT"], `ruling:${type} default exclude`);
716
+ };
717
+ const walkTo = (type, span) => {
718
+ const known = walks.get(type);
719
+ if (known !== void 0) return known;
720
+ if (dead.has(type)) return null;
721
+ const paths = findPaths(pack, seed, type);
722
+ if (paths.length === 0) {
723
+ dead.add(type);
724
+ dropped.push({
725
+ span,
726
+ reason: `no crossRef path from ${seed} to ${type} within 3 hops`,
727
+ kind: "filter"
728
+ });
729
+ return null;
730
+ }
731
+ if (paths.length > 1) {
732
+ clarify ??= `several equally short paths from ${seed} to ${type}: ${paths.map((p) => pathLabel(ns, p)).join("; ")}`;
733
+ dead.add(type);
734
+ return null;
735
+ }
736
+ const w = {
737
+ type,
738
+ path: paths[0],
739
+ filters: [],
740
+ window: [],
741
+ excludes: [typeExclude(type)].filter((x) => x !== null),
742
+ notes: [],
743
+ applied: /* @__PURE__ */ new Set()
744
+ };
745
+ walks.set(type, w);
746
+ return w;
747
+ };
748
+ /** Where a phrase's own clauses go: the seed, a walk, or nowhere (dropped). */
749
+ const home = (p) => {
750
+ if (p.type === void 0) return null;
751
+ if (p.type === seed) return { seed: true };
752
+ return walkTo(p.type, p.span);
753
+ };
754
+ const isWalk = (h) => !("seed" in h);
755
+ for (const p of claims.phrases) {
756
+ if (p.field === void 0 || p.type === void 0) continue;
757
+ const h = home(p);
758
+ if (h === null) continue;
759
+ if (isWalk(h) && h.applied.has(p.span)) continue;
760
+ const parts = [];
761
+ if (p.entry.value !== void 0) parts.push(filter({ [p.field]: { eq: p.entry.value } }, [p.field], `ruling:${p.span}`));
762
+ const excl = p.entry.exclude;
763
+ if (excl !== void 0) {
764
+ const part = filter({ NOT: excl }, ["NOT"], `ruling:${p.span}`);
765
+ if (isWalk(h)) h.excludes.push(part);
766
+ else seedParts.push(part);
767
+ }
768
+ if (isWalk(h)) {
769
+ h.filters.push(...parts);
770
+ h.applied.add(p.span);
771
+ } else seedParts.push(...parts);
772
+ }
773
+ const picked = /* @__PURE__ */ new Map();
774
+ for (const k of claims.picks) picked.set(k.phrase, k.kind);
775
+ for (const p of claims.phrases) {
776
+ if (p.type === void 0 || p.type === seed || p.field === void 0) continue;
777
+ const w = walks.get(p.type);
778
+ if (w === void 0) continue;
779
+ const kind = picked.get(p) ?? p.entry.pick;
780
+ if (kind === void 0) continue;
781
+ const source = picked.has(p) ? `"${claims.picks.find((k) => k.phrase === p)?.span}"` : "ruling";
782
+ const span = claims.picks.find((k) => k.phrase === p)?.span ?? p.span;
783
+ const pick = {
784
+ kind,
785
+ by: kind === "latest" ? timeField(p.type) : p.field,
786
+ source,
787
+ span
788
+ };
789
+ if (w.pick !== void 0 && (w.pick.kind !== pick.kind || w.pick.by !== pick.by)) {
790
+ clarify ??= `${w.pick.source} and ${pick.source} pick different ${p.type} rows`;
791
+ continue;
792
+ }
793
+ w.pick = pick;
794
+ }
795
+ let seedLatest;
796
+ let seedOrder;
797
+ for (const k of claims.picks) if (k.phrase.type === seed && k.kind === "latest") seedLatest = k.span;
798
+ else if (k.phrase.type === seed && (k.span === "highest" || k.span === "lowest") && k.phrase.entry.value === void 0) seedOrder = {
799
+ span: `${k.span} ${k.phrase.span}`,
800
+ dir: k.kind === "max" ? "desc" : "asc",
801
+ phrase: k.phrase
802
+ };
803
+ else if (k.phrase.type === seed) dropped.push({
804
+ span: `${k.span} ${k.phrase.span}`,
805
+ reason: `"${k.span}" picks one neighbour, and ${seed} is the type being asked about`,
806
+ kind: "order"
807
+ });
808
+ const mentionOf = /* @__PURE__ */ new Map();
809
+ const mention = (w, p, text) => {
810
+ const known = mentionOf.get(w);
811
+ if (known === void 0) mentionOf.set(w, {
812
+ at: p.at[0],
813
+ text
814
+ });
815
+ else if (known.at !== p.at[0]) clarify ??= `"${known.text}" and "${text}": one ${w.type} meeting both, or two different ${w.type} rows?`;
816
+ };
817
+ for (const c of claims.compares) {
818
+ if (c.cmp.invalid !== void 0) {
819
+ dropped.push({
820
+ span: c.span,
821
+ reason: c.cmp.invalid,
822
+ kind: "filter"
823
+ });
824
+ continue;
825
+ }
826
+ const s = c.subject;
827
+ if (s?.type === void 0 || s.field === void 0) {
828
+ dropped.push({
829
+ span: c.span,
830
+ reason: "no field phrase directly before it to compare",
831
+ kind: "filter"
832
+ });
833
+ continue;
834
+ }
835
+ const sh = home(s);
836
+ if (sh === null) {
837
+ dropped.push({
838
+ span: c.span,
839
+ reason: `its field "${s.span}" was dropped`,
840
+ kind: "filter"
841
+ });
842
+ continue;
843
+ }
844
+ let operand;
845
+ let kind = "filter";
846
+ if (c.cmp.value !== void 0) operand = c.cmp.value;
847
+ else {
848
+ const o = c.object;
849
+ if (o?.type === void 0 || o.field === void 0) {
850
+ dropped.push({
851
+ span: c.span,
852
+ reason: "nothing to compare against",
853
+ kind: "filter"
854
+ });
855
+ continue;
856
+ }
857
+ let ref;
858
+ if (o.type === seed) ref = `$.${o.field}`;
859
+ else {
860
+ if (o.type === s.type) {
861
+ dropped.push({
862
+ span: `${c.span} ${o.span}`,
863
+ reason: `comparing two fields of one ${o.type} is not expressible`,
864
+ kind: "filter"
865
+ });
866
+ continue;
867
+ }
868
+ const ow = walkTo(o.type, o.span);
869
+ if (ow === null) {
870
+ dropped.push({
871
+ span: c.span,
872
+ reason: `its operand "${o.span}" was dropped`,
873
+ kind: "filter"
874
+ });
875
+ continue;
876
+ }
877
+ mention(ow, o, `${c.span} ${o.span}`);
878
+ if (ow.path.length > 1 || ow.pick !== void 0) {
879
+ dropped.push({
880
+ span: `${c.span} ${o.span}`,
881
+ reason: ow.pick !== void 0 ? `a picked ${o.type} cannot be referenced` : `a comparison against a ${ow.path.length}-hop walk is not expressible`,
882
+ kind: "filter"
883
+ });
884
+ continue;
885
+ }
886
+ ref = `${o.type}\u0000${o.field}`;
887
+ }
888
+ operand = {
889
+ $ref: ref,
890
+ ...c.cmp.times !== void 0 ? { times: c.cmp.times } : {},
891
+ ...c.cmp.plus !== void 0 ? { plus: c.cmp.plus } : {}
892
+ };
893
+ kind = "ref";
894
+ }
895
+ const part = {
896
+ clause: { [s.field]: { [c.cmp.op]: operand } },
897
+ plan: [{
898
+ path: [
899
+ s.field,
900
+ c.cmp.op,
901
+ ...kind === "ref" ? [] : [`compare:${c.span}`]
902
+ ],
903
+ kind,
904
+ served: kind === "ref"
905
+ }]
906
+ };
907
+ if (isWalk(sh)) {
908
+ mention(sh, s, `${s.span} ${c.span}`);
909
+ sh.filters.push(part);
910
+ } else seedParts.push(part);
911
+ }
912
+ let timeOnSeed = input.time !== null;
913
+ if (input.time !== null) {
914
+ const t = input.time.at;
915
+ const dist = ([s, e]) => s > t[1] ? s - t[1] : e < t[0] ? t[0] - e : 0;
916
+ const near = /* @__PURE__ */ new Map();
917
+ const note = (type, at) => {
918
+ if (type === void 0) return;
919
+ near.set(type, Math.min(near.get(type) ?? Number.POSITIVE_INFINITY, dist(at)));
920
+ };
921
+ for (const p of claims.phrases) note(p.type, p.at);
922
+ for (const m of input.mentions) note(m.type, m.at);
923
+ const best = Math.min(...near.values());
924
+ const nearest = [...near].filter(([, d]) => d === best).map(([type]) => type);
925
+ if (nearest.length > 1) clarify ??= `"${input.time.span}" could window ${nearest.sort().join(" or ")}`;
926
+ else if (nearest.length === 1 && nearest[0] !== seed) {
927
+ const type = nearest[0];
928
+ const w = walkTo(type, input.time.span);
929
+ timeOnSeed = false;
930
+ if (w === null) dropped.push({
931
+ span: input.time.span,
932
+ reason: `it windows ${type}, which no walk from ${seed} reaches`,
933
+ kind: "filter"
934
+ });
935
+ else {
936
+ const field = timeField(type);
937
+ const ruled = own(rulings.timeField, type) !== void 0;
938
+ w.window.push(filter({ [field]: { ...input.time.range } }, [field], `window:${input.time.span}${ruled ? "" : ` on ${field} (default)`}`));
939
+ }
940
+ }
941
+ }
942
+ const params = {};
943
+ const plan = [];
944
+ for (const d of claims.computed) {
945
+ const spec = d.entry.select;
946
+ if (spec === void 0) continue;
947
+ const [op, operands] = Object.entries(spec)[0];
948
+ if (!operands.every((o) => o.startsWith(`${seed}.`))) {
949
+ dropped.push({
950
+ span: `by ${d.span}`,
951
+ reason: `"${d.span}" derives from fields of another type than ${seed}`,
952
+ kind: "order"
953
+ });
954
+ continue;
955
+ }
956
+ const name = d.span.replace(/[^a-z0-9]+(.)?/g, (_, ch) => (ch ?? "").toUpperCase());
957
+ if (own(pack.types, seed)?.fields !== void 0 && Object.hasOwn(own(pack.types, seed)?.fields ?? {}, name)) {
958
+ dropped.push({
959
+ span: `by ${d.span}`,
960
+ reason: `its name "${name}" is also a field of ${seed}`,
961
+ kind: "order"
962
+ });
963
+ continue;
964
+ }
965
+ params.select = {
966
+ ...params.select ?? {},
967
+ [name]: { [op]: operands.map((o) => o.slice(seed.length + 1)) }
968
+ };
969
+ params.orderBy = [{ [name]: "desc" }];
970
+ plan.push({
971
+ path: [
972
+ "select",
973
+ name,
974
+ `ruling:${d.span}`
975
+ ],
976
+ kind: "select",
977
+ served: false
978
+ }, {
979
+ path: [
980
+ "orderBy",
981
+ "0",
982
+ name,
983
+ "desc (default)"
984
+ ],
985
+ kind: "order",
986
+ served: false
987
+ });
988
+ }
989
+ if (clarify !== null) return { clarify };
990
+ for (const w of walks.values()) {
991
+ const def = typeExclude(w.type);
992
+ const tested = [];
993
+ if (def !== null) whereFields(own(rulings.typeExcludes, w.type), tested);
994
+ const named = [];
995
+ for (const f of w.filters) whereFields(f.clause, named);
996
+ const yieldTo = tested.find((f) => named.includes(f));
997
+ if (yieldTo === void 0) continue;
998
+ w.excludes = w.excludes.filter((x) => !isDefault(x, w.type));
999
+ w.notes.push(defaultYield(w.type, yieldTo, []));
1000
+ }
1001
+ let pickDropped = false;
1002
+ for (const w of walks.values()) {
1003
+ if (w.pick === void 0 || w.excludes.length === 0) continue;
1004
+ const names = w.excludes.flatMap((x) => x.plan.map((c) => `'${String(c.path.at(-1)).replace(/^ruling:/, "")}'`)).join(", ");
1005
+ dropped.push({
1006
+ span: w.pick.span,
1007
+ reason: `cannot pick the ${PICKED[w.pick.kind]} ${w.type} while the ${names} exclusion applies`,
1008
+ kind: "filter"
1009
+ });
1010
+ delete w.pick;
1011
+ pickDropped = true;
1012
+ }
1013
+ const taken = /* @__PURE__ */ new Set();
1014
+ const ordered = [...walks.values()].sort((x, y) => hopKey(ns, x.path[0]).localeCompare(hopKey(ns, y.path[0])));
1015
+ for (const w of ordered) if (w.path.length === 1 && w.pick === void 0) w.alias = aliasFor(w.type, taken);
1016
+ const aliasOf = new Map(ordered.map((w) => [w.type, w.alias]));
1017
+ const resolveRefs = (v) => {
1018
+ if (Array.isArray(v)) return v.map(resolveRefs);
1019
+ if (typeof v !== "object" || v === null) return v;
1020
+ const out = {};
1021
+ for (const [k, x] of Object.entries(v)) if (k === "$ref" && typeof x === "string" && x.includes("\0")) {
1022
+ const [type, field] = x.split("\0");
1023
+ out[k] = `${aliasOf.get(type)}.${field}`;
1024
+ } else out[k] = resolveRefs(x);
1025
+ return out;
1026
+ };
1027
+ const parts = [...seedParts];
1028
+ for (const w of ordered) parts.push(walkPart(ns, w, typeExclude));
1029
+ const composed = parts.map((p) => ({
1030
+ ...p,
1031
+ clause: resolveRefs(p.clause)
1032
+ }));
1033
+ return {
1034
+ parts: composed,
1035
+ params,
1036
+ plan,
1037
+ dropped,
1038
+ timeOnSeed,
1039
+ ...seedLatest !== void 0 ? { seedLatest } : {},
1040
+ ...seedOrder !== void 0 ? { seedOrder } : {},
1041
+ walked: walks.size > 0 || seedParts.some((p) => p.plan.some((c) => c.kind === "ref")) || plan.length > 0,
1042
+ strict: pickDropped || ordered.some((w) => w.pick !== void 0) || composed.some((p) => p.plan.some((c) => c.kind === "ref"))
1043
+ };
1044
+ }
1045
+ const isDefault = (x, type) => x.plan.some((c) => c.path.at(-1) === `ruling:${type} default exclude`);
1046
+ function hopKey(ns, h) {
1047
+ return h.dir === "in" ? `${ns}/${h.owner}.${h.field}` : h.field;
1048
+ }
1049
+ /** One walk as a (possibly nested) `_walk` clause. */
1050
+ function walkPart(ns, w, exclude) {
1051
+ const inner = andOf([
1052
+ ...w.filters,
1053
+ ...w.window,
1054
+ ...w.excludes
1055
+ ]);
1056
+ const label = w.pick === void 0 ? "any" : `pick:${w.pick.kind}(${w.pick.by}) from ${w.pick.source}`;
1057
+ let node = {
1058
+ ...w.alias !== void 0 ? { as: w.alias } : {},
1059
+ ...edge(ns, w.path[w.path.length - 1]),
1060
+ ...inner !== null ? { where: inner.where } : {},
1061
+ ...w.pick !== void 0 ? { pick: { [w.pick.kind]: w.pick.by } } : {}
1062
+ };
1063
+ let plan = [{
1064
+ path: [
1065
+ "_walk",
1066
+ hopKey(ns, w.path[w.path.length - 1]),
1067
+ label
1068
+ ],
1069
+ kind: "hop",
1070
+ served: true
1071
+ }, ...[...inner?.plan ?? [], ...w.notes].map((c) => ({
1072
+ ...c,
1073
+ path: [
1074
+ "_walk",
1075
+ "where",
1076
+ ...c.path
1077
+ ]
1078
+ }))];
1079
+ for (let i = w.path.length - 2; i >= 0; i--) {
1080
+ const h = w.path[i];
1081
+ const ex = exclude(h.to);
1082
+ const where = andOf([{
1083
+ clause: { _walk: node },
1084
+ plan
1085
+ }, ...ex !== null ? [ex] : []]);
1086
+ node = {
1087
+ ...edge(ns, h),
1088
+ where: where?.where
1089
+ };
1090
+ plan = [{
1091
+ path: [
1092
+ "_walk",
1093
+ hopKey(ns, h),
1094
+ "any"
1095
+ ],
1096
+ kind: "hop",
1097
+ served: true
1098
+ }, ...(where?.plan ?? []).map((c) => ({
1099
+ ...c,
1100
+ path: [
1101
+ "_walk",
1102
+ "where",
1103
+ ...c.path
1104
+ ]
1105
+ }))];
1106
+ }
1107
+ return {
1108
+ clause: { _walk: node },
1109
+ plan
1110
+ };
1111
+ }
1112
+ function edge(ns, h) {
1113
+ return h.dir === "in" ? { in: `${ns}/${h.owner}.${h.field}` } : { out: h.field };
1114
+ }
1115
+
1116
+ //#endregion
1117
+ //#region src/parse/parse.ts
1118
+ /** Words that carry no query meaning on their own. */
1119
+ const GLUE = new Set("a about again all am an and any anything are as at be been by can could current did do does for from get give go got have hey i i'm in is it it's let let's lets list me more my need needs next now of ok on or our please raised see show so some still talk tell that the their them there these this those to us want was we we've we'd what what's whats when where which who whose why will with would you your yo up thought handled judgement judgment make nice there's anymore stuff things few runs run ran lives wrote write written created made filed logged".split(/\s+/));
1120
+ /** First word of an imperative edit, which substrate-nl refuses: it only reads. */
1121
+ const MUTATIONS = new Set("close delete remove archive merge approve approved create add update set mark rename reopen assign ack deploy cut land".split(" "));
1122
+ const LEADING_FILLER = new Set("please can could would you go ahead let let's lets hey ok yo so and then".split(" "));
1123
+ const STATE_CUES = new Set("what what's whats show talk tell status is describe about see which who".split(" "));
1124
+ const CLOSE_VERBS = new Set("close closed closing done finished completed resolved ship shipped drop dropped cancel cancelled abandoned".split(" "));
1125
+ const UPDATE_VERBS = new Set("updated changed edited touched".split(" "));
1126
+ /** Terminal status values: matching one is a question about the past. */
1127
+ const TERMINAL = [
1128
+ "closed",
1129
+ "complete",
1130
+ "completed",
1131
+ "done",
1132
+ "resolved",
1133
+ "superseded"
1134
+ ];
1135
+ /** Terminal statuses a closing verb selects: finished, not merely replaced. */
1136
+ const CLOSED = [
1137
+ "closed",
1138
+ "complete",
1139
+ "completed",
1140
+ "done",
1141
+ "resolved"
1142
+ ];
1143
+ const HISTORY_WORDS = new Set("archived archive history historical ever previously past trend trends over-time all-time total".split(" "));
1144
+ /** Connectives a composed reading cannot honour; dropped while composing walks. */
1145
+ const CONNECTIVES = /* @__PURE__ */ new Set([
1146
+ "or",
1147
+ "not",
1148
+ "no",
1149
+ "every"
1150
+ ]);
1151
+ const LATEST = new Set("latest newest recent last".split(" "));
1152
+ const OLDEST = new Set("oldest earliest first".split(" "));
1153
+ const AUTHOR_VERBS = new Set("raised created written filed authored opened made sent logged".split(" "));
1154
+ const BUILTIN_FIELD_ALIASES = { author: "createdById" };
1155
+ /** `field:value`, `field:[a,b]`, `field:"two words"`; optionally wrapped in quotes. A clock time starts with a digit. */
1156
+ const CLAUSE = /(['"]?)\b([A-Za-z][A-Za-z0-9]*):(\[[^\]]*\]|"[^"]*"|[^\s,'"]+)\1/g;
1157
+ function parseClause(span, field, raw) {
1158
+ const unquote = (v) => v.trim().replace(/^["']|["']$/g, "");
1159
+ if (raw.startsWith("[")) return {
1160
+ span,
1161
+ field,
1162
+ op: "in",
1163
+ values: raw.slice(1, -1).split(",").map(unquote).filter((v) => v.length > 0)
1164
+ };
1165
+ if (raw.startsWith("\"")) return {
1166
+ span,
1167
+ field,
1168
+ op: "eq",
1169
+ values: [unquote(raw)]
1170
+ };
1171
+ const cmp = /^(>=|<=|>|<)(.+)$/.exec(raw);
1172
+ if (cmp !== null) return {
1173
+ span,
1174
+ field,
1175
+ op: {
1176
+ ">": "gt",
1177
+ ">=": "gte",
1178
+ "<": "lt",
1179
+ "<=": "lte"
1180
+ }[cmp[1]],
1181
+ values: [cmp[2]]
1182
+ };
1183
+ const range = /^(.+)\.\.(.+)$/.exec(raw);
1184
+ if (range !== null) return {
1185
+ span,
1186
+ field,
1187
+ op: "between",
1188
+ values: [range[1], range[2]]
1189
+ };
1190
+ if (raw.startsWith("!")) return {
1191
+ span,
1192
+ field,
1193
+ op: "neq",
1194
+ values: [raw.slice(1)]
1195
+ };
1196
+ if (raw.startsWith("~")) return {
1197
+ span,
1198
+ field,
1199
+ op: "contains",
1200
+ values: [raw.slice(1)]
1201
+ };
1202
+ return {
1203
+ span,
1204
+ field,
1205
+ op: "eq",
1206
+ values: [raw]
1207
+ };
1208
+ }
1209
+ function parseQuestion(question, pack, ctx) {
1210
+ const rulings = ctx.rulings ?? {};
1211
+ const clauses = [];
1212
+ const tokens = (question.replace(CLAUSE, (span, _q, field, raw) => {
1213
+ clauses.push(parseClause(span, field, raw));
1214
+ return " ";
1215
+ }).toLowerCase().replace(/[‘’]/g, "'").match(/\d{4}-\d{2}-\d{2}t\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:z|[+-]\d{2}:\d{2})?|\$\d+(?:\.\d+)?|\d+(?:\.\d+)?[%×]|#\d+|[a-z0-9@[][a-z0-9@._'\]-]*/g) ?? []).map((t) => t.replace(/[.'-]+$/, "").replace(/'s$/, "")).filter((t) => t.length > 0).map((text) => ({
1216
+ text,
1217
+ used: false
1218
+ }));
1219
+ const words = tokens.map((t) => t.text);
1220
+ const evidence = [];
1221
+ const lead = words.find((w) => !LEADING_FILLER.has(w));
1222
+ if (lead !== void 0 && MUTATIONS.has(lead)) return {
1223
+ status: "refuse",
1224
+ candidates: [],
1225
+ residual: [],
1226
+ reason: `"${lead}" is an edit; substrate-nl answers questions and does not change data`
1227
+ };
1228
+ const values = [];
1229
+ claimNgrams(tokens, 4, (key, at) => {
1230
+ const alias = own(rulings.valueAliases, key);
1231
+ if (alias === void 0) return false;
1232
+ values.push({
1233
+ span: key,
1234
+ key: null,
1235
+ alias,
1236
+ at
1237
+ });
1238
+ return true;
1239
+ });
1240
+ const walkClaims = claimWalkParts(tokens, rulings, GLUE);
1241
+ const mentioned = /* @__PURE__ */ new Map();
1242
+ for (const entry of buildTypeIndex(pack, rulings)) {
1243
+ const n = entry.phrase.split(" ").length;
1244
+ for (let i = 0; i + n <= tokens.length; i++) {
1245
+ const slice = tokens.slice(i, i + n);
1246
+ if (slice.some((t) => t.used) || slice.map((t) => t.text).join(" ") !== entry.phrase) continue;
1247
+ for (const t of slice) t.used = true;
1248
+ for (const type of entry.types) mentioned.set(type, {
1249
+ span: entry.phrase,
1250
+ plural: entry.plural,
1251
+ at: mentioned.get(type)?.at ?? [i, i + n - 1]
1252
+ });
1253
+ }
1254
+ }
1255
+ for (const [type, m] of mentioned) evidence.push({
1256
+ span: m.span,
1257
+ role: "type",
1258
+ detail: type
1259
+ });
1260
+ const time = claimTime(tokens, ctx.asOf);
1261
+ if (time !== null) evidence.push({
1262
+ span: time.span,
1263
+ role: "time",
1264
+ detail: `${time.range.gte ?? ""} .. ${time.range.lt ?? ""}`.trim()
1265
+ });
1266
+ const aggregate = claimAggregate(tokens, walkClaims, pack, rulings, [...mentioned.values()].map((m) => m.at[0]));
1267
+ const fieldOrder = claimFieldOrder(tokens, walkClaims, pack, rulings, mentioned);
1268
+ const fieldType = fieldOrder?.type;
1269
+ if (fieldType !== void 0 && time === null && mentioned.size > 1) {
1270
+ mentioned.delete(fieldType);
1271
+ const e = evidence.findIndex((x) => x.role === "type" && x.detail === fieldType);
1272
+ if (e >= 0) evidence.splice(e, 1);
1273
+ }
1274
+ const ids = [];
1275
+ let bareNumber = false;
1276
+ tokens.forEach((t, i) => {
1277
+ if (t.used) return;
1278
+ if (/^#\d+$/.test(t.text)) {
1279
+ ids.push(Number(t.text.slice(1)));
1280
+ t.used = true;
1281
+ evidence.push({
1282
+ span: t.text,
1283
+ role: "id",
1284
+ detail: "shortId"
1285
+ });
1286
+ } else if (/^\d+$/.test(t.text)) {
1287
+ if (tokens[i - 1]?.used === true && mentioned.size > 0) {
1288
+ ids.push(Number(t.text));
1289
+ t.used = true;
1290
+ evidence.push({
1291
+ span: t.text,
1292
+ role: "id",
1293
+ detail: "shortId"
1294
+ });
1295
+ } else bareNumber = true;
1296
+ }
1297
+ });
1298
+ let order = null;
1299
+ let count = false;
1300
+ let allProjects = false;
1301
+ let historyWord = false;
1302
+ const singularMention = [...mentioned.values()].some((m) => !m.plural);
1303
+ tokens.forEach((t, i) => {
1304
+ if (t.used) return;
1305
+ const next = tokens[i + 1];
1306
+ if (LATEST.has(t.text) || t.text === "most" && /^recent(ly)?$/.test(next?.text ?? "") || t.text === "current" && singularMention) {
1307
+ order = "desc";
1308
+ t.used = true;
1309
+ if (t.text === "most" && next !== void 0) next.used = true;
1310
+ evidence.push({
1311
+ span: t.text,
1312
+ role: "order",
1313
+ detail: "createdAt desc, limit 1"
1314
+ });
1315
+ } else if (OLDEST.has(t.text)) {
1316
+ order = "asc";
1317
+ t.used = true;
1318
+ evidence.push({
1319
+ span: t.text,
1320
+ role: "order",
1321
+ detail: "createdAt asc, limit 1"
1322
+ });
1323
+ } else if (t.text === "how" && next?.text === "many") {
1324
+ count = true;
1325
+ t.used = true;
1326
+ next.used = true;
1327
+ evidence.push({
1328
+ span: "how many",
1329
+ role: "count",
1330
+ detail: "answer = count"
1331
+ });
1332
+ } else if ((t.text === "every" || t.text === "all") && /^projects?$/.test(next?.text ?? "")) {
1333
+ allProjects = true;
1334
+ t.used = true;
1335
+ next.used = true;
1336
+ evidence.push({
1337
+ span: `${t.text} ${next?.text}`,
1338
+ role: "scope",
1339
+ detail: "no project scope"
1340
+ });
1341
+ } else if (t.text === "across") {
1342
+ allProjects = true;
1343
+ t.used = true;
1344
+ } else if (HISTORY_WORDS.has(t.text)) {
1345
+ historyWord = true;
1346
+ t.used = true;
1347
+ evidence.push({
1348
+ span: t.text,
1349
+ role: "history",
1350
+ detail: "search the whole record"
1351
+ });
1352
+ }
1353
+ });
1354
+ let author = null;
1355
+ tokens.forEach((t, i) => {
1356
+ const prev = tokens[i - 1];
1357
+ const next = tokens[i + 1];
1358
+ if (t.text === "by" && prev !== void 0 && AUTHOR_VERBS.has(prev.text) && next !== void 0) {
1359
+ author = next.text;
1360
+ for (const x of [
1361
+ prev,
1362
+ t,
1363
+ next
1364
+ ]) x.used = true;
1365
+ } else if (t.text === "sent" && prev !== void 0 && !GLUE.has(prev.text) && !prev.used) {
1366
+ author = prev.text;
1367
+ prev.used = true;
1368
+ t.used = true;
1369
+ }
1370
+ });
1371
+ if (author !== null) evidence.push({
1372
+ span: author,
1373
+ role: "author",
1374
+ detail: `createdById startsWith ${author}`
1375
+ });
1376
+ const composing = walkClaims.phrases.length + walkClaims.compares.length + walkClaims.dropped.length > 0;
1377
+ if (composing) {
1378
+ dropComparatives(tokens, walkClaims.dropped);
1379
+ for (const t of tokens) {
1380
+ if (t.used || !CONNECTIVES.has(t.text)) continue;
1381
+ t.used = true;
1382
+ walkClaims.dropped.push({
1383
+ span: t.text,
1384
+ reason: `"${t.text}" is not composed: walk clauses are read as all applying together`,
1385
+ kind: "filter"
1386
+ });
1387
+ }
1388
+ }
1389
+ const fieldAliases = {
1390
+ ...BUILTIN_FIELD_ALIASES,
1391
+ ...rulings.fieldAliases ?? {}
1392
+ };
1393
+ let askField = null;
1394
+ tokens.forEach((t, i) => {
1395
+ if (t.used || tokens[i - 1]?.text !== "which") return;
1396
+ for (const form of [t.text, t.text.replace(/s$/, "")]) {
1397
+ const field = own(fieldAliases, form) ?? (fieldNamed(pack, form) ? form : null);
1398
+ if (field === null) continue;
1399
+ askField = {
1400
+ field,
1401
+ group: form !== t.text
1402
+ };
1403
+ t.used = true;
1404
+ evidence.push({
1405
+ span: t.text,
1406
+ role: "field",
1407
+ detail: askField.group ? `group by ${field}` : `answer = ${field}`
1408
+ });
1409
+ return;
1410
+ }
1411
+ });
1412
+ const flagClaims = /* @__PURE__ */ new Map();
1413
+ for (const type of mentioned.keys()) for (const [name, f] of Object.entries(own(pack.types, type)?.fields ?? {})) {
1414
+ if (f.valueType !== "boolean" || name === "archived") continue;
1415
+ const t = tokens.find((x) => !x.used && f.phrases.includes(x.text));
1416
+ if (t === void 0) continue;
1417
+ t.used = true;
1418
+ flagClaims.set(type, [...flagClaims.get(type) ?? [], {
1419
+ span: t.text,
1420
+ role: "value",
1421
+ detail: name
1422
+ }]);
1423
+ }
1424
+ claimNgrams(tokens, 4, (key, at) => {
1425
+ if (at.length === 1 && GLUE.has(key)) return false;
1426
+ if (at.length === 1 && CLOSE_VERBS.has(key)) return false;
1427
+ const found = own(pack.values, key) !== void 0 ? key : at.length === 1 && /[^s]s$/.test(key) && own(pack.values, key.slice(0, -1)) !== void 0 ? key.slice(0, -1) : null;
1428
+ if (found === null) return false;
1429
+ values.push({
1430
+ span: key,
1431
+ key: found,
1432
+ at
1433
+ });
1434
+ return true;
1435
+ });
1436
+ const closeVerb = words.some((w) => CLOSE_VERBS.has(w));
1437
+ const updateVerb = words.some((w) => UPDATE_VERBS.has(w));
1438
+ for (const t of tokens) if (CLOSE_VERBS.has(t.text) || UPDATE_VERBS.has(t.text)) t.used = true;
1439
+ let types = [...mentioned.keys()].sort();
1440
+ if (ctx.forceType !== void 0 && own(pack.types, ctx.forceType) !== void 0) {
1441
+ types = [ctx.forceType];
1442
+ if (!mentioned.has(ctx.forceType)) evidence.push({
1443
+ span: "",
1444
+ role: "type",
1445
+ detail: ctx.forceType
1446
+ });
1447
+ }
1448
+ if (composing && ctx.forceType === void 0 && mentioned.size > 0) {
1449
+ const reached = new Set(walkClaims.phrases.map((p) => p.type));
1450
+ const byPosition = [...mentioned].sort(([, x], [, y]) => x.at[0] - y.at[0]).map(([t]) => t);
1451
+ const seeds = byPosition.filter((t) => !reached.has(t));
1452
+ types = (seeds.length > 0 ? seeds : byPosition.slice(0, 1)).sort();
1453
+ }
1454
+ if (types.length === 0 && ids.length > 0 && ctx.defaultIdType !== void 0) types = [ctx.defaultIdType];
1455
+ if (types.length === 0 && values.length > 0) {
1456
+ types = typesCovering(pack, values);
1457
+ const live = types.filter((t) => values.some((v) => v.key !== null && v.key === own(rulings.liveStatus, t)));
1458
+ if (types.length > 1 && live.length > 0) types = live;
1459
+ }
1460
+ if (types.length === 0 && clauses.length > 0) types = typesWithFields(pack, clauses, rulings);
1461
+ if (types.length === 0 && closeVerb) types = closableTypes(pack);
1462
+ const named = mentioned.size > 0 || ctx.forceType !== void 0;
1463
+ if (bareNumber && ids.length === 0 && !named) return {
1464
+ status: "clarify",
1465
+ candidates: [],
1466
+ residual: [],
1467
+ reason: "a bare number with no type"
1468
+ };
1469
+ if (ids.length > 0 && !named && !words.some((w) => STATE_CUES.has(w))) return {
1470
+ status: "clarify",
1471
+ candidates: [],
1472
+ residual: [],
1473
+ reason: "#N with no question about it: a Todo or a PR?"
1474
+ };
1475
+ if (types.length === 0) return {
1476
+ status: "unparsed",
1477
+ candidates: [],
1478
+ evidence,
1479
+ residual: contentWords(tokens),
1480
+ reason: "no type, id or known value"
1481
+ };
1482
+ const candidates = [];
1483
+ const ruledOut = [];
1484
+ for (const type of types) {
1485
+ let composed;
1486
+ if (composing) {
1487
+ const r = compose({
1488
+ pack,
1489
+ rulings,
1490
+ seed: type,
1491
+ claims: walkClaims,
1492
+ mentions: [...mentioned].map(([t, m]) => ({
1493
+ type: t,
1494
+ span: m.span,
1495
+ at: m.at
1496
+ })),
1497
+ time
1498
+ });
1499
+ if ("clarify" in r) return {
1500
+ status: "clarify",
1501
+ candidates: [],
1502
+ residual: [],
1503
+ reason: r.clarify
1504
+ };
1505
+ composed = r;
1506
+ }
1507
+ const c = assemble(type, {
1508
+ composed,
1509
+ pack,
1510
+ ctx,
1511
+ tokens: tokens.map((t) => ({ ...t })),
1512
+ evidence: evidence.filter((e) => e.role !== "type" || e.detail === type),
1513
+ ids,
1514
+ values,
1515
+ clauses,
1516
+ time: composed === void 0 || composed.timeOnSeed ? time : null,
1517
+ order,
1518
+ fieldOrder: fieldOrder ?? composed?.seedOrder ?? null,
1519
+ plural: mentioned.get(type)?.plural ?? false,
1520
+ count,
1521
+ aggregate,
1522
+ allProjects,
1523
+ historyWord,
1524
+ flags: flagClaims.get(type) ?? [],
1525
+ author,
1526
+ askField,
1527
+ closeVerb,
1528
+ updateVerb
1529
+ });
1530
+ if ("reason" in c) ruledOut.push(`${type}: ${c.reason}`);
1531
+ else candidates.push(c);
1532
+ }
1533
+ if (candidates.length === 0) {
1534
+ const reason = ruledOut.length > 0 ? ruledOut.join("; ") : "no type fits every value";
1535
+ return {
1536
+ status: "unparsed",
1537
+ candidates,
1538
+ evidence,
1539
+ residual: contentWords(tokens),
1540
+ reason
1541
+ };
1542
+ }
1543
+ if (candidates.length > 1) return {
1544
+ status: "ambiguous",
1545
+ candidates,
1546
+ residual: [],
1547
+ reason: `${candidates.length} readings`
1548
+ };
1549
+ const only = candidates[0];
1550
+ if (only.dropped.length > 0) return {
1551
+ status: "partial",
1552
+ candidates,
1553
+ residual: only.residual,
1554
+ reason: `dropped: ${only.dropped.map((d) => `"${d.span}" (${d.reason})`).join("; ")}`
1555
+ };
1556
+ if (only.residual.length > 0 && ids.length === 0) return {
1557
+ status: "partial",
1558
+ candidates,
1559
+ residual: only.residual,
1560
+ reason: `unexplained: ${only.residual.join(", ")}`
1561
+ };
1562
+ return {
1563
+ status: "resolved",
1564
+ candidates,
1565
+ residual: only.residual
1566
+ };
1567
+ }
1568
+ /** One reading of the question as `type`, or why there is none. */
1569
+ function assemble(type, a) {
1570
+ const { pack, ctx, tokens } = a;
1571
+ const rulings = ctx.rulings ?? {};
1572
+ const fields = own(pack.types, type)?.fields ?? {};
1573
+ const words = tokens.map((t) => t.text);
1574
+ const seedLatest = a.composed?.seedLatest;
1575
+ const evidence = a.order === null && seedLatest !== void 0 ? [...a.evidence, {
1576
+ span: seedLatest,
1577
+ role: "order",
1578
+ detail: "desc, limit 1"
1579
+ }] : a.evidence;
1580
+ const recency = a.order ?? (seedLatest !== void 0 ? "desc" : null);
1581
+ const derived = a.composed?.params.orderBy !== void 0;
1582
+ const aggClaim = a.count ? null : a.aggregate;
1583
+ const fieldOrder = [];
1584
+ let sortBy = null;
1585
+ if (a.fieldOrder !== null && (a.count || aggClaim !== null)) fieldOrder.push({
1586
+ span: a.fieldOrder.span,
1587
+ reason: `ordering does not apply to ${a.count ? "a count" : "an aggregate"}`,
1588
+ kind: "filter"
1589
+ });
1590
+ if (a.fieldOrder !== null && !a.count && aggClaim === null) {
1591
+ const r = orderField(a.fieldOrder, type, pack, rulings);
1592
+ const reason = "reason" in r ? r.reason : derived ? "it conflicts with the derived ordering, which is kept" : null;
1593
+ const limit = a.fieldOrder.limit ?? (a.plural ? 10 : 1);
1594
+ if (reason !== null) fieldOrder.push({
1595
+ span: a.fieldOrder.span,
1596
+ reason,
1597
+ kind: "order"
1598
+ });
1599
+ else if ("field" in r) sortBy = {
1600
+ field: r.field,
1601
+ dir: a.fieldOrder.dir,
1602
+ limit
1603
+ };
1604
+ else if ("hop" in r && Object.hasOwn(fields, r.hop.name)) fieldOrder.push({
1605
+ span: a.fieldOrder.span,
1606
+ reason: `its name "${r.hop.name}" is also a field of ${type}`,
1607
+ kind: "order"
1608
+ });
1609
+ else if ("hop" in r) sortBy = {
1610
+ field: r.hop.name,
1611
+ hop: r.hop,
1612
+ dir: a.fieldOrder.dir,
1613
+ limit
1614
+ };
1615
+ }
1616
+ const pickOver = (a.count || aggClaim !== null) && recency !== null;
1617
+ const conflict = !pickOver && (derived || sortBy !== null) && recency !== null;
1618
+ const order = conflict || pickOver ? null : recency;
1619
+ const orderSpan = evidence.find((e) => e.role === "order")?.span ?? "";
1620
+ const ev = conflict || pickOver ? evidence.filter((e) => e.role !== "order") : [...evidence];
1621
+ if (sortBy !== null) ev.push({
1622
+ span: a.fieldOrder?.span ?? "",
1623
+ role: "order",
1624
+ detail: `${sortBy.hop?.label ?? sortBy.field} ${sortBy.dir}, limit ${sortBy.limit}`
1625
+ });
1626
+ const dropped = [
1627
+ ...a.composed?.dropped ?? [],
1628
+ ...fieldOrder,
1629
+ ...conflict ? [{
1630
+ span: orderSpan,
1631
+ reason: `it conflicts with the ${derived ? "derived" : "field"} ordering, which is kept`,
1632
+ kind: "order"
1633
+ }] : [],
1634
+ ...pickOver ? [{
1635
+ span: orderSpan,
1636
+ reason: `${a.count ? "counting" : "aggregating"} over the latest N rows is not supported`,
1637
+ kind: "filter"
1638
+ }] : [],
1639
+ ...a.count && a.aggregate !== null ? [{
1640
+ span: a.aggregate.span,
1641
+ reason: "an aggregate does not apply to a count",
1642
+ kind: "filter"
1643
+ }] : [],
1644
+ ...aggClaim !== null && derived ? [{
1645
+ span: `by ${Object.keys(a.composed?.params.select ?? {}).join(", ")}`,
1646
+ reason: "grouping by a derived value is not supported",
1647
+ kind: "order"
1648
+ }] : []
1649
+ ];
1650
+ const where = [];
1651
+ const wherePlan = /* @__PURE__ */ new Map();
1652
+ const yields = [];
1653
+ if (a.ids.length > 0) where.push({ shortId: a.ids.length === 1 ? { eq: a.ids[0] } : { in: a.ids } });
1654
+ const byField = /* @__PURE__ */ new Map();
1655
+ const usedFields = /* @__PURE__ */ new Set();
1656
+ let terminal = false;
1657
+ for (const v of a.ids.length > 0 ? [] : a.values) {
1658
+ if (v.alias !== void 0) {
1659
+ const hit = v.alias.find((x) => x.type === type);
1660
+ if (hit === void 0) return { reason: `"${v.span}" does not apply to ${type}` };
1661
+ const op = hit.in !== void 0 ? { in: hit.in } : hit.eq !== void 0 ? { eq: hit.eq } : hit.startsWith !== void 0 ? { startsWith: hit.startsWith } : { contains: hit.contains };
1662
+ where.push({ [hit.field]: op });
1663
+ usedFields.add(hit.field);
1664
+ ev.push({
1665
+ span: v.span,
1666
+ role: "value",
1667
+ detail: `${hit.field} ${JSON.stringify(op)}`
1668
+ });
1669
+ continue;
1670
+ }
1671
+ const refs = (own(a.pack.values, v.key) ?? []).filter((r) => r.type === type);
1672
+ if (refs.length === 0) return { reason: `"${v.span}" is not a ${type} value` };
1673
+ const field = pickField(refs.map((r) => r.field), fields, words);
1674
+ const stored = refs.find((r) => r.field === field)?.value ?? v.key;
1675
+ if (TERMINAL.includes(stored)) terminal = true;
1676
+ byField.set(field, [...byField.get(field) ?? [], stored]);
1677
+ usedFields.add(field);
1678
+ ev.push({
1679
+ span: v.span,
1680
+ role: "value",
1681
+ detail: `${field} = ${stored}`
1682
+ });
1683
+ }
1684
+ for (const [field, vals] of [...byField].sort(([x], [y]) => x.localeCompare(y))) if (fields[field]?.kind === "list") for (const v of vals) where.push({ [field]: { has: v } });
1685
+ else where.push({ [field]: vals.length === 1 ? { eq: vals[0] } : { in: vals } });
1686
+ for (const c of a.clauses) {
1687
+ const name = resolveField(c.field, fields, rulings);
1688
+ const f = name === null ? void 0 : fields[name];
1689
+ if (name === null || f === void 0) return { reason: `${type} has no field "${c.field}"` };
1690
+ if (!f.operators.includes(c.op)) return { reason: `${name} does not accept ${c.op}` };
1691
+ const coerced = c.values.map((v) => coerce(v, f));
1692
+ if (coerced.some((v) => v === void 0)) return { reason: `"${c.span}" is not a ${f.valueType} value` };
1693
+ const operand = c.op === "in" || c.op === "between" ? coerced : coerced[0];
1694
+ where.push({ [name]: { [c.op]: operand } });
1695
+ usedFields.add(name);
1696
+ ev.push({
1697
+ span: c.span,
1698
+ role: "value",
1699
+ detail: `${name} ${c.op} ${JSON.stringify(operand)} (inline)`
1700
+ });
1701
+ }
1702
+ for (const field of usedFields) creditFieldWords(tokens, fields[field]);
1703
+ if (a.author !== null) where.push({ createdById: { startsWith: a.author } });
1704
+ const orderExclude = a.fieldOrder?.phrase?.entry.exclude;
1705
+ if (sortBy !== null && sortBy.hop === void 0 && orderExclude !== void 0) where.push({ NOT: orderExclude });
1706
+ const agg = aggClaim === null ? null : aggregateOn(aggClaim, type, pack, rulings);
1707
+ if (agg !== null) {
1708
+ dropped.push(...agg.dropped);
1709
+ ev.push(...agg.evidence);
1710
+ if (agg.exclude !== void 0) where.push({ NOT: agg.exclude });
1711
+ if (agg.group !== void 0) usedFields.add(agg.group.field);
1712
+ }
1713
+ for (const flag of a.flags) {
1714
+ usedFields.add(flag.detail);
1715
+ where.push({ [flag.detail]: { eq: true } });
1716
+ ev.push({
1717
+ ...flag,
1718
+ detail: `${flag.detail} = true`
1719
+ });
1720
+ }
1721
+ for (const [name, f] of Object.entries(fields)) {
1722
+ if (f.valueType !== "boolean" || name === "archived" || usedFields.has(name)) continue;
1723
+ const t = tokens.find((x) => !x.used && f.phrases.includes(x.text));
1724
+ if (t === void 0) continue;
1725
+ t.used = true;
1726
+ usedFields.add(name);
1727
+ where.push({ [name]: { eq: true } });
1728
+ ev.push({
1729
+ span: t.text,
1730
+ role: "value",
1731
+ detail: `${name} = true`
1732
+ });
1733
+ }
1734
+ const historical = a.historyWord || a.time !== null || a.closeVerb || terminal;
1735
+ if (a.time !== null) {
1736
+ const named = Object.entries(fields).find(([, f]) => f.valueType === "date" && f.kind !== "metadata" && creditFieldWords(tokens, f));
1737
+ const dateField = named?.[0] ?? (a.closeVerb || a.updateVerb ? "updatedAt" : own(rulings.timeField, type) ?? "createdAt");
1738
+ const clause = { [dateField]: { ...a.time.range } };
1739
+ where.push(clause);
1740
+ if (a.composed !== void 0) {
1741
+ const ruled = named !== void 0 || a.closeVerb || a.updateVerb || own(rulings.timeField, type) !== void 0;
1742
+ wherePlan.set(clause, [{
1743
+ path: [dateField, `window:${a.time.span}${ruled ? "" : ` on ${dateField} (default)`}`],
1744
+ kind: "filter",
1745
+ served: false
1746
+ }]);
1747
+ }
1748
+ }
1749
+ if (a.ids.length === 0) {
1750
+ const excluded = own(rulings.typeExcludes, type);
1751
+ if (excluded !== void 0) {
1752
+ const tested = [];
1753
+ whereFields(excluded, tested);
1754
+ const named = [...usedFields];
1755
+ for (const p of a.composed?.parts ?? []) whereFields(p.clause, named);
1756
+ const yieldTo = tested.find((f) => named.includes(f));
1757
+ if (yieldTo === void 0) {
1758
+ const clause = { NOT: excluded };
1759
+ where.push(clause);
1760
+ wherePlan.set(clause, [{
1761
+ path: ["NOT", `ruling:${type} default exclude`],
1762
+ kind: "filter",
1763
+ served: false
1764
+ }]);
1765
+ } else yields.push(defaultYield(type, yieldTo));
1766
+ }
1767
+ const statusField = fields.status;
1768
+ const live = own(rulings.liveStatus, type);
1769
+ if (a.closeVerb && statusField?.enum !== void 0 && !byField.has("status")) {
1770
+ const closed = statusField.enum.filter((s) => CLOSED.includes(s));
1771
+ if (closed.length > 0) where.push({ status: { in: closed } });
1772
+ } else if (!historical && live !== void 0 && statusField?.enum?.includes(live) === true && !usedFields.has("status") && order === null) where.push({ status: { eq: live } });
1773
+ if (!historical && fields.archived !== void 0 && !usedFields.has("archived")) where.push({ archived: { eq: false } });
1774
+ else if (historical) ev.push({
1775
+ span: "(history)",
1776
+ role: "history",
1777
+ detail: "archived rows included"
1778
+ });
1779
+ if (fields.active?.valueType === "boolean" && !usedFields.has("active") && !words.includes("inactive")) where.push({ active: { eq: true } });
1780
+ const scoped = fields.project !== void 0 && !(rulings.unscopedTypes ?? []).includes(type);
1781
+ const groupedByProject = a.askField?.group === true && a.askField.field === "project";
1782
+ if (scoped && !usedFields.has("project") && !a.allProjects && !groupedByProject && ctx.project !== void 0) {
1783
+ where.push({ OR: [{ project: { eq: ctx.project } }, { project: { eq: null } }] });
1784
+ ev.push({
1785
+ span: "(context)",
1786
+ role: "scope",
1787
+ detail: `project = ${ctx.project} or none`
1788
+ });
1789
+ }
1790
+ }
1791
+ const params = {};
1792
+ const parts = [...where.map((clause) => ({
1793
+ clause,
1794
+ plan: wherePlan.get(clause) ?? []
1795
+ })), ...a.composed?.parts ?? []];
1796
+ const all = andOf(parts);
1797
+ if (all !== null) params.where = all.where;
1798
+ const plan = [
1799
+ ...(all?.plan ?? []).map((c) => ({
1800
+ ...c,
1801
+ path: ["where", ...c.path]
1802
+ })),
1803
+ ...yields,
1804
+ ...(a.composed?.plan ?? []).filter((c) => aggClaim === null || c.kind !== "select"),
1805
+ ...sortBy?.hop !== void 0 ? [{
1806
+ path: [
1807
+ "fields",
1808
+ "_agg",
1809
+ sortBy.hop.name,
1810
+ sortBy.hop.label
1811
+ ],
1812
+ kind: "hop",
1813
+ served: true
1814
+ }, {
1815
+ path: [
1816
+ "orderBy",
1817
+ "0",
1818
+ sortBy.field,
1819
+ sortBy.dir
1820
+ ],
1821
+ kind: "order",
1822
+ served: false
1823
+ }] : [],
1824
+ ...agg?.group !== void 0 ? [{
1825
+ path: ["aggregate", `group:${agg.group.field} (one frame per value, and one for no value)`],
1826
+ kind: "agg",
1827
+ served: false
1828
+ }] : []
1829
+ ];
1830
+ if (order !== null) {
1831
+ params.orderBy = [{ [own(rulings.timeField, type) ?? "createdAt"]: order }];
1832
+ params.limit = 1;
1833
+ }
1834
+ if (sortBy !== null) {
1835
+ if (sortBy.hop !== void 0) params.select = { [sortBy.hop.name]: `_agg.${sortBy.hop.name}` };
1836
+ params.orderBy = [{ [sortBy.field]: sortBy.dir }];
1837
+ params.limit = sortBy.limit;
1838
+ }
1839
+ Object.assign(params, a.composed?.params ?? {});
1840
+ if (a.count && a.composed?.walked === true) params.count = true;
1841
+ if (aggClaim !== null) {
1842
+ delete params.select;
1843
+ delete params.orderBy;
1844
+ }
1845
+ if (agg?.fn !== void 0 && agg.field !== void 0) {
1846
+ params.aggregate = { value: { [agg.fn]: agg.field } };
1847
+ if (agg.dateGroup !== void 0) params.groupBy = { bucket: { dateTrunc: [{ lit: agg.dateGroup.by }, agg.dateGroup.field] } };
1848
+ }
1849
+ const answer = aggClaim !== null ? "aggregate" : a.askField !== null ? a.askField.group ? `group:${a.askField.field}` : `field:${a.askField.field}` : a.count ? "count" : order !== null || a.ids.length === 1 || sortBy?.limit === 1 ? "single" : "rows";
1850
+ return {
1851
+ type,
1852
+ frame: { [`${pack.namespace}/${type}`]: {
1853
+ params,
1854
+ ...sortBy?.hop !== void 0 ? { fields: { _agg: { [sortBy.hop.name]: sortBy.hop.agg } } } : {}
1855
+ } },
1856
+ answer,
1857
+ evidence: ev,
1858
+ residual: contentWords(tokens),
1859
+ plan,
1860
+ dropped,
1861
+ ...agg?.fn !== void 0 && agg.field !== void 0 ? { aggregate: {
1862
+ fn: agg.fn,
1863
+ field: agg.field,
1864
+ ...agg.group !== void 0 ? { group: agg.group } : {}
1865
+ } } : {},
1866
+ strict: a.count || aggClaim !== null || order !== null || sortBy !== null || a.ids.length === 1 || a.composed?.strict === true
1867
+ };
1868
+ }
1869
+ /** A field named by words on one type: one of its field phrases, else its name or an alias. */
1870
+ function fieldByWords(words, fields, rulings) {
1871
+ return Object.entries(fields).find(([, f]) => f.phrases.includes(words))?.[0] ?? (words.includes(" ") ? null : resolveField(words, fields, rulings));
1872
+ }
1873
+ /**
1874
+ * The field named at `i`: a field phrase claim, else the longest run of up to
1875
+ * three free words naming a field on some type, else (unless `numeric`) one
1876
+ * free unknown word, so the reading can drop it with a reason.
1877
+ */
1878
+ function fieldAt(tokens, walkClaims, pack, rulings, i, numeric) {
1879
+ const p = walkClaims.phrases.find((x) => x.at[0] === i && x.field !== void 0 && x.entry.value === void 0);
1880
+ if (p !== void 0) return {
1881
+ phrase: p,
1882
+ span: p.span,
1883
+ end: p.at[1]
1884
+ };
1885
+ for (let n = 3; n >= 1; n--) {
1886
+ const slice = tokens.slice(i, i + n);
1887
+ if (slice.length < n || slice.some((t) => t.used)) continue;
1888
+ const w = slice.map((t) => t.text).join(" ");
1889
+ if (Object.values(pack.types).some((t) => {
1890
+ const name = fieldByWords(w, t.fields, rulings);
1891
+ return name !== null && (!numeric || t.fields[name]?.valueType === "number");
1892
+ })) return {
1893
+ words: w,
1894
+ span: w,
1895
+ end: i + n - 1
1896
+ };
1897
+ }
1898
+ const t = tokens[i];
1899
+ return !numeric && t !== void 0 && !t.used && !GLUE.has(t.text) && !/^\d/.test(t.text) ? {
1900
+ words: t.text,
1901
+ span: t.text,
1902
+ end: i
1903
+ } : null;
1904
+ }
1905
+ /** Marks tokens `from`..`f.end` used; a field phrase named here is not walked to. */
1906
+ function takeField(tokens, walkClaims, from, f) {
1907
+ for (let k = from; k <= f.end; k++) tokens[k].used = true;
1908
+ if (f.phrase !== void 0) walkClaims.phrases.splice(walkClaims.phrases.indexOf(f.phrase), 1);
1909
+ }
1910
+ const fieldRef = (f) => f.phrase !== void 0 ? { phrase: f.phrase } : {
1911
+ words: f.words,
1912
+ ...f.type !== void 0 ? { type: f.type } : {}
1913
+ };
1914
+ /**
1915
+ * Claims one field ordering: "top|bottom [N] … by [pick] <field>",
1916
+ * "highest|lowest <field>", "most <number field>". The field may be a
1917
+ * "<type> <field>" pair, whose type mention is then part of the field, not a
1918
+ * seed; or a field phrase on another type that a walk pick claimed.
1919
+ */
1920
+ function claimFieldOrder(tokens, walkClaims, pack, rulings, mentioned) {
1921
+ const index = buildTypeIndex(pack, rulings);
1922
+ /** "<type> <field>": a named type's phrase at `i`, then a field of that type or one free word. */
1923
+ const typed = (i) => {
1924
+ for (const e of index) {
1925
+ const n = e.phrase.split(" ").length;
1926
+ const words = tokens.slice(i, i + n);
1927
+ const type = e.types[0];
1928
+ if (e.types.length !== 1 || !mentioned.has(type) || words.length < n) continue;
1929
+ if (words.map((t) => t.text).join(" ") !== e.phrase || words.some((t) => !t.used)) continue;
1930
+ const fields = own(pack.types, type)?.fields ?? {};
1931
+ const end = i + n - 1;
1932
+ for (let m = 3; m >= 1; m--) {
1933
+ const slice = tokens.slice(end + 1, end + 1 + m);
1934
+ if (slice.length < m || slice.some((t) => t.used)) continue;
1935
+ const w = slice.map((t) => t.text).join(" ");
1936
+ if (fieldByWords(w, fields, rulings) !== null || m === 1 && !GLUE.has(w) && !/^\d/.test(w)) return {
1937
+ words: w,
1938
+ type,
1939
+ span: `${e.phrase} ${w}`,
1940
+ end: end + m
1941
+ };
1942
+ }
1943
+ return null;
1944
+ }
1945
+ return null;
1946
+ };
1947
+ const at = (i, numeric) => typed(i) ?? fieldAt(tokens, walkClaims, pack, rulings, i, numeric);
1948
+ const take = (from, f) => takeField(tokens, walkClaims, from, f);
1949
+ /** A pick word at `i` ("latest", "lowest" …), free or claimed by a walk pick; a direction word sets `dir`. */
1950
+ const pickAt = (i) => {
1951
+ const claimed = walkClaims.picks.find((k) => k.at[0] === i);
1952
+ if (claimed !== void 0) return {
1953
+ span: claimed.span,
1954
+ kind: claimed.kind,
1955
+ dir: own(DIRECTION_WORDS, claimed.span),
1956
+ next: claimed.at[1] + 1,
1957
+ claimed
1958
+ };
1959
+ const words = [
1960
+ ...Object.keys(PICK_WORDS).filter((w) => w.includes(" ")),
1961
+ ...Object.keys(DIRECTION_WORDS),
1962
+ ...Object.keys(PICK_WORDS)
1963
+ ];
1964
+ for (const word of words) {
1965
+ const n = word.split(" ").length;
1966
+ const slice = tokens.slice(i, i + n);
1967
+ if (slice.length === n && slice.every((t) => !t.used) && slice.map((t) => t.text).join(" ") === word) return {
1968
+ span: word,
1969
+ kind: own(PICK_WORDS, word) ?? "max",
1970
+ dir: own(DIRECTION_WORDS, word),
1971
+ next: i + n
1972
+ };
1973
+ }
1974
+ return null;
1975
+ };
1976
+ const field = fieldRef;
1977
+ for (let i = 0; i < tokens.length; i++) {
1978
+ const t = tokens[i];
1979
+ if (t.used) {
1980
+ const k = walkClaims.picks.find((x) => x.at[0] === i && x.at[1] === i && (x.span === "highest" || x.span === "lowest"));
1981
+ const p = k?.phrase;
1982
+ if (k === void 0 || p === void 0 || p.field === void 0 || p.entry.value !== void 0 || walkClaims.compares.some((c) => c.subject === p || c.object === p)) continue;
1983
+ walkClaims.picks.splice(walkClaims.picks.indexOf(k), 1);
1984
+ take(i, {
1985
+ phrase: p,
1986
+ span: p.span,
1987
+ end: p.at[1]
1988
+ });
1989
+ return {
1990
+ span: `${k.span} ${p.span}`,
1991
+ dir: k.kind === "max" ? "desc" : "asc",
1992
+ phrase: p
1993
+ };
1994
+ }
1995
+ if (t.text === "top" || t.text === "bottom") {
1996
+ const n = tokens[i + 1];
1997
+ const limit = n !== void 0 && !n.used && /^[1-9]\d*$/.test(n.text) ? n : void 0;
1998
+ const by = tokens.findIndex((x, j) => j > i && x.text === "by" && !x.used && !AUTHOR_VERBS.has(tokens[j - 1]?.text ?? ""));
1999
+ if (by < 0) continue;
2000
+ const pick = pickAt(by + 1);
2001
+ const picked = pick === null ? null : at(pick.next, false);
2002
+ const f = picked ?? at(by + 1, false);
2003
+ if (f === null) continue;
2004
+ t.used = true;
2005
+ if (limit !== void 0) limit.used = true;
2006
+ const withPick = picked !== null && pick !== null;
2007
+ if (withPick && pick.claimed !== void 0) walkClaims.picks.splice(walkClaims.picks.indexOf(pick.claimed), 1);
2008
+ take(by, f);
2009
+ return {
2010
+ span: [
2011
+ t.text,
2012
+ limit?.text,
2013
+ "by",
2014
+ withPick ? pick.span : void 0,
2015
+ f.span
2016
+ ].filter((x) => x !== void 0).join(" "),
2017
+ dir: withPick && pick.dir !== void 0 ? pick.dir : t.text === "top" ? "desc" : "asc",
2018
+ ...limit !== void 0 ? { limit: Number(limit.text) } : {},
2019
+ ...withPick && pick.dir === void 0 ? { pick: {
2020
+ span: pick.span,
2021
+ kind: pick.kind
2022
+ } } : {},
2023
+ ...field(f)
2024
+ };
2025
+ }
2026
+ if (t.text === "highest" || t.text === "lowest" || t.text === "most") {
2027
+ const numeric = t.text === "most";
2028
+ const f = at(i + 1, numeric);
2029
+ if (f === null) continue;
2030
+ take(i, f);
2031
+ return {
2032
+ span: `${t.text} ${f.span}`,
2033
+ dir: t.text === "lowest" ? "asc" : "desc",
2034
+ ...numeric ? { numeric } : {},
2035
+ ...field(f)
2036
+ };
2037
+ }
2038
+ }
2039
+ return null;
2040
+ }
2041
+ const AGGREGATE_WORDS = {
2042
+ average: "avg",
2043
+ avg: "avg",
2044
+ mean: "avg",
2045
+ total: "sum",
2046
+ sum: "sum",
2047
+ min: "min",
2048
+ minimum: "min",
2049
+ lowest: "min",
2050
+ max: "max",
2051
+ maximum: "max",
2052
+ highest: "max"
2053
+ };
2054
+ /** Superlatives that are an ordering (#1903) unless the field is followed by one of these. */
2055
+ const VALUE_SUPERLATIVES = /* @__PURE__ */ new Set(["highest", "lowest"]);
2056
+ const VALUE_OF = /* @__PURE__ */ new Set(["of", "for"]);
2057
+ /** A word right after "by" that sets an ordering's direction ("top 10 items by lowest price"). */
2058
+ const DIRECTION_WORDS = {
2059
+ lowest: "asc",
2060
+ smallest: "asc",
2061
+ least: "asc",
2062
+ highest: "desc",
2063
+ largest: "desc",
2064
+ most: "desc"
2065
+ };
2066
+ /** A field grouping runs one frame per value: more than this is dropped. */
2067
+ const MAX_GROUPS = 20;
2068
+ const BUCKET_WORDS = /* @__PURE__ */ new Set([
2069
+ "hour",
2070
+ "day",
2071
+ "week",
2072
+ "month",
2073
+ "year"
2074
+ ]);
2075
+ /**
2076
+ * Claims one aggregate. "highest|lowest <field>" is a value only when "of" or
2077
+ * "for" follows the field and a type is named after it, none before the
2078
+ * superlative ("the highest price of items"); otherwise it stays an ordering
2079
+ * ("items with the highest price", "… highest price for last week").
2080
+ */
2081
+ function claimAggregate(tokens, walkClaims, pack, rulings, mentions) {
2082
+ const ofFollows = (end) => VALUE_OF.has(tokens[end + 1]?.text ?? "");
2083
+ const valueAt = (start, end) => ofFollows(end) && mentions.some((m) => m > end) && !mentions.some((m) => m < start);
2084
+ for (let i = 0; i < tokens.length; i++) {
2085
+ const t = tokens[i];
2086
+ const fn = own(AGGREGATE_WORDS, t.text);
2087
+ if (fn === void 0) continue;
2088
+ let f = null;
2089
+ if (t.used) {
2090
+ const pick = walkClaims.picks.find((k) => k.at[0] === i && k.at[1] === i);
2091
+ if (pick === void 0 || pick.phrase.field === void 0 || !valueAt(i, pick.phrase.at[1])) continue;
2092
+ walkClaims.picks.splice(walkClaims.picks.indexOf(pick), 1);
2093
+ f = {
2094
+ phrase: pick.phrase,
2095
+ span: pick.phrase.span,
2096
+ end: pick.phrase.at[1]
2097
+ };
2098
+ } else {
2099
+ let j = i + 1;
2100
+ while (!(tokens[j]?.used ?? true) && (tokens[j]?.text === "of" || tokens[j]?.text === "the")) j++;
2101
+ f = fieldAt(tokens, walkClaims, pack, rulings, j, false);
2102
+ if (f === null || VALUE_SUPERLATIVES.has(t.text) && !valueAt(i, f.end)) continue;
2103
+ }
2104
+ takeField(tokens, walkClaims, i, f);
2105
+ const claim = {
2106
+ span: tokens.slice(i, f.end + 1).map((x) => x.text).join(" "),
2107
+ word: t.text,
2108
+ fn,
2109
+ field: fieldRef(f)
2110
+ };
2111
+ for (let k = 0; k < tokens.length; k++) {
2112
+ const by = tokens[k];
2113
+ if (by.used || by.text !== "by" && by.text !== "per") continue;
2114
+ if (AUTHOR_VERBS.has(tokens[k - 1]?.text ?? "")) continue;
2115
+ const next = tokens[k + 1];
2116
+ if (next !== void 0 && !next.used && BUCKET_WORDS.has(next.text)) {
2117
+ by.used = next.used = true;
2118
+ claim.group = {
2119
+ span: `${by.text} ${next.text}`,
2120
+ unit: next.text
2121
+ };
2122
+ break;
2123
+ }
2124
+ const g = fieldAt(tokens, walkClaims, pack, rulings, k + 1, false);
2125
+ if (g === null) continue;
2126
+ takeField(tokens, walkClaims, k, g);
2127
+ claim.group = {
2128
+ span: `${by.text} ${g.span}`,
2129
+ field: fieldRef(g)
2130
+ };
2131
+ break;
2132
+ }
2133
+ return claim;
2134
+ }
2135
+ return null;
2136
+ }
2137
+ /**
2138
+ * The seed field words or a field phrase name on `type`, or why there is none:
2139
+ * `doing` names the act when the field is on another type ("ordering").
2140
+ */
2141
+ function seedField(o, type, pack, rulings, doing) {
2142
+ const fields = own(pack.types, type)?.fields ?? {};
2143
+ const walked = { reason: `${doing} across a walk is not supported` };
2144
+ let name;
2145
+ if (o.phrase !== void 0) {
2146
+ if (o.phrase.type !== type) return walked;
2147
+ name = o.phrase.field ?? null;
2148
+ } else {
2149
+ const words = o.words ?? "";
2150
+ name = fieldByWords(words, fields, rulings);
2151
+ if (name === null) return Object.values(pack.types).some((t) => fieldByWords(words, t.fields, rulings) !== null) ? walked : { reason: `${type} has no field "${words}"` };
2152
+ }
2153
+ const f = name === null ? void 0 : fields[name];
2154
+ if (name === null || f === void 0) return { reason: `${type} has no field "${o.span}"` };
2155
+ return {
2156
+ name,
2157
+ f
2158
+ };
2159
+ }
2160
+ /** An aggregate claim read on `type`: its function and field, or drops saying why not. */
2161
+ function aggregateOn(c, type, pack, rulings) {
2162
+ const r = seedField({
2163
+ span: c.span,
2164
+ ...c.field
2165
+ }, type, pack, rulings, "aggregating");
2166
+ const wants = c.fn === "min" || c.fn === "max" ? ["number", "date"] : ["number"];
2167
+ const reason = "reason" in r ? r.reason : (r.f.kind === "scalar" || r.f.kind === "metadata") && wants.includes(r.f.valueType ?? "") ? null : `${c.word} needs a ${wants.join(" or ")} field; ${r.name} is a ${r.f.valueType ?? r.f.kind} field`;
2168
+ if (reason !== null || "reason" in r) return {
2169
+ dropped: [{
2170
+ span: c.span,
2171
+ reason: reason ?? "",
2172
+ kind: "filter"
2173
+ }],
2174
+ evidence: []
2175
+ };
2176
+ const out = {
2177
+ fn: c.fn,
2178
+ field: r.name,
2179
+ dropped: [],
2180
+ evidence: [{
2181
+ span: c.span,
2182
+ role: "aggregate",
2183
+ detail: `${c.fn} ${r.name}`
2184
+ }]
2185
+ };
2186
+ const exclude = c.field.phrase?.entry.exclude;
2187
+ if (exclude !== void 0) out.exclude = exclude;
2188
+ const g = c.group;
2189
+ if (g === void 0) return out;
2190
+ const drop = (why) => {
2191
+ out.dropped.push({
2192
+ span: g.span,
2193
+ reason: why,
2194
+ kind: "order"
2195
+ });
2196
+ return out;
2197
+ };
2198
+ if (g.unit !== void 0) {
2199
+ if (g.unit !== "day" && g.unit !== "hour") return drop("only day and hour groupings are supported");
2200
+ const field = own(rulings.timeField, type) ?? "createdAt";
2201
+ out.dateGroup = {
2202
+ field,
2203
+ by: g.unit
2204
+ };
2205
+ out.evidence.push({
2206
+ span: g.span,
2207
+ role: "field",
2208
+ detail: `bucket ${field} by ${g.unit}`
2209
+ });
2210
+ return out;
2211
+ }
2212
+ const gr = seedField({
2213
+ span: g.span,
2214
+ ...g.field
2215
+ }, type, pack, rulings, "grouping");
2216
+ if ("reason" in gr) return drop(gr.reason);
2217
+ const values = gr.f.valueType === "boolean" ? [true, false] : gr.f.kind === "scalar" ? gr.f.enum : void 0;
2218
+ if (values === void 0) return drop(`only enum and yes/no fields group; ${gr.name} is a ${gr.f.valueType ?? gr.f.kind} field`);
2219
+ if (values.length > MAX_GROUPS) return drop(`${gr.name} has ${values.length} values; grouping runs one frame per value, at most ${MAX_GROUPS}`);
2220
+ out.group = {
2221
+ field: gr.name,
2222
+ values
2223
+ };
2224
+ out.evidence.push({
2225
+ span: g.span,
2226
+ role: "field",
2227
+ detail: `group by ${gr.name}`
2228
+ });
2229
+ return out;
2230
+ }
2231
+ /** The seed field an ordering sorts by on `type`, the value one hop away, or why neither. */
2232
+ function orderField(o, type, pack, rulings) {
2233
+ const away = fieldAway(o, type, pack, rulings);
2234
+ if (away !== null) return "reason" in away ? away : hopOrder(o, type, away, pack, rulings);
2235
+ const r = seedField(o, type, pack, rulings, "ordering");
2236
+ if ("reason" in r) return r;
2237
+ const { name, f } = r;
2238
+ if (o.pick !== void 0) return { reason: pickReason(o.pick, `${type}.${name}`, type) };
2239
+ if (!((f.kind === "scalar" || f.kind === "metadata") && (f.valueType === "number" || f.valueType === "date" && o.numeric !== true))) return { reason: o.numeric === true ? `"most" needs a number field; ${name} is a ${f.valueType ?? f.kind} field` : `${name} is a ${f.valueType ?? f.kind} field; only number and date fields order` };
2240
+ return { field: name };
2241
+ }
2242
+ /** Why a pick word cannot order: it is not a direction, or there is one value per seed row. */
2243
+ function pickReason(pick, field, seed) {
2244
+ return pick.kind === "latest" ? `"${pick.span}" picks one of many rows; ${field} is one value per ${seed.toLowerCase()}` : `"${pick.span}" is not an ordering direction; say lowest or highest`;
2245
+ }
2246
+ /** The field an ordering names on a type other than `seed`, null when it is the seed's (or none). */
2247
+ function fieldAway(o, seed, pack, rulings) {
2248
+ if (o.phrase !== void 0) {
2249
+ const { type, field } = o.phrase;
2250
+ return type === void 0 || field === void 0 || type === seed ? null : {
2251
+ type,
2252
+ field
2253
+ };
2254
+ }
2255
+ const words = o.words ?? "";
2256
+ if (o.type !== void 0) {
2257
+ if (o.type === seed) return null;
2258
+ const field = fieldByWords(words, own(pack.types, o.type)?.fields ?? {}, rulings);
2259
+ return field === null ? { reason: `${o.type} has no field "${words}"` } : {
2260
+ type: o.type,
2261
+ field
2262
+ };
2263
+ }
2264
+ if (fieldByWords(words, own(pack.types, seed)?.fields ?? {}, rulings) !== null) return null;
2265
+ const on = Object.entries(pack.types).filter(([t, def]) => t !== seed && fieldByWords(words, def.fields, rulings) !== null).map(([t]) => t).sort();
2266
+ if (on.length === 0) return null;
2267
+ if (on.length > 1) return { reason: `"${words}" names a field on several types: ${on.join(", ")}` };
2268
+ const type = on[0];
2269
+ return {
2270
+ type,
2271
+ field: fieldByWords(words, own(pack.types, type)?.fields ?? {}, rulings)
2272
+ };
2273
+ }
2274
+ /**
2275
+ * The `_agg` an ordering by `<type>.<field>` sorts the seed by, over the one
2276
+ * crossRef hop between them. Out to one row, its value; in from many, a pick:
2277
+ * the asked one ("latest", "lowest" …), else max for a descending order and
2278
+ * min for an ascending one.
2279
+ */
2280
+ function hopOrder(o, seed, to, pack, rulings) {
2281
+ const paths = findPaths(pack, seed, to.type);
2282
+ if (paths.length === 0) return { reason: `no crossRef path from ${seed} to ${to.type} within 3 hops` };
2283
+ if (paths.length > 1) return { reason: `several equally short paths from ${seed} to ${to.type}: ${paths.map((p) => pathLabel(pack.namespace, p)).join("; ")}` };
2284
+ const path = paths[0];
2285
+ if (path.length > 1) return { reason: `ordering across ${path.length} hops is not supported; one hop only` };
2286
+ const f = own(pack.types, to.type)?.fields[to.field];
2287
+ const qualified = `${to.type}.${to.field}`;
2288
+ if (f === void 0 || f.kind !== "scalar" && f.kind !== "metadata" || f.valueType !== "number") return { reason: `ordering across a hop needs a number field; ${qualified} is a ${f?.valueType ?? f?.kind} field` };
2289
+ const h = path[0];
2290
+ if (o.pick !== void 0 && (h.dir === "out" || o.pick.kind !== "latest")) return { reason: pickReason(o.pick, qualified, seed) };
2291
+ const cap = to.field.charAt(0).toUpperCase() + to.field.slice(1);
2292
+ const exclude = o.phrase?.entry.exclude;
2293
+ const where = exclude !== void 0 ? { where: { NOT: exclude } } : {};
2294
+ if (h.dir === "out") return { hop: {
2295
+ name: `${to.type.charAt(0).toLowerCase()}${to.type.slice(1)}${cap}`,
2296
+ agg: {
2297
+ out: h.field,
2298
+ ...where,
2299
+ max: to.field
2300
+ },
2301
+ label: `${qualified} via ${h.field}`
2302
+ } };
2303
+ const kind = o.pick?.kind ?? o.phrase?.entry.pick ?? (o.dir === "desc" ? "max" : "min");
2304
+ const by = own(rulings.timeField, to.type) ?? "createdAt";
2305
+ return { hop: {
2306
+ name: `${kind}${to.type}${cap}`,
2307
+ agg: {
2308
+ in: `${pack.namespace}/${h.owner}.${h.field}`,
2309
+ ...where,
2310
+ ...kind === "latest" ? { latest: {
2311
+ by,
2312
+ value: to.field
2313
+ } } : { [kind]: to.field }
2314
+ },
2315
+ label: `${kind}(${qualified}) per ${seed.toLowerCase()}`
2316
+ } };
2317
+ }
2318
+ /** A clause's field name: the field itself, case-insensitively, then the rulings' and built-in aliases. */
2319
+ function resolveField(raw, fields, rulings) {
2320
+ const lower = raw.toLowerCase();
2321
+ const direct = Object.keys(fields).find((f) => f.toLowerCase() === lower);
2322
+ if (direct !== void 0) return direct;
2323
+ const aliased = own(rulings.fieldAliases, lower) ?? own(BUILTIN_FIELD_ALIASES, lower);
2324
+ return aliased !== void 0 && Object.hasOwn(fields, aliased) ? aliased : null;
2325
+ }
2326
+ /** A clause value as the field's type, or undefined when it is not one. */
2327
+ function coerce(raw, f) {
2328
+ if (f.valueType === "number") {
2329
+ const n = Number(raw);
2330
+ return Number.isFinite(n) ? n : void 0;
2331
+ }
2332
+ if (f.valueType === "boolean") return raw === "true" ? true : raw === "false" ? false : void 0;
2333
+ return raw;
2334
+ }
2335
+ /** Types that have every field the clauses name, sorted. */
2336
+ function typesWithFields(pack, clauses, rulings) {
2337
+ return Object.entries(pack.types).filter(([, t]) => clauses.every((c) => resolveField(c.field, t.fields, rulings) !== null)).map(([name]) => name).sort();
2338
+ }
2339
+ /** Marks unused tokens naming `field` as explained; true when any did. */
2340
+ function creditFieldWords(tokens, field) {
2341
+ if (field === void 0) return false;
2342
+ let hit = false;
2343
+ for (const phrase of field.phrases) {
2344
+ const parts = phrase.split(" ");
2345
+ const stem = (parts[parts.length - 1] ?? "").replace(/s$/, "");
2346
+ for (let i = 0; i + parts.length <= tokens.length; i++) {
2347
+ const slice = tokens.slice(i, i + parts.length);
2348
+ if (slice.some((t) => t.used)) continue;
2349
+ const text = slice.map((t) => t.text).join(" ");
2350
+ const last = slice[slice.length - 1]?.text ?? "";
2351
+ const head = slice.slice(0, -1).map((t) => t.text).join(" ");
2352
+ const headWant = parts.slice(0, -1).join(" ");
2353
+ if (text === phrase || head === headWant && stem.length >= 3 && last.startsWith(stem)) {
2354
+ for (const t of slice) t.used = true;
2355
+ hit = true;
2356
+ }
2357
+ }
2358
+ }
2359
+ return hit;
2360
+ }
2361
+ function contentWords(tokens) {
2362
+ const free = (t) => t !== void 0 && !t.used && !GLUE.has(t.text);
2363
+ const num = (t) => free(t) && /^\d+$/.test(t.text);
2364
+ const out = [];
2365
+ tokens.forEach((t, i) => {
2366
+ if (!free(t) || num(t)) return;
2367
+ const before = num(tokens[i - 1]) ? `${tokens[i - 1]?.text} ` : "";
2368
+ const after = num(tokens[i + 1]) && !(free(tokens[i + 2]) && !num(tokens[i + 2])) ? ` ${tokens[i + 1]?.text}` : "";
2369
+ out.push(`${before}${t.text}${after}`);
2370
+ });
2371
+ return out;
2372
+ }
2373
+ /** Claims the longest n-grams (up to `max` words) for which `accept` returns true. */
2374
+ function claimNgrams(tokens, max, accept) {
2375
+ for (let n = max; n >= 1; n--) for (let i = 0; i + n <= tokens.length; i++) {
2376
+ const slice = tokens.slice(i, i + n);
2377
+ if (slice.some((t) => t.used)) continue;
2378
+ const at = slice.map((_, j) => i + j);
2379
+ if (!accept(slice.map((t) => t.text).join(" "), at)) continue;
2380
+ for (const t of slice) t.used = true;
2381
+ }
2382
+ }
2383
+ /** Type phrases: rulings aliases, then the pack's, plus each multi-word type's first word. Longest first. */
2384
+ function buildTypeIndex(pack, rulings) {
2385
+ const map = /* @__PURE__ */ new Map();
2386
+ const add = (phrase, type, plural) => {
2387
+ const e = map.get(phrase) ?? {
2388
+ types: /* @__PURE__ */ new Set(),
2389
+ plural
2390
+ };
2391
+ e.types.add(type);
2392
+ map.set(phrase, e);
2393
+ };
2394
+ const aliased = new Set(Object.keys(rulings.typeAliases ?? {}));
2395
+ for (const [phrase, type] of Object.entries(rulings.typeAliases ?? {})) add(phrase, type, phrase.endsWith("s"));
2396
+ for (const [name, t] of Object.entries(pack.types)) {
2397
+ const words = splitWords(name);
2398
+ const singulars = /* @__PURE__ */ new Set([words.join(" "), words[words.length - 1] ?? ""]);
2399
+ for (const p of [...t.phrases, name.toLowerCase()]) if (!aliased.has(p)) add(p, name, !singulars.has(p) && p !== name.toLowerCase());
2400
+ if (words.length > 1) {
2401
+ const first = words[0];
2402
+ if (!aliased.has(first)) add(first, name, false);
2403
+ if (!aliased.has(pluralize(first))) add(pluralize(first), name, true);
2404
+ }
2405
+ }
2406
+ return [...map].map(([phrase, e]) => ({
2407
+ phrase,
2408
+ types: [...e.types].sort(),
2409
+ plural: e.plural
2410
+ })).sort((x, y) => y.phrase.split(" ").length - x.phrase.split(" ").length || x.phrase.localeCompare(y.phrase));
2411
+ }
2412
+ function fieldNamed(pack, word) {
2413
+ return Object.values(pack.types).some((t) => Object.values(t.fields).some((f) => f.phrases.includes(word)));
2414
+ }
2415
+ /** Types every value can be read as, sorted. */
2416
+ function typesCovering(pack, values) {
2417
+ let acc = null;
2418
+ for (const v of values) {
2419
+ const types = new Set(v.alias !== void 0 ? v.alias.map((x) => x.type) : (own(pack.values, v.key) ?? []).map((r) => r.type));
2420
+ acc = acc === null ? [...types] : acc.filter((t) => types.has(t));
2421
+ }
2422
+ return [...acc ?? []].sort();
2423
+ }
2424
+ /** Types whose `status` enum has a terminal value. */
2425
+ function closableTypes(pack) {
2426
+ return Object.entries(pack.types).filter(([, t]) => t.fields.status?.enum?.some((v) => CLOSED.includes(v)) === true).map(([name]) => name).sort();
2427
+ }
2428
+ /**
2429
+ * The field a value reads as when it fits several on one type: a field named
2430
+ * in the question first, then the most categorical (fewest distinct values,
2431
+ * enum size for enums), then name order.
2432
+ */
2433
+ function pickField(candidates, fields, words) {
2434
+ const unique = [...new Set(candidates)];
2435
+ const text = ` ${words.join(" ")} `;
2436
+ const stem = (p) => p.replace(/s$/, "");
2437
+ const named = unique.filter((f) => fields[f]?.phrases.some((p) => text.includes(` ${p} `) || stem(p).length >= 3 && words.some((w) => w !== p && w.startsWith(stem(p)))));
2438
+ const pool = named.length > 0 ? named : unique;
2439
+ const size = (f) => fields[f]?.enum?.length ?? fields[f]?.distinct ?? Number.MAX_SAFE_INTEGER;
2440
+ return [...pool].sort((x, y) => size(x) - size(y) || x.localeCompare(y))[0];
2441
+ }
2442
+ function claimTime(tokens, asOf) {
2443
+ let found = null;
2444
+ claimNgrams(tokens, 8, (key, at) => {
2445
+ if (found !== null) return false;
2446
+ const range = rangeFor(key, asOf);
2447
+ if (range === null) return false;
2448
+ found = {
2449
+ span: key,
2450
+ range,
2451
+ at: [at[0], at[at.length - 1]]
2452
+ };
2453
+ return true;
2454
+ });
2455
+ return found;
2456
+ }
2457
+
2458
+ //#endregion
2459
+ //#region src/judge/judge.ts
2460
+ /** String scalar fields a binding may target, as `Type.field`. */
2461
+ function bindableFields(pack, types) {
2462
+ const out = [];
2463
+ for (const type of types) for (const [name, f] of Object.entries(pack.types[type]?.fields ?? {})) if (f.kind === "scalar" && f.valueType === "string" && f.indexed) out.push(`${type}.${name}`);
2464
+ return out.sort();
2465
+ }
2466
+ /** Build the options, the prompt and the schema for one escalated parse. */
2467
+ function buildJudgePrompt(question, result, pack, rulings = {}, rejected = []) {
2468
+ const allTypes = Object.keys(pack.types).sort();
2469
+ const words = [...new Set(result.residual)];
2470
+ const fields = bindableFields(pack, result.candidates.length > 0 ? [...new Set(result.candidates.map((c) => c.type))] : allTypes);
2471
+ const branch = (action, args = {}) => ({
2472
+ type: "object",
2473
+ properties: {
2474
+ action: { const: action },
2475
+ ...args
2476
+ },
2477
+ required: ["action", ...Object.keys(args)]
2478
+ });
2479
+ const schema = { anyOf: [
2480
+ ...result.candidates.length > 0 ? [branch("pick", { candidate: {
2481
+ type: "integer",
2482
+ enum: result.candidates.map((_, i) => i)
2483
+ } })] : [],
2484
+ branch("type", { type: {
2485
+ type: "string",
2486
+ enum: allTypes
2487
+ } }),
2488
+ ...words.length > 0 && fields.length > 0 ? [branch("bind", {
2489
+ word: {
2490
+ type: "string",
2491
+ enum: words
2492
+ },
2493
+ field: {
2494
+ type: "string",
2495
+ enum: fields
2496
+ },
2497
+ op: {
2498
+ type: "string",
2499
+ enum: [
2500
+ "eq",
2501
+ "startsWith",
2502
+ "contains"
2503
+ ]
2504
+ }
2505
+ })] : [],
2506
+ branch("recall", { type: {
2507
+ type: "string",
2508
+ enum: allTypes
2509
+ } }),
2510
+ branch("clarify"),
2511
+ branch("refuse"),
2512
+ branch("escalate")
2513
+ ] };
2514
+ const ruled = (t) => Object.entries(rulings.typeAliases ?? {}).filter(([, type]) => type === t).map(([phrase]) => phrase);
2515
+ const typeLines = allTypes.map((t) => {
2516
+ const note = rulings.typeNotes?.[t];
2517
+ const names = [...ruled(t), ...(pack.types[t]?.phrases ?? []).slice(0, 4)].join(", ");
2518
+ return `- ${t}${note !== void 0 ? ` (${note})` : ""}: ${names}`;
2519
+ });
2520
+ const candidateLines = result.candidates.map((c, i) => `${i}. ${c.type} where ${JSON.stringify(Object.values(c.frame)[0]?.params.where ?? {})} (from: ${c.evidence.map((e) => `"${e.span}"=${e.detail}`).join("; ")})`);
2521
+ return {
2522
+ system: [
2523
+ "You choose how a question about a data store should be answered. You do not write queries.",
2524
+ "A deterministic parser read the question first and could not settle it. Choose ONE action:",
2525
+ "- pick: one reading answers the WHOLE question as asked; leftover words are noise. If the",
2526
+ " question needs rows of one type found through another, no single reading answers it.",
2527
+ "- type: the question lists or counts rows of one type; the parser then builds the query from the",
2528
+ " question's own words (dates, \"latest\", known values). Prefer this when a type clearly fits.",
2529
+ "- bind: a leftover word is a value stored in a field: eq = the whole value, startsWith = a prefix",
2530
+ " of a name or id, contains = a word inside a title or subject. Never bind a word that only",
2531
+ " describes the question (e.g. \"status\", \"called\").",
2532
+ "- recall: the question asks what is known ABOUT a topic (free-text subject words, not field values);",
2533
+ " semantic search over the text answers it. Name the type whose rows hold that knowledge.",
2534
+ "- clarify: RARE. Only when the question has two specific readings and nothing in it chooses one.",
2535
+ " Missing detail is not ambiguity: if a type or a topic fits, choose type or recall.",
2536
+ "- refuse: the question is not about this store at all, or asks to change data.",
2537
+ "- escalate: none of these answers the question as asked (e.g. it needs two queries chained).",
2538
+ "",
2539
+ `Types in the "${pack.namespace}" store:`,
2540
+ ...typeLines
2541
+ ].join("\n"),
2542
+ user: [
2543
+ `Question: ${question}`,
2544
+ `Parser: ${result.status}${result.reason !== void 0 ? ` (${result.reason})` : ""}`,
2545
+ ...result.evidence !== void 0 && result.evidence.length > 0 ? [`Understood so far: ${result.evidence.map((e) => `"${e.span}" = ${e.role} ${e.detail}`).join("; ")}`] : [],
2546
+ ...candidateLines.length > 0 ? ["Readings:", ...candidateLines] : [],
2547
+ ...words.length > 0 ? [`Leftover words: ${words.join(", ")}`] : [],
2548
+ ...rejected.map((r) => `Already tried and rejected: ${r}`)
2549
+ ].join("\n"),
2550
+ schema
2551
+ };
2552
+ }
2553
+ /** Check a reply against the options it was offered. */
2554
+ function checkChoice(reply, prompt) {
2555
+ if (typeof reply !== "object" || reply === null) return "reply is not an object";
2556
+ const r = reply;
2557
+ const branch = (prompt.schema.anyOf ?? []).find((b) => b.properties.action?.const === r.action);
2558
+ if (branch === void 0) return `action ${JSON.stringify(r.action)} was not offered`;
2559
+ const choice = { action: r.action };
2560
+ for (const key of branch.required) {
2561
+ if (key === "action") continue;
2562
+ if (branch.properties[key]?.enum?.includes(r[key]) !== true) return `${String(r.action)} needs an offered ${key}`;
2563
+ choice[key] = r[key];
2564
+ }
2565
+ return choice;
2566
+ }
2567
+ /** A binding becomes a one-question ruling, so the parser applies it like any other. */
2568
+ function withBinding(rulings, choice) {
2569
+ const [type, field] = choice.field.split(".");
2570
+ const word = choice.word;
2571
+ const alias = choice.op === "startsWith" ? {
2572
+ type,
2573
+ field,
2574
+ startsWith: word
2575
+ } : choice.op === "contains" ? {
2576
+ type,
2577
+ field,
2578
+ contains: word
2579
+ } : {
2580
+ type,
2581
+ field,
2582
+ eq: word
2583
+ };
2584
+ return {
2585
+ ...rulings ?? {},
2586
+ valueAliases: {
2587
+ ...rulings?.valueAliases ?? {},
2588
+ [word]: [alias]
2589
+ }
2590
+ };
2591
+ }
2592
+ /** Why a binding cannot be applied, or null when it grounds. */
2593
+ async function verifyBinding(choice, earlier, pack, opts) {
2594
+ const [type, field] = choice.field.split(".");
2595
+ const word = choice.word;
2596
+ const def = own(own(pack.types, type)?.fields, field);
2597
+ if (def === void 0) return `${type}.${field} is not a field`;
2598
+ if (!def.operators.includes(choice.op)) return `${type}.${field} does not accept ${choice.op}`;
2599
+ if (def.enum !== void 0 && choice.op === "eq") {
2600
+ if (![...def.enum, ...Object.keys(def.aliases ?? {})].map((v) => v.toLowerCase()).includes(word.toLowerCase())) return `"${word}" is not a ${type}.${field} value`;
2601
+ }
2602
+ if (opts.exists === void 0) return null;
2603
+ const predicate = (c) => ({ [c.field.split(".")[1]]: { [c.op]: c.word } });
2604
+ const same = earlier.filter((c) => c.field.startsWith(`${type}.`));
2605
+ const where = same.length === 0 ? predicate(choice) : { AND: [...same, choice].map(predicate) };
2606
+ if (!await opts.exists(type, where)) return same.length === 0 ? `no ${type} has ${field} ${choice.op} "${word}"` : `no ${type} matches it together with ${same.map((c) => `"${c.word}"`).join(", ")}`;
2607
+ return null;
2608
+ }
2609
+ /**
2610
+ * Parse; while the parse is not resolved, ask the judge and apply its choice.
2611
+ * A refused, clarified or resolved parse never reaches the model.
2612
+ */
2613
+ async function parseWithJudge(question, pack, ctx, judge, opts = {}) {
2614
+ const trail = [];
2615
+ let context = ctx;
2616
+ let result = parseQuestion(question, pack, context);
2617
+ const rejected = [];
2618
+ const bound = [];
2619
+ for (let round = 0; round < (opts.rounds ?? 3); round++) {
2620
+ if (result.status === "resolved") return {
2621
+ status: "resolved",
2622
+ candidate: result.candidates[0],
2623
+ trail
2624
+ };
2625
+ if (result.status === "refuse" || result.status === "clarify") return {
2626
+ status: result.status,
2627
+ reason: result.reason ?? "",
2628
+ trail
2629
+ };
2630
+ const step = { parse: {
2631
+ status: result.status,
2632
+ ...result.reason !== void 0 ? { reason: result.reason } : {}
2633
+ } };
2634
+ trail.push(step);
2635
+ const prompt = buildJudgePrompt(question, result, pack, context.rulings, rejected);
2636
+ const reply = await judge.decide(prompt, opts.signal);
2637
+ const checked = checkChoice(reply, prompt);
2638
+ if (typeof checked === "string") {
2639
+ step.rejected = checked;
2640
+ break;
2641
+ }
2642
+ step.choice = checked;
2643
+ const extra = Object.keys(reply).filter((k) => !Object.hasOwn(checked, k));
2644
+ if (extra.length > 0) step.ignored = extra.sort();
2645
+ switch (checked.action) {
2646
+ case "pick": {
2647
+ const chosen = result.candidates[checked.candidate];
2648
+ if (chosen.dropped.length > 0) {
2649
+ const reason = `dropped: ${chosen.dropped.map((d) => `"${d.span}" (${d.reason})`).join("; ")}`;
2650
+ return {
2651
+ status: "escalated",
2652
+ result: {
2653
+ status: "partial",
2654
+ candidates: [chosen],
2655
+ residual: chosen.residual,
2656
+ reason
2657
+ },
2658
+ trail
2659
+ };
2660
+ }
2661
+ if (chosen.strict && chosen.residual.length > 0) {
2662
+ const reason = `unexplained under a strict reading: ${chosen.residual.join(", ")}`;
2663
+ return {
2664
+ status: "escalated",
2665
+ result: {
2666
+ status: "partial",
2667
+ candidates: [chosen],
2668
+ residual: chosen.residual,
2669
+ reason
2670
+ },
2671
+ trail
2672
+ };
2673
+ }
2674
+ return {
2675
+ status: "resolved",
2676
+ candidate: chosen,
2677
+ trail
2678
+ };
2679
+ }
2680
+ case "recall": return {
2681
+ status: "recall",
2682
+ query: question,
2683
+ type: checked.type,
2684
+ trail
2685
+ };
2686
+ case "clarify":
2687
+ case "refuse": return {
2688
+ status: checked.action,
2689
+ reason: "judge",
2690
+ trail
2691
+ };
2692
+ case "type":
2693
+ context = {
2694
+ ...context,
2695
+ forceType: checked.type
2696
+ };
2697
+ break;
2698
+ case "escalate": return {
2699
+ status: "escalated",
2700
+ result,
2701
+ trail
2702
+ };
2703
+ case "bind": {
2704
+ const why = await verifyBinding(checked, bound, pack, opts);
2705
+ if (why !== null) {
2706
+ step.rejected = why;
2707
+ rejected.push(`bind ${checked.word} to ${checked.field} (${why})`);
2708
+ continue;
2709
+ }
2710
+ bound.push(checked);
2711
+ context = {
2712
+ ...context,
2713
+ rulings: withBinding(context.rulings, checked)
2714
+ };
2715
+ break;
2716
+ }
2717
+ }
2718
+ result = parseQuestion(question, pack, context);
2719
+ }
2720
+ if (result.status === "resolved") return {
2721
+ status: "resolved",
2722
+ candidate: result.candidates[0],
2723
+ trail
2724
+ };
2725
+ return {
2726
+ status: "escalated",
2727
+ result,
2728
+ trail
2729
+ };
2730
+ }
2731
+
2732
+ //#endregion
2733
+ //#region src/ask/run.ts
2734
+ const RECALL_K = 10;
2735
+ /**
2736
+ * The frame a candidate needs to run. A count is the server's `count: true`
2737
+ * over the reading's where, an aggregate its `aggregate`; `paged` is the rows
2738
+ * frame with every projectable field, which a count falls back to when the
2739
+ * server cannot count.
2740
+ */
2741
+ function executable(c, pack, paged = c.answer !== "count" && c.answer !== "aggregate") {
2742
+ const [key, value] = Object.entries(c.frame)[0];
2743
+ const { count: _count, ...params } = value.params;
2744
+ if (!paged) {
2745
+ const { orderBy: _o, limit: _l, select: _s, ...counted } = params;
2746
+ const shaped = c.answer === "aggregate" ? counted : {
2747
+ ...counted,
2748
+ count: true
2749
+ };
2750
+ return { [key]: {
2751
+ params: shaped,
2752
+ fields: { id: true }
2753
+ } };
2754
+ }
2755
+ const fields = { id: true };
2756
+ for (const [name, f] of Object.entries(own(pack.types, c.type)?.fields ?? {})) if (f.kind !== "metadata") fields[name] = true;
2757
+ return { [key]: {
2758
+ params,
2759
+ fields: {
2760
+ ...fields,
2761
+ ...value.fields
2762
+ }
2763
+ } };
2764
+ }
2765
+ /**
2766
+ * The engine refused `count: true`: the seed is under a row policy, or the
2767
+ * store (memory, legacy-layout pg) answers no walk grammar. A plain paged read
2768
+ * works in every case.
2769
+ */
2770
+ const COUNT_REFUSED = /* @__PURE__ */ new Set([
2771
+ ROW_POLICY_BLOCKS_WALK,
2772
+ WALKS_UNSUPPORTED_STORE,
2773
+ WALKS_NEED_PARTITIONED
2774
+ ]);
2775
+ /**
2776
+ * The parser's plan with the engine's `served`/`recommend` where the engine
2777
+ * planned the same clause (matched by path: the engine's path is a prefix of
2778
+ * the parser's labelled one, or, for a NOT, extends it). Parser-only clauses
2779
+ * keep their entries; engine-only clauses are appended.
2780
+ */
2781
+ function mergePlan(parsed, engine) {
2782
+ if (engine === void 0) return parsed;
2783
+ const kindOf = (c) => c.kind === "select" && c.path[0] === "orderBy" ? "order" : c.kind;
2784
+ const prefix = (a, b) => a.length <= b.length && a.every((x, i) => x === b[i]);
2785
+ const used = /* @__PURE__ */ new Set();
2786
+ return [...parsed.map((p) => {
2787
+ const same = engine.filter((e) => kindOf(e) === kindOf(p));
2788
+ const under = same.filter((e) => prefix(e.path, p.path)).sort((x, y) => y.path.length - x.path.length);
2789
+ const matches = under.length > 0 ? [under[0]] : same.filter((e) => prefix(p.path.slice(0, -1), e.path));
2790
+ if (matches.length === 0) return p;
2791
+ for (const m of matches) used.add(m);
2792
+ const { recommend: _r, ...rest } = p;
2793
+ const recommend = matches.find((m) => !m.served)?.recommend;
2794
+ return {
2795
+ ...rest,
2796
+ served: matches.every((m) => m.served),
2797
+ ...recommend !== void 0 ? { recommend } : {}
2798
+ };
2799
+ }), ...engine.filter((e) => !used.has(e))];
2800
+ }
2801
+ async function rows(c, source, question, http, deps, handoff, leftovers = []) {
2802
+ const dropped = [...c.dropped, ...leftovers];
2803
+ if (c.strict && dropped.some((d) => d.kind === "filter")) return {
2804
+ kind: "unknown",
2805
+ question,
2806
+ dropped,
2807
+ plan: c.plan
2808
+ };
2809
+ let frame = executable(c, deps.pack);
2810
+ const key = Object.keys(frame)[0];
2811
+ if (c.aggregate !== void 0) return aggregate(c, frame, key, source, http, deps, dropped, handoff);
2812
+ let env = await deps.engine.query(frame, http);
2813
+ const refused = (env.errors ?? []).some((e) => COUNT_REFUSED.has(e.code ?? ""));
2814
+ const paging = c.answer === "count" && !(key in (env.data ?? {})) && refused;
2815
+ if (paging) {
2816
+ frame = executable(c, deps.pack, true);
2817
+ env = await deps.engine.query(frame, http);
2818
+ }
2819
+ const data = env.data !== void 0 && key in env.data ? env.data?.[key] : void 0;
2820
+ const errors = [...env.errors ?? []];
2821
+ let count;
2822
+ if (paging && Array.isArray(data)) {
2823
+ const counted = await countRest(frame, key, data.length, env, http, deps);
2824
+ if (typeof counted === "number") count = counted;
2825
+ else errors.push(counted);
2826
+ } else if (c.answer === "count" && typeof data?.count === "number") count = data.count;
2827
+ return {
2828
+ kind: "rows",
2829
+ frame,
2830
+ answer: c.answer,
2831
+ data,
2832
+ ...count !== void 0 ? { count } : {},
2833
+ ...errors.length > 0 ? { errors } : {},
2834
+ source,
2835
+ ...handoff !== void 0 ? { handoff } : {},
2836
+ dropped,
2837
+ plan: mergePlan(c.plan, env._diagnostics?.[key]?.plan)
2838
+ };
2839
+ }
2840
+ /**
2841
+ * An aggregate answer: the engine's one frame, or, grouped by a field the
2842
+ * engine cannot group, one frame per value of it.
2843
+ */
2844
+ async function aggregate(c, frame, key, source, http, deps, dropped, handoff) {
2845
+ const { fn, field, group } = c.aggregate;
2846
+ const params = frame[key]?.params;
2847
+ const errors = [];
2848
+ let data;
2849
+ let plan;
2850
+ if (group === void 0) {
2851
+ const env = await deps.engine.query(frame, http);
2852
+ errors.push(...env.errors ?? []);
2853
+ data = env.data !== void 0 && key in env.data ? env.data[key] : void 0;
2854
+ plan = env._diagnostics?.[key]?.plan;
2855
+ } else {
2856
+ const keys = [...group.values, null];
2857
+ const values = await Promise.all(keys.map(async (v) => {
2858
+ if (isAborted(http)) return void 0;
2859
+ const one = { [group.field]: { eq: v } };
2860
+ const where = params.where === void 0 ? one : { AND: [params.where, one] };
2861
+ const env = await deps.engine.query({ [key]: {
2862
+ params: {
2863
+ ...params,
2864
+ where
2865
+ },
2866
+ fields: { id: true }
2867
+ } }, http);
2868
+ errors.push(...env.errors ?? []);
2869
+ return (env.data?.[key])?.groups?.[0]?.value;
2870
+ }));
2871
+ data = values.some((v) => v === void 0) ? void 0 : { groups: keys.map((k, i) => ({
2872
+ key: k,
2873
+ value: values[i]
2874
+ })).filter((g) => g.key !== null || g.value !== null) };
2875
+ }
2876
+ const trunc = params.groupBy?.bucket?.dateTrunc;
2877
+ const by = group?.field ?? trunc?.[0].lit;
2878
+ const short = (k) => typeof k === "string" && trunc !== void 0 ? k.slice(0, trunc[0].lit === "day" ? 10 : 13) : k;
2879
+ const rows = data?.groups;
2880
+ const result = rows === void 0 ? void 0 : {
2881
+ fn,
2882
+ field,
2883
+ ...by !== void 0 ? {
2884
+ by,
2885
+ groups: rows.filter((g) => trunc === void 0 || g.bucket !== null).map((g) => ({
2886
+ key: short(g.bucket ?? g.key),
2887
+ value: g.value
2888
+ }))
2889
+ } : { value: rows[0]?.value ?? null },
2890
+ ...data?.truncated === true ? { truncated: true } : {}
2891
+ };
2892
+ return {
2893
+ kind: "rows",
2894
+ frame,
2895
+ answer: c.answer,
2896
+ data,
2897
+ ...result !== void 0 ? { aggregate: result } : {},
2898
+ ...errors.length > 0 ? { errors } : {},
2899
+ source,
2900
+ ...handoff !== void 0 ? { handoff } : {},
2901
+ dropped,
2902
+ plan: mergePlan(c.plan, plan)
2903
+ };
2904
+ }
2905
+ const MAX_COUNT_PAGES = 1e3;
2906
+ /** The population a count candidate matches: `seen` rows from page one, then id-only pages after its cursor. */
2907
+ async function countRest(frame, key, seen, first, http, deps) {
2908
+ const params = frame[key]?.params ?? {};
2909
+ let count = seen;
2910
+ let page = first._pagination?.[key];
2911
+ for (let pages = 1; page?.hasMore === true; pages++) {
2912
+ if (pages >= MAX_COUNT_PAGES || page.nextCursor === void 0 || isAborted(http)) return {
2913
+ code: "count_incomplete",
2914
+ message: `counted ${count} rows and stopped before the end; the true count is higher`
2915
+ };
2916
+ const env = await deps.engine.query({ [key]: {
2917
+ params: {
2918
+ ...params,
2919
+ cursor: page.nextCursor
2920
+ },
2921
+ fields: { id: true }
2922
+ } }, http);
2923
+ const rows = env.data?.[key];
2924
+ if (!Array.isArray(rows)) return {
2925
+ code: "count_incomplete",
2926
+ message: `counted ${count} rows, then a page failed: ${JSON.stringify(env.errors ?? [])}`
2927
+ };
2928
+ count += rows.length;
2929
+ page = env._pagination?.[key];
2930
+ }
2931
+ return count;
2932
+ }
2933
+ async function recall(query, ns, type, http, deps) {
2934
+ const frame = { "recall/Hit": {
2935
+ params: {
2936
+ to: query,
2937
+ namespace: ns,
2938
+ type,
2939
+ k: RECALL_K
2940
+ },
2941
+ fields: {
2942
+ id: true,
2943
+ namespace: true,
2944
+ type: true,
2945
+ score: true,
2946
+ row: true
2947
+ }
2948
+ } };
2949
+ const env = await deps.engine.query(frame, http);
2950
+ const hits = env.data?.["recall/Hit"];
2951
+ return {
2952
+ kind: "recall",
2953
+ query,
2954
+ hits: Array.isArray(hits) ? hits : void 0,
2955
+ ...env.errors !== void 0 && env.errors.length > 0 ? { errors: env.errors } : {}
2956
+ };
2957
+ }
2958
+ function clarify(question, reason, candidates, pack) {
2959
+ const seen = /* @__PURE__ */ new Set();
2960
+ const options = [];
2961
+ for (const c of candidates) {
2962
+ if (seen.has(c.type)) continue;
2963
+ seen.add(c.type);
2964
+ const phrase = own(pack.types, c.type)?.phrases[0] ?? c.type;
2965
+ options.push({
2966
+ label: `${phrase} (${c.type})`,
2967
+ question,
2968
+ type: c.type
2969
+ });
2970
+ }
2971
+ return {
2972
+ kind: "clarify",
2973
+ question,
2974
+ reason,
2975
+ options
2976
+ };
2977
+ }
2978
+ const isAborted = (http) => http.signal?.aborted === true;
2979
+ async function* runAsk(req, http, deps) {
2980
+ const ctx = {
2981
+ asOf: req.asOf ?? (deps.now ?? (() => /* @__PURE__ */ new Date()))().toISOString(),
2982
+ rulings: deps.pack.rulings,
2983
+ ...req.project !== void 0 ? { project: req.project } : {},
2984
+ ...req.type !== void 0 ? { forceType: req.type } : {}
2985
+ };
2986
+ const first = parseQuestion(req.question, deps.pack, ctx);
2987
+ const best = first.candidates[0];
2988
+ yield {
2989
+ event: "parsed",
2990
+ status: first.status,
2991
+ ...best !== void 0 ? { frame: executable(best, deps.pack) } : {},
2992
+ evidence: best?.evidence ?? first.evidence ?? [],
2993
+ residual: first.residual,
2994
+ ...first.reason !== void 0 ? { reason: first.reason } : {},
2995
+ asOf: ctx.asOf
2996
+ };
2997
+ if (isAborted(http)) return yield { event: "done" };
2998
+ /**
2999
+ * No judge decided: the parser's reading runs as it stands. Its unexplained
3000
+ * words are dropped, so a strict reading with any is `unknown`, never a number.
3001
+ */
3002
+ const handoff = async (reason, parsed = first) => {
3003
+ const best = parsed.candidates[0];
3004
+ if (best === void 0) return clarify(req.question, reason, parsed.candidates, deps.pack);
3005
+ const leftovers = best.residual.map((w) => ({
3006
+ span: w,
3007
+ reason: `not understood (${reason})`,
3008
+ kind: "filter"
3009
+ }));
3010
+ return rows(best, "handoff", req.question, http, deps, reason, leftovers);
3011
+ };
3012
+ let outcome;
3013
+ if (first.status === "resolved" && best !== void 0) outcome = await rows(best, "parser", req.question, http, deps);
3014
+ else if (first.status === "refuse") outcome = {
3015
+ kind: "refuse",
3016
+ reason: first.reason ?? "refused"
3017
+ };
3018
+ else if (first.status === "clarify") outcome = clarify(req.question, first.reason ?? "which did you mean?", first.candidates, deps.pack);
3019
+ else if (deps.judge === void 0) outcome = await handoff("judge not configured");
3020
+ else {
3021
+ yield {
3022
+ event: "judging",
3023
+ reason: first.reason ?? first.status
3024
+ };
3025
+ const ac = new AbortController();
3026
+ const timer = setTimeout(() => ac.abort(/* @__PURE__ */ new Error("judge timeout")), deps.judgeTimeoutMs ?? 2e4);
3027
+ const onAbort = () => ac.abort(http.signal?.reason);
3028
+ http.signal?.addEventListener("abort", onAbort, { once: true });
3029
+ if (isAborted(http)) onAbort();
3030
+ let judged;
3031
+ try {
3032
+ const judging = parseWithJudge(req.question, deps.pack, ctx, deps.judge, {
3033
+ signal: ac.signal,
3034
+ exists: async (type, where) => {
3035
+ if (ac.signal.aborted) return false;
3036
+ const key = `${deps.pack.namespace}/${type}`;
3037
+ const r = (await deps.engine.query({ [key]: {
3038
+ params: {
3039
+ where,
3040
+ limit: 1
3041
+ },
3042
+ fields: { id: true }
3043
+ } }, http)).data?.[key];
3044
+ return Array.isArray(r) && r.length > 0;
3045
+ }
3046
+ });
3047
+ judging.catch(() => {});
3048
+ const gone = new Promise((_, reject) => {
3049
+ const fire = () => reject(ac.signal.reason);
3050
+ if (ac.signal.aborted) fire();
3051
+ else ac.signal.addEventListener("abort", fire, { once: true });
3052
+ });
3053
+ judged = await Promise.race([judging, gone]);
3054
+ } catch {
3055
+ judged = void 0;
3056
+ } finally {
3057
+ clearTimeout(timer);
3058
+ http.signal?.removeEventListener("abort", onAbort);
3059
+ }
3060
+ if (isAborted(http)) return yield { event: "done" };
3061
+ if (judged === void 0) outcome = await handoff("judge unavailable");
3062
+ else {
3063
+ yield {
3064
+ event: "judged",
3065
+ status: judged.status,
3066
+ trail: judged.trail
3067
+ };
3068
+ switch (judged.status) {
3069
+ case "resolved": {
3070
+ const noise = judged.candidate.residual.map((w) => ({
3071
+ span: w,
3072
+ reason: "judge: noise",
3073
+ kind: "filter"
3074
+ }));
3075
+ outcome = await rows(judged.candidate, "judge", req.question, http, deps, void 0, noise);
3076
+ break;
3077
+ }
3078
+ case "recall":
3079
+ outcome = await recall(judged.query, deps.pack.namespace, ctx.forceType ?? judged.type, http, deps);
3080
+ break;
3081
+ case "refuse":
3082
+ outcome = {
3083
+ kind: "refuse",
3084
+ reason: judged.reason
3085
+ };
3086
+ break;
3087
+ case "clarify":
3088
+ outcome = clarify(req.question, judged.reason, first.candidates, deps.pack);
3089
+ break;
3090
+ case "escalated": outcome = await handoff("judge could not decide", judged.result.candidates.length > 0 ? judged.result : first);
3091
+ }
3092
+ }
3093
+ }
3094
+ yield {
3095
+ event: "outcome",
3096
+ outcome
3097
+ };
3098
+ yield { event: "done" };
3099
+ }
3100
+
3101
+ //#endregion
3102
+ //#region src/judge/ollama.ts
3103
+ /**
3104
+ * Ollama's native chat endpoint with `format` set to the question's schema,
3105
+ * so decoding cannot leave the offered options. Thinking off, temperature 0
3106
+ * and a fixed seed. Sends no `num_ctx` / `keep_alive`: Ollama shares one
3107
+ * runner per model, and differing options force a reload for every client
3108
+ * (see substrate-embedder's README).
3109
+ */
3110
+ var OllamaJudge = class {
3111
+ #config;
3112
+ constructor(config) {
3113
+ this.#config = {
3114
+ ...config,
3115
+ baseUrl: trimTrailingSlashes(config.baseUrl)
3116
+ };
3117
+ }
3118
+ async decide(prompt, signal) {
3119
+ const timeout = AbortSignal.timeout(this.#config.timeoutMs ?? 6e4);
3120
+ const res = await fetch(`${this.#config.baseUrl}/api/chat`, {
3121
+ method: "POST",
3122
+ headers: { "content-type": "application/json" },
3123
+ signal: signal === void 0 ? timeout : AbortSignal.any([timeout, signal]),
3124
+ body: JSON.stringify({
3125
+ model: this.#config.model,
3126
+ stream: false,
3127
+ think: false,
3128
+ format: prompt.schema,
3129
+ options: {
3130
+ temperature: 0,
3131
+ seed: 0
3132
+ },
3133
+ messages: [{
3134
+ role: "system",
3135
+ content: prompt.system
3136
+ }, {
3137
+ role: "user",
3138
+ content: prompt.user
3139
+ }]
3140
+ })
3141
+ });
3142
+ if (!res.ok) throw new Error(`ollama ${res.status} ${res.statusText}`);
3143
+ const body = await res.json();
3144
+ return JSON.parse(body.message?.content ?? "");
3145
+ }
3146
+ };
3147
+
3148
+ //#endregion
3149
+ //#region src/pack/build.ts
3150
+ /** Longest value worth matching as a whole phrase. */
3151
+ const MAX_VALUE_LENGTH = 64;
3152
+ /**
3153
+ * A field is vocabulary when its values are labels rather than prose. The
3154
+ * test is length, not distinct count: an `area` with hundreds of one-word
3155
+ * values is vocabulary, a `title` with a dozen sentences is not.
3156
+ */
3157
+ const MAX_MEAN_WORDS = 3;
3158
+ /** Server-managed fields every type can filter on, with their value type. */
3159
+ const METADATA_FIELDS = {
3160
+ createdAt: {
3161
+ valueType: "date",
3162
+ phrases: ["created", "created at"]
3163
+ },
3164
+ updatedAt: {
3165
+ valueType: "date",
3166
+ phrases: ["updated", "updated at"]
3167
+ },
3168
+ createdById: {
3169
+ valueType: "string",
3170
+ phrases: ["created by", "author"]
3171
+ },
3172
+ createdByKind: {
3173
+ valueType: "string",
3174
+ phrases: ["created by kind"]
3175
+ },
3176
+ updatedById: {
3177
+ valueType: "string",
3178
+ phrases: ["updated by"]
3179
+ },
3180
+ updatedByKind: {
3181
+ valueType: "string",
3182
+ phrases: ["updated by kind"]
3183
+ }
3184
+ };
3185
+ /**
3186
+ * Builds the NL vocabulary for one namespace. Pure: the same schema, operator
3187
+ * table and profile always give byte-identical output, with sorted keys.
3188
+ */
3189
+ function buildNamespacePack(input) {
3190
+ const { namespace, schema, operators, profile } = input;
3191
+ const maxDistinct = input.maxDistinct ?? 1e3;
3192
+ const types = {};
3193
+ const refs = [];
3194
+ for (const typeName of Object.keys(schema.types).sort()) {
3195
+ const declared = schema.types[typeName]?.fields ?? {};
3196
+ const fields = {};
3197
+ for (const name of Object.keys(declared).sort()) {
3198
+ const def = declared[name];
3199
+ const field = packField(name, def, operators);
3200
+ fields[name] = field;
3201
+ for (const value of field.enum ?? []) refs.push({
3202
+ type: typeName,
3203
+ field: name,
3204
+ value
3205
+ });
3206
+ for (const alias of Object.keys(field.aliases ?? {})) refs.push({
3207
+ type: typeName,
3208
+ field: name,
3209
+ value: alias
3210
+ });
3211
+ const observed = profile?.types[typeName]?.[name];
3212
+ if (observed !== void 0 && field.indexed && isStringy(def) && !observed.truncated && observed.values.length <= maxDistinct && areLabels(observed.values)) {
3213
+ for (const value of observed.values) refs.push({
3214
+ type: typeName,
3215
+ field: name,
3216
+ value
3217
+ });
3218
+ field.distinct = observed.values.length;
3219
+ }
3220
+ }
3221
+ for (const [name, meta] of Object.entries(METADATA_FIELDS)) {
3222
+ if (name in fields) continue;
3223
+ fields[name] = {
3224
+ name,
3225
+ kind: "metadata",
3226
+ valueType: meta.valueType,
3227
+ indexed: true,
3228
+ operators: [...operators[`scalar.${meta.valueType}`] ?? []],
3229
+ phrases: meta.phrases
3230
+ };
3231
+ }
3232
+ types[typeName] = {
3233
+ name: typeName,
3234
+ phrases: typePhrases(typeName),
3235
+ fields: sortKeys(fields)
3236
+ };
3237
+ }
3238
+ return {
3239
+ namespace,
3240
+ schemaVersion: schema.schemaVersion,
3241
+ types,
3242
+ values: indexValues(refs)
3243
+ };
3244
+ }
3245
+ function packField(name, def, operators) {
3246
+ const phrases = uniqueSorted([splitWords(name).join(" "), name.toLowerCase()]);
3247
+ switch (def.kind) {
3248
+ case "scalar": return {
3249
+ name,
3250
+ kind: "scalar",
3251
+ valueType: def.type,
3252
+ indexed: def.indexed !== false,
3253
+ operators: [...operators[`scalar.${def.type}`] ?? []],
3254
+ phrases,
3255
+ ...def.enum !== void 0 ? { enum: [...def.enum] } : {},
3256
+ ...def.aliases !== void 0 ? { aliases: { ...def.aliases } } : {}
3257
+ };
3258
+ case "crossRef": return {
3259
+ name,
3260
+ kind: "crossRef",
3261
+ target: {
3262
+ namespace: def.ns,
3263
+ type: def.type
3264
+ },
3265
+ indexed: def.indexed !== false,
3266
+ operators: [...operators.crossRef ?? []],
3267
+ phrases
3268
+ };
3269
+ case "list": return {
3270
+ name,
3271
+ kind: "list",
3272
+ indexed: def.indexed === true,
3273
+ operators: [...operators.list ?? []],
3274
+ phrases
3275
+ };
3276
+ default: return {
3277
+ name,
3278
+ kind: "struct",
3279
+ indexed: false,
3280
+ operators: [],
3281
+ phrases
3282
+ };
3283
+ }
3284
+ }
3285
+ function areLabels(values) {
3286
+ if (values.length === 0) return false;
3287
+ return values.reduce((n, v) => n + v.trim().split(/\s+/).length, 0) / values.length <= MAX_MEAN_WORDS;
3288
+ }
3289
+ /** A string scalar, or a list of string scalars: the fields whose values read as words. */
3290
+ function isStringy(def) {
3291
+ if (def.kind === "scalar") return def.type === "string";
3292
+ return def.kind === "list" && def.of.kind === "scalar" && def.of.type === "string";
3293
+ }
3294
+ function typePhrases(typeName) {
3295
+ const words = splitWords(typeName);
3296
+ const last = words[words.length - 1] ?? typeName.toLowerCase();
3297
+ const head = words.slice(0, -1);
3298
+ const out = [[...head, last].join(" "), [...head, pluralize(last)].join(" ")];
3299
+ if (head.length > 0) out.push(last, pluralize(last));
3300
+ return uniqueSorted(out);
3301
+ }
3302
+ function indexValues(refs) {
3303
+ const byKey = /* @__PURE__ */ new Map();
3304
+ for (const ref of refs) {
3305
+ const key = ref.value.trim().toLowerCase();
3306
+ if (key.length === 0 || key.length > MAX_VALUE_LENGTH) continue;
3307
+ const bucket = byKey.get(key) ?? /* @__PURE__ */ new Map();
3308
+ bucket.set(`${ref.type}\u0000${ref.field}`, ref);
3309
+ byKey.set(key, bucket);
3310
+ }
3311
+ const out = {};
3312
+ for (const key of [...byKey.keys()].sort()) {
3313
+ const bucket = byKey.get(key);
3314
+ out[key] = [...bucket.keys()].sort().map((k) => bucket.get(k));
3315
+ }
3316
+ return out;
3317
+ }
3318
+ function sortKeys(obj) {
3319
+ return Object.fromEntries(Object.keys(obj).sort().map((k) => [k, obj[k]]));
3320
+ }
3321
+
3322
+ //#endregion
3323
+ //#region src/pack/profile.ts
3324
+ /**
3325
+ * Distinct values of every indexed string field (and indexed list-of-string
3326
+ * field) in the namespace, reading up to `maxRows` rows per type. A field that
3327
+ * passes `maxDistinct` is marked truncated and stops growing.
3328
+ */
3329
+ async function profileNamespace(input) {
3330
+ const maxDistinct = input.maxDistinct ?? 1e3;
3331
+ const maxRows = input.maxRows ?? 1e4;
3332
+ const types = {};
3333
+ for (const typeName of Object.keys(input.schema.types).sort()) {
3334
+ const declared = input.schema.types[typeName]?.fields ?? {};
3335
+ const fields = Object.keys(declared).filter((f) => profiled(declared[f]));
3336
+ if (fields.length === 0) continue;
3337
+ const seen = new Map(fields.map((f) => [f, /* @__PURE__ */ new Set()]));
3338
+ const truncated = /* @__PURE__ */ new Set();
3339
+ let cursor;
3340
+ let rowsRead = 0;
3341
+ do {
3342
+ const page = await input.read(typeName, fields, cursor);
3343
+ rowsRead += page.rows.length;
3344
+ for (const row of page.rows) for (const f of fields) {
3345
+ if (truncated.has(f)) continue;
3346
+ const raw = row[f];
3347
+ const values = Array.isArray(raw) ? raw : [raw];
3348
+ const set = seen.get(f);
3349
+ for (const v of values) {
3350
+ if (typeof v !== "string" || v.length === 0) continue;
3351
+ set.add(v);
3352
+ if (set.size > maxDistinct) {
3353
+ truncated.add(f);
3354
+ break;
3355
+ }
3356
+ }
3357
+ }
3358
+ cursor = page.nextCursor;
3359
+ } while (cursor !== void 0 && truncated.size < fields.length && rowsRead < maxRows);
3360
+ const out = {};
3361
+ for (const f of [...fields].sort()) {
3362
+ const values = [...seen.get(f)].sort();
3363
+ const isTruncated = truncated.has(f);
3364
+ if (values.length === 0 && !isTruncated) continue;
3365
+ out[f] = {
3366
+ values: isTruncated ? values.slice(0, maxDistinct) : values,
3367
+ truncated: isTruncated
3368
+ };
3369
+ }
3370
+ types[typeName] = out;
3371
+ }
3372
+ return { types };
3373
+ }
3374
+ function profiled(def) {
3375
+ if (def.kind === "scalar") return def.type === "string" && def.indexed !== false;
3376
+ return def.kind === "list" && def.indexed === true && def.of.kind === "scalar" && def.of.type === "string";
3377
+ }
3378
+
3379
+ //#endregion
3380
+ //#region src/pack/service.ts
3381
+ /**
3382
+ * Packs are built under the CALLER's request: the profile reads distinct
3383
+ * values through `engine.query(frame, req)`, so row policy applies and a
3384
+ * pack can never disclose a value its caller could not read. Hence the
3385
+ * principal is part of the cache key.
3386
+ */
3387
+ var PackService = class {
3388
+ #opts;
3389
+ #cache = /* @__PURE__ */ new Map();
3390
+ #inflight = /* @__PURE__ */ new Map();
3391
+ #warned = /* @__PURE__ */ new Set();
3392
+ constructor(opts) {
3393
+ this.#opts = opts;
3394
+ }
3395
+ async get(ns, req) {
3396
+ const schemas = this.#opts.engine.federatedSchema();
3397
+ const schema = Object.hasOwn(schemas, ns) ? schemas[ns] : void 0;
3398
+ if (schema === void 0) return void 0;
3399
+ const now = (this.#opts.now ?? Date.now)();
3400
+ const ttl = this.#opts.ttlMs ?? 3e5;
3401
+ const key = `${ns}\u0000${schema.schemaVersion}\u0000${principalKey(req)}`;
3402
+ const hit = this.#cache.get(key);
3403
+ if (hit !== void 0 && now - hit.at < ttl) {
3404
+ this.#cache.delete(key);
3405
+ this.#cache.set(key, hit);
3406
+ return {
3407
+ pack: hit.pack,
3408
+ etag: hit.etag
3409
+ };
3410
+ }
3411
+ let pending = this.#inflight.get(key);
3412
+ if (pending === void 0) {
3413
+ pending = this.#build(ns, schema, req, now).finally(() => this.#inflight.delete(key));
3414
+ this.#inflight.set(key, pending);
3415
+ }
3416
+ const entry = await pending;
3417
+ this.#cache.delete(key);
3418
+ this.#cache.set(key, entry);
3419
+ const max = this.#opts.maxEntries ?? 256;
3420
+ while (this.#cache.size > max) {
3421
+ const oldest = this.#cache.keys().next().value;
3422
+ if (oldest === void 0) break;
3423
+ this.#cache.delete(oldest);
3424
+ }
3425
+ return {
3426
+ pack: entry.pack,
3427
+ etag: entry.etag
3428
+ };
3429
+ }
3430
+ async #build(ns, schema, req, now) {
3431
+ const { rulings, warnings } = readRulings(schema, own(this.#opts.rulings, ns));
3432
+ const warnKey = `${ns}\u0000${schema.schemaVersion}`;
3433
+ if (warnings.length > 0 && !this.#warned.has(warnKey)) {
3434
+ this.#warned.add(warnKey);
3435
+ (this.#opts.log ?? console.warn)(`substrate-nl: ${ns}: ${warnings.join("; ")}`);
3436
+ }
3437
+ const read = async (type, fields, cursor) => {
3438
+ const frameKey = `${ns}/${type}`;
3439
+ const env = await this.#opts.engine.query({ [frameKey]: {
3440
+ params: cursor !== void 0 ? { cursor } : {},
3441
+ fields: Object.fromEntries(fields.map((f) => [f, true]))
3442
+ } }, req);
3443
+ const rows = env.data?.[frameKey];
3444
+ const page = env._pagination?.[frameKey];
3445
+ return {
3446
+ rows: Array.isArray(rows) ? rows : [],
3447
+ nextCursor: page?.hasMore === true ? page.nextCursor : void 0
3448
+ };
3449
+ };
3450
+ const profile = await profileNamespace({
3451
+ schema,
3452
+ read
3453
+ });
3454
+ const pack = {
3455
+ ...buildNamespacePack({
3456
+ namespace: ns,
3457
+ schema,
3458
+ operators: this.#opts.engine.operators(ns) ?? {},
3459
+ profile
3460
+ }),
3461
+ rulings,
3462
+ warnings
3463
+ };
3464
+ return {
3465
+ pack,
3466
+ etag: `"${createHash("sha256").update(JSON.stringify(pack)).digest("hex").slice(0, 16)}"`,
3467
+ at: now
3468
+ };
3469
+ }
3470
+ };
3471
+ /**
3472
+ * The Identity canonicalised, less `expiresAt`: a custom row policy may key on
3473
+ * any claim (a tenant, say), so no other subset is safe to share a cached pack
3474
+ * across, while a token's expiry changes with every refresh.
3475
+ */
3476
+ function principalKey(req) {
3477
+ const id = req.identity;
3478
+ if (id === void 0) return "\0anon";
3479
+ const { expiresAt: _expiresAt, ...stable } = id;
3480
+ return JSON.stringify(canonical(stable));
3481
+ }
3482
+ function canonical(v) {
3483
+ if (Array.isArray(v)) return v.map(canonical);
3484
+ if (v !== null && typeof v === "object") return Object.fromEntries(Object.entries(v).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, x]) => [k, canonical(x)]));
3485
+ return v;
3486
+ }
3487
+
3488
+ //#endregion
3489
+ //#region src/ask/encode.ts
3490
+ function wireName(ev) {
3491
+ if (ev.event === "outcome") return [ev.outcome.kind, ev.outcome];
3492
+ const { event, ...rest } = ev;
3493
+ return [event, rest];
3494
+ }
3495
+ /** A length-prefixed JSON frame carrying `{ event, data }`, the client's `NlWireEvent`. */
3496
+ const frameBytes = (event, data) => encodeStreamFrame({
3497
+ event,
3498
+ data
3499
+ }, "json");
3500
+ const FRAMES_HEADERS = {
3501
+ "content-type": FRAMES_JSON_MIME,
3502
+ "cache-control": "no-store",
3503
+ "x-accel-buffering": "no"
3504
+ };
3505
+ function toEventStream(events, encode, onCancel, onError) {
3506
+ return new ReadableStream({
3507
+ async pull(controller) {
3508
+ try {
3509
+ const next = await events.next();
3510
+ if (next.done === true) return controller.close();
3511
+ const [name, data] = wireName(next.value);
3512
+ controller.enqueue(encode(name, data));
3513
+ } catch (err) {
3514
+ onError?.(err);
3515
+ controller.enqueue(encode("error", {
3516
+ code: "nl_engine_error",
3517
+ message: "NL query failed"
3518
+ }));
3519
+ controller.close();
3520
+ }
3521
+ },
3522
+ async cancel() {
3523
+ onCancel?.();
3524
+ await events.return(void 0);
3525
+ }
3526
+ });
3527
+ }
3528
+ async function toJson(events) {
3529
+ const trail = [];
3530
+ let outcome = null;
3531
+ for await (const ev of events) {
3532
+ trail.push(ev);
3533
+ if (ev.event === "outcome") outcome = ev.outcome;
3534
+ }
3535
+ return {
3536
+ outcome,
3537
+ trail
3538
+ };
3539
+ }
3540
+
3541
+ //#endregion
3542
+ //#region src/routes.ts
3543
+ const VARY = { vary: "authorization" };
3544
+ const engineFailure = (req, err, log) => {
3545
+ if (req.signal?.aborted === true) return { status: 499 };
3546
+ log(err);
3547
+ return jsonResponse(502, {
3548
+ error: "NL query failed",
3549
+ code: "nl_engine_error"
3550
+ });
3551
+ };
3552
+ const str = (v) => typeof v === "string" && v.length > 0;
3553
+ /** Longest question parsed; the same bound recall puts on its query text. */
3554
+ const MAX_QUESTION_CHARS = 8192;
3555
+ function askHandler(deps) {
3556
+ const log = deps.log ?? ((err) => console.error("substrate-nl:", err));
3557
+ return async (req) => {
3558
+ const parsed = parseJsonBody(req);
3559
+ if (!parsed.ok) return parsed.response;
3560
+ const body = parsed.value;
3561
+ if (body === null || typeof body !== "object" || Array.isArray(body)) return error400("body must be a JSON object: { namespace, question, project?, type?, asOf? }");
3562
+ if (!str(body.namespace)) return error400("body.namespace must be a non-empty string");
3563
+ if (!str(body.question)) return error400("body.question must be a non-empty string");
3564
+ if (body.question.length > MAX_QUESTION_CHARS) return error400(`body.question is longer than ${MAX_QUESTION_CHARS} characters`);
3565
+ for (const k of ["project", "type"]) if (body[k] !== void 0 && !str(body[k])) return error400(`body.${k} must be a non-empty string when given`);
3566
+ if (body.asOf !== void 0 && !validAsOf(body.asOf)) return jsonResponse(400, {
3567
+ error: "body.asOf must be an ISO-8601 date-time with an offset, e.g. 2026-10-02T12:00:00-05:00",
3568
+ code: "invalid_params"
3569
+ });
3570
+ const ask = {
3571
+ namespace: body.namespace,
3572
+ question: body.question,
3573
+ ...str(body.project) ? { project: body.project } : {},
3574
+ ...str(body.type) ? { type: body.type } : {},
3575
+ ...validAsOf(body.asOf) ? { asOf: body.asOf } : {}
3576
+ };
3577
+ let served;
3578
+ try {
3579
+ served = await deps.packs.get(ask.namespace, req);
3580
+ } catch (err) {
3581
+ return engineFailure(req, err, log);
3582
+ }
3583
+ if (served === void 0) return jsonResponse(404, {
3584
+ error: `unknown namespace '${ask.namespace}'`,
3585
+ code: "nl_unknown_namespace"
3586
+ });
3587
+ if (ask.type !== void 0 && !Object.hasOwn(served.pack.types, ask.type)) return error400(`unknown type '${ask.type}'`);
3588
+ const frames = framesEncodingFromAccept(req.headers.accept);
3589
+ if (frames === "pack") return jsonResponse(406, {
3590
+ error: `NL streams ${FRAMES_JSON_MIME} only`,
3591
+ code: "not_acceptable"
3592
+ });
3593
+ const events = runAsk(ask, req, {
3594
+ pack: served.pack,
3595
+ engine: deps.engine,
3596
+ ...deps.judge !== void 0 ? { judge: deps.judge } : {},
3597
+ ...deps.judgeTimeoutMs !== void 0 ? { judgeTimeoutMs: deps.judgeTimeoutMs } : {},
3598
+ ...deps.now !== void 0 ? { now: deps.now } : {}
3599
+ });
3600
+ if (frames === "json") return {
3601
+ status: 200,
3602
+ headers: FRAMES_HEADERS,
3603
+ body: toEventStream(events, frameBytes, void 0, log)
3604
+ };
3605
+ try {
3606
+ return jsonResponse(200, await toJson(events));
3607
+ } catch (err) {
3608
+ return engineFailure(req, err, log);
3609
+ }
3610
+ };
3611
+ }
3612
+ function packHandler(deps) {
3613
+ const log = deps.log ?? ((err) => console.error("substrate-nl:", err));
3614
+ return async (req) => {
3615
+ const ns = req.params.ns ?? "";
3616
+ let served;
3617
+ try {
3618
+ served = await deps.packs.get(ns, req);
3619
+ } catch (err) {
3620
+ return engineFailure(req, err, log);
3621
+ }
3622
+ if (served === void 0) return jsonResponse(404, {
3623
+ error: `unknown namespace '${ns}'`,
3624
+ code: "nl_unknown_namespace"
3625
+ });
3626
+ if (req.headers["if-none-match"] === served.etag) return {
3627
+ status: 304,
3628
+ headers: {
3629
+ etag: served.etag,
3630
+ ...VARY
3631
+ }
3632
+ };
3633
+ return jsonResponse(200, served.pack, {
3634
+ etag: served.etag,
3635
+ "cache-control": "private, no-cache",
3636
+ ...VARY
3637
+ });
3638
+ };
3639
+ }
3640
+
3641
+ //#endregion
3642
+ //#region src/plugin.ts
3643
+ /** The routes rely on `KernelRouteClaim.capability`, which every 1.x host honours. */
3644
+ const CONTRACT_VERSION = ">=1.0.0-alpha.0 <2.0.0";
3645
+ function createNlPlugin(cfg) {
3646
+ const packs = new PackService({
3647
+ engine: cfg.engine,
3648
+ ...cfg.rulings !== void 0 ? { rulings: cfg.rulings } : {},
3649
+ ...cfg.packTtlMs !== void 0 ? { ttlMs: cfg.packTtlMs } : {}
3650
+ });
3651
+ const deps = {
3652
+ engine: cfg.engine,
3653
+ packs,
3654
+ ...cfg.judge !== void 0 ? { judge: cfg.judge } : {},
3655
+ ...cfg.judgeTimeoutMs !== void 0 ? { judgeTimeoutMs: cfg.judgeTimeoutMs } : {}
3656
+ };
3657
+ return {
3658
+ name: "substrate-nl",
3659
+ contractVersion: CONTRACT_VERSION,
3660
+ kernelRoutes: [{
3661
+ path: "nl",
3662
+ method: "POST",
3663
+ handler: askHandler(deps),
3664
+ capability: "read"
3665
+ }, {
3666
+ path: "nl/pack/:ns",
3667
+ method: "GET",
3668
+ handler: packHandler(deps),
3669
+ capability: "read"
3670
+ }]
3671
+ };
3672
+ }
3673
+
3674
+ //#endregion
3675
+ //#region src/bootstrap.ts
3676
+ /**
3677
+ * Structured-config bootstrap for `@mnmal-ai/substrate-nl`.
3678
+ *
3679
+ * Operator-overridable (`<pluginDir>/substrate-nl.config.json`):
3680
+ * - `judge` optional; Ollama for the constrained judge. Absent = parser-only:
3681
+ * every escalation is an honest hand-off.
3682
+ * - `rulings` optional; per-namespace override merged over declared rulings.
3683
+ * - `packTtlMs` how long a served pack is reused. Default 300000.
3684
+ * Host-supplied (`hostDeps.nlEngine`): schema, operators and query access.
3685
+ */
3686
+ const JudgeSchema = z.object({
3687
+ baseUrl: z.url(),
3688
+ model: z.string().min(1),
3689
+ timeoutMs: z.number().int().positive().default(2e4)
3690
+ }).strict();
3691
+ const NlBootstrapConfigSchema = z.object({
3692
+ judge: JudgeSchema.optional(),
3693
+ rulings: z.record(z.string(), NamespaceRulingsSchema).optional(),
3694
+ packTtlMs: z.number().int().positive().default(3e5)
3695
+ }).strict();
3696
+ const bootstrap = defineBootstrap.kernel({
3697
+ schema: NlBootstrapConfigSchema,
3698
+ build: (config, deps) => createNlPlugin({
3699
+ engine: deps.nlEngine,
3700
+ packTtlMs: config.packTtlMs,
3701
+ ...config.judge !== void 0 ? {
3702
+ judge: new OllamaJudge(config.judge),
3703
+ judgeTimeoutMs: config.judge.timeoutMs
3704
+ } : {},
3705
+ ...config.rulings !== void 0 ? { rulings: config.rulings } : {}
3706
+ })
3707
+ });
3708
+
3709
+ //#endregion
3710
+ export { askHandler as a, profileNamespace as c, runAsk as d, parseWithJudge as f, readRulings as g, mergeRulings as h, createNlPlugin as i, buildNamespacePack as l, NamespaceRulingsSchema as m, bootstrap as n, packHandler as o, parseQuestion as p, CONTRACT_VERSION as r, PackService as s, NlBootstrapConfigSchema as t, OllamaJudge as u };