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

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